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
GoteoFoundation/goteo-api
goteoapi/auth/decorators.py
1
6707
# -*- coding: utf-8 -*- # # Currently this module only handles an implicit oauth authentication. # # ---------------------------------------- # Access token authorization # ---------------------------------------- # # With Basic HTTP Auth: # # HTTP AUTH # User owner | ---user/password--> | /login # | <--access_token---- | # # Or with API key (which is valid also for public requests) # # HTTP AUTH # User owner | ---user/api_key---> | /login # | <--access_token---- | # # ---------------------------------------- # Access to public protected resources # ---------------------------------------- # # HEADER Authorize: Bearer # User owner | ---access_token---> | /projects/ # | <-------JSON------- | # # or with API key (legacy): # # HTTP AUTH # User owner | ---user/api_key---> | /projects/ # | <-------JSON------- | # # ---------------------------------------- # Access to private/user-only protected resources: # ---------------------------------------- # # HEADER Authorize: Bearer # User owner | ---access_token---> | /projects/ # | <-------JSON------- | # from datetime import datetime as dtdatetime from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from itsdangerous import BadSignature, SignatureExpired from functools import update_wrapper from flask import g, request, jsonify from netaddr import IPSet, AddrFormatError, IPAddress from sqlalchemy.orm.exc import NoResultFound from .. import app from ..users.models import User, UserApi def generate_auth_token(authid, expiration=app.config['ACCESS_TOKEN_DURATION']): s = Serializer(app.secret_key, expires_in=expiration) return s.dumps({'id': authid}) def verify_auth_token(token): s = Serializer(app.secret_key) try: data = s.loads(token) except SignatureExpired: return 'Expired token' # valid token, but expired except BadSignature: return 'Invalid token' # invalid token g.loginId = data['id'] return True def check_builtin_auth(username, password): """Checks username & password authentication""" # Personal token workflow # try some built-in auth first origin = request.headers.get('Origin', '*') remote_ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr) if (app.config['USERS'] and username in app.config['USERS'] and 'password' in app.config['USERS'][username]): user = app.config['USERS'][username] if user['password'] == password: if 'remotes' in user: try: if IPAddress(remote_ip) not in IPSet(user['remotes']): return 'Not valid user for this IP' except AddrFormatError as e: if(app.debug): return e return 'Malformed remote IP' if 'cors' in user: if origin not in user['cors']: return 'Origin header not valid' g.loginId = '#' + username return True return False def check_apikey_auth(username, password): """Checks username & API-key authentication""" # Try the user-id-key values in sql try: userapi = UserApi.query.filter(UserApi.user_id == username, UserApi.key == password).one() if (userapi.expiration_date is not None and userapi.expiration_date <= dtdatetime.today()): return 'API Key expired' user = User.query.filter(User.id == userapi.user_id).one() except NoResultFound: return 'Invalid API Key or secret' g.loginId = user.id return True def check_user_auth(username, password): """Checks username & password authentication""" # Try the user-id-key values in sql user = User.get(username) if user and user.verify_password(password): g.loginId = user.id return True return 'Invalid username or password' def requires_auth(scope='public'): """ scope: - public: Either "Bearer" token or a pair key/secret can be used to gain access to the resource - access_token: Either user/password or key/secret can be used to gain access. The endpoint using this kind of auth should return the "Bearer" token - private: Only "Bearer" token will be accepted as authorization """ def decorator(f): def wrapped_function(*args, **kwargs): if not app.config['AUTH_ENABLED'] and scope == 'public': return f(*args, **kwargs) # Bearer Auth ok = None auth = request.headers.get('Authorization') if auth and 'Bearer' in auth: # Check bearer ok = verify_auth_token(auth[7:]) if ok is True: user = User.query.get(g.loginId) if isinstance(user, User): g.user = user if scope == 'access_token': ok = 'Access token cannot be used to refresh tokens' else: # Basic Auth auth = request.authorization msg = ("This resource requires authorization. " "More info in http://developers.goteo.org/") if auth: msg = 'Invalid access method or wrong credentials' # normal user/password can only be used to # obtain access_tokens if scope == 'access_token': ok = check_user_auth(auth.username, auth.password) if ok is not True: ok = check_apikey_auth(auth.username, auth.password) if ok is not True: ok = check_builtin_auth(auth.username, auth.password) # Check scope for non public resources if (ok is True and scope not in ('public', 'access_token') and not hasattr(g, 'user')): ok = 'Use a proper access token to access this resource' if ok is True: return f(*args, **kwargs) if ok is not False and ok is not None: msg = 'Access denied: ' + str(ok) resp = jsonify(error=401, message=msg) resp.status_code = 401 resp.headers.add('WWW-Authenticate', 'Basic realm="Goteo API"') return resp return update_wrapper(wrapped_function, f) return decorator
agpl-3.0
jaggu303619/asylum-v2.0
openerp/addons/edi/models/edi.py
16
32166
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (c) 2011-2012 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/>. # ############################################################################## import base64 import hashlib import simplejson as json import logging import re import time import urllib2 import openerp import openerp.release as release import openerp.netsvc as netsvc from openerp.osv import osv, fields from openerp.tools.translate import _ from openerp.tools.safe_eval import safe_eval as eval _logger = logging.getLogger(__name__) EXTERNAL_ID_PATTERN = re.compile(r'^([^.:]+)(?::([^.]+))?\.(\S+)$') EDI_VIEW_WEB_URL = '%s/edi/view?db=%s&token=%s' EDI_PROTOCOL_VERSION = 1 # arbitrary ever-increasing version number EDI_GENERATOR = 'OpenERP ' + release.major_version EDI_GENERATOR_VERSION = release.version_info def split_external_id(ext_id): match = EXTERNAL_ID_PATTERN.match(ext_id) assert match, \ _("'%s' is an invalid external ID") % (ext_id) return {'module': match.group(1), 'db_uuid': match.group(2), 'id': match.group(3), 'full': match.group(0)} def safe_unique_id(database_id, model, record_id): """Generate a unique string to represent a (database_uuid,model,record_id) pair without being too long, and with a very low probability of collisions. """ msg = "%s-%s-%s-%s" % (time.time(), database_id, model, record_id) digest = hashlib.sha1(msg).digest() # fold the sha1 20 bytes digest to 9 bytes digest = ''.join(chr(ord(x) ^ ord(y)) for (x,y) in zip(digest[:9], digest[9:-2])) # b64-encode the 9-bytes folded digest to a reasonable 12 chars ASCII ID digest = base64.urlsafe_b64encode(digest) return '%s-%s' % (model.replace('.','_'), digest) def last_update_for(record): """Returns the last update timestamp for the given record, if available, otherwise False """ if record._model._log_access: record_log = record.perm_read()[0] return record_log.get('write_date') or record_log.get('create_date') or False return False class edi(osv.AbstractModel): _name = 'edi.edi' _description = 'EDI Subsystem' def new_edi_token(self, cr, uid, record): """Return a new, random unique token to identify this model record, and to be used as token when exporting it as an EDI document. :param browse_record record: model record for which a token is needed """ db_uuid = self.pool.get('ir.config_parameter').get_param(cr, uid, 'database.uuid') edi_token = hashlib.sha256('%s-%s-%s-%s' % (time.time(), db_uuid, record._name, record.id)).hexdigest() return edi_token def serialize(self, edi_documents): """Serialize the given EDI document structures (Python dicts holding EDI data), using JSON serialization. :param [dict] edi_documents: list of EDI document structures to serialize :return: UTF-8 encoded string containing the serialized document """ serialized_list = json.dumps(edi_documents) return serialized_list def generate_edi(self, cr, uid, records, context=None): """Generates a final EDI document containing the EDI serialization of the given records, which should all be instances of a Model that has the :meth:`~.edi` mixin. The document is not saved in the database. :param list(browse_record) records: records to export as EDI :return: UTF-8 encoded string containing the serialized records """ edi_list = [] for record in records: record_model_obj = self.pool.get(record._name) edi_list += record_model_obj.edi_export(cr, uid, [record], context=context) return self.serialize(edi_list) def load_edi(self, cr, uid, edi_documents, context=None): """Import the given EDI document structures into the system, using :meth:`~.import_edi`. :param edi_documents: list of Python dicts containing the deserialized version of EDI documents :return: list of (model, id, action) tuple containing the model and database ID of all records that were imported in the system, plus a suggested action definition dict for displaying each document. """ ir_module = self.pool.get('ir.module.module') res = [] for edi_document in edi_documents: module = edi_document.get('__import_module') or edi_document.get('__module') assert module, 'a `__module` or `__import_module` attribute is required in each EDI document.' if module != 'base' and not ir_module.search(cr, uid, [('name','=',module),('state','=','installed')]): raise osv.except_osv(_('Missing Application.'), _("The document you are trying to import requires the OpenERP `%s` application. " "You can install it by connecting as the administrator and opening the configuration assistant.")%(module,)) model = edi_document.get('__import_model') or edi_document.get('__model') assert model, 'a `__model` or `__import_model` attribute is required in each EDI document.' model_obj = self.pool.get(model) assert model_obj, 'model `%s` cannot be found, despite module `%s` being available - '\ 'this EDI document seems invalid or unsupported.' % (model,module) record_id = model_obj.edi_import(cr, uid, edi_document, context=context) record_action = model_obj._edi_record_display_action(cr, uid, record_id, context=context) res.append((model, record_id, record_action)) return res def deserialize(self, edi_documents_string): """Return deserialized version of the given EDI Document string. :param str|unicode edi_documents_string: UTF-8 string (or unicode) containing JSON-serialized EDI document(s) :return: Python object representing the EDI document(s) (usually a list of dicts) """ return json.loads(edi_documents_string) def import_edi(self, cr, uid, edi_document=None, edi_url=None, context=None): """Import a JSON serialized EDI Document string into the system, first retrieving it from the given ``edi_url`` if provided. :param str|unicode edi: UTF-8 string or unicode containing JSON-serialized EDI Document to import. Must not be provided if ``edi_url`` is given. :param str|unicode edi_url: URL where the EDI document (same format as ``edi``) may be retrieved, without authentication. """ if edi_url: assert not edi_document, 'edi must not be provided if edi_url is given.' edi_document = urllib2.urlopen(edi_url).read() assert edi_document, 'EDI Document is empty!' edi_documents = self.deserialize(edi_document) return self.load_edi(cr, uid, edi_documents, context=context) class EDIMixin(object): """Mixin class for Model objects that want be exposed as EDI documents. Classes that inherit from this mixin class should override the ``edi_import()`` and ``edi_export()`` methods to implement their specific behavior, based on the primitives provided by this mixin.""" def _edi_requires_attributes(self, attributes, edi): model_name = edi.get('__imported_model') or edi.get('__model') or self._name for attribute in attributes: assert edi.get(attribute),\ 'Attribute `%s` is required in %s EDI documents.' % (attribute, model_name) # private method, not RPC-exposed as it creates ir.model.data entries as # SUPERUSER based on its parameters def _edi_external_id(self, cr, uid, record, existing_id=None, existing_module=None, context=None): """Generate/Retrieve unique external ID for ``record``. Each EDI record and each relationship attribute in it is identified by a unique external ID, which includes the database's UUID, as a way to refer to any record within any OpenERP instance, without conflict. For OpenERP records that have an existing "External ID" (i.e. an entry in ir.model.data), the EDI unique identifier for this record will be made of "%s:%s:%s" % (module, database UUID, ir.model.data ID). The database's UUID MUST NOT contain a colon characters (this is guaranteed by the UUID algorithm). For records that have no existing ir.model.data entry, a new one will be created during the EDI export. It is recommended that the generated external ID contains a readable reference to the record model, plus a unique value that hides the database ID. If ``existing_id`` is provided (because it came from an import), it will be used instead of generating a new one. If ``existing_module`` is provided (because it came from an import), it will be used instead of using local values. :param browse_record record: any browse_record needing an EDI external ID :param string existing_id: optional existing external ID value, usually coming from a just-imported EDI record, to be used instead of generating a new one :param string existing_module: optional existing module name, usually in the format ``module:db_uuid`` and coming from a just-imported EDI record, to be used instead of local values :return: the full unique External ID to use for record """ ir_model_data = self.pool.get('ir.model.data') db_uuid = self.pool.get('ir.config_parameter').get_param(cr, uid, 'database.uuid') ext_id = record.get_external_id()[record.id] if not ext_id: ext_id = existing_id or safe_unique_id(db_uuid, record._name, record.id) # ID is unique cross-db thanks to db_uuid (already included in existing_module) module = existing_module or "%s:%s" % (record._original_module, db_uuid) _logger.debug("%s: Generating new external ID `%s.%s` for %r.", self._name, module, ext_id, record) ir_model_data.create(cr, openerp.SUPERUSER_ID, {'name': ext_id, 'model': record._name, 'module': module, 'res_id': record.id}) else: module, ext_id = ext_id.split('.') if not ':' in module: # this record was not previously EDI-imported if not module == record._original_module: # this could happen for data records defined in a module that depends # on the module that owns the model, e.g. purchase defines # product.pricelist records. _logger.debug('Mismatching module: expected %s, got %s, for %s.', module, record._original_module, record) # ID is unique cross-db thanks to db_uuid module = "%s:%s" % (module, db_uuid) return '%s.%s' % (module, ext_id) def _edi_record_display_action(self, cr, uid, id, context=None): """Returns an appropriate action definition dict for displaying the record with ID ``rec_id``. :param int id: database ID of record to display :return: action definition dict """ return {'type': 'ir.actions.act_window', 'view_mode': 'form,tree', 'view_type': 'form', 'res_model': self._name, 'res_id': id} def edi_metadata(self, cr, uid, records, context=None): """Return a list containing the boilerplate EDI structures for exporting ``records`` as EDI, including the metadata fields The metadata fields always include:: { '__model': 'some.model', # record model '__module': 'module', # require module '__id': 'module:db-uuid:model.id', # unique global external ID for the record '__last_update': '2011-01-01 10:00:00', # last update date in UTC! '__version': 1, # EDI spec version '__generator' : 'OpenERP', # EDI generator '__generator_version' : [6,1,0], # server version, to check compatibility. '__attachments_': } :param list(browse_record) records: records to export :return: list of dicts containing boilerplate EDI metadata for each record, at the corresponding index from ``records``. """ ir_attachment = self.pool.get('ir.attachment') results = [] for record in records: ext_id = self._edi_external_id(cr, uid, record, context=context) edi_dict = { '__id': ext_id, '__last_update': last_update_for(record), '__model' : record._name, '__module' : record._original_module, '__version': EDI_PROTOCOL_VERSION, '__generator': EDI_GENERATOR, '__generator_version': EDI_GENERATOR_VERSION, } attachment_ids = ir_attachment.search(cr, uid, [('res_model','=', record._name), ('res_id', '=', record.id)]) if attachment_ids: attachments = [] for attachment in ir_attachment.browse(cr, uid, attachment_ids, context=context): attachments.append({ 'name' : attachment.name, 'content': attachment.datas, # already base64 encoded! 'file_name': attachment.datas_fname, }) edi_dict.update(__attachments=attachments) results.append(edi_dict) return results def edi_m2o(self, cr, uid, record, context=None): """Return a m2o EDI representation for the given record. The EDI format for a many2one is:: ['unique_external_id', 'Document Name'] """ edi_ext_id = self._edi_external_id(cr, uid, record, context=context) relation_model = record._model name = relation_model.name_get(cr, uid, [record.id], context=context) name = name and name[0][1] or False return [edi_ext_id, name] def edi_o2m(self, cr, uid, records, edi_struct=None, context=None): """Return a list representing a O2M EDI relationship containing all the given records, according to the given ``edi_struct``. This is basically the same as exporting all the record using :meth:`~.edi_export` with the given ``edi_struct``, and wrapping the results in a list. Example:: [ # O2M fields would be a list of dicts, with their { '__id': 'module:db-uuid.id', # own __id. '__last_update': 'iso date', # update date 'name': 'some name', #... }, # ... ], """ result = [] for record in records: result += record._model.edi_export(cr, uid, [record], edi_struct=edi_struct, context=context) return result def edi_m2m(self, cr, uid, records, context=None): """Return a list representing a M2M EDI relationship directed towards all the given records. This is basically the same as exporting all the record using :meth:`~.edi_m2o` and wrapping the results in a list. Example:: # M2M fields are exported as a list of pairs, like a list of M2O values [ ['module:db-uuid.id1', 'Task 01: bla bla'], ['module:db-uuid.id2', 'Task 02: bla bla'] ] """ return [self.edi_m2o(cr, uid, r, context=context) for r in records] def edi_export(self, cr, uid, records, edi_struct=None, context=None): """Returns a list of dicts representing EDI documents containing the records, and matching the given ``edi_struct``, if provided. :param edi_struct: if provided, edi_struct should be a dictionary with a skeleton of the fields to export. Basic fields can have any key as value, but o2m values should have a sample skeleton dict as value, to act like a recursive export. For example, for a res.partner record:: edi_struct: { 'name': True, 'company_id': True, 'address': { 'name': True, 'street': True, } } Any field not specified in the edi_struct will not be included in the exported data. Fields with no value (False) will be omitted in the EDI struct. If edi_struct is omitted, no fields will be exported """ if edi_struct is None: edi_struct = {} fields_to_export = edi_struct.keys() results = [] for record in records: edi_dict = self.edi_metadata(cr, uid, [record], context=context)[0] for field in fields_to_export: column = self._all_columns[field].column value = getattr(record, field) if not value and value not in ('', 0): continue elif column._type == 'many2one': value = self.edi_m2o(cr, uid, value, context=context) elif column._type == 'many2many': value = self.edi_m2m(cr, uid, value, context=context) elif column._type == 'one2many': value = self.edi_o2m(cr, uid, value, edi_struct=edi_struct.get(field, {}), context=context) edi_dict[field] = value results.append(edi_dict) return results def _edi_get_object_by_name(self, cr, uid, name, model_name, context=None): model = self.pool.get(model_name) search_results = model.name_search(cr, uid, name, operator='=', context=context) if len(search_results) == 1: return model.browse(cr, uid, search_results[0][0], context=context) return False def _edi_generate_report_attachment(self, cr, uid, record, context=None): """Utility method to generate the first PDF-type report declared for the current model with ``usage`` attribute set to ``default``. This must be called explicitly by models that need it, usually at the beginning of ``edi_export``, before the call to ``super()``.""" ir_actions_report = self.pool.get('ir.actions.report.xml') matching_reports = ir_actions_report.search(cr, uid, [('model','=',self._name), ('report_type','=','pdf'), ('usage','=','default')]) if matching_reports: report = ir_actions_report.browse(cr, uid, matching_reports[0]) report_service = 'report.' + report.report_name service = netsvc.LocalService(report_service) (result, format) = service.create(cr, uid, [record.id], {'model': self._name}, context=context) eval_context = {'time': time, 'object': record} if not report.attachment or not eval(report.attachment, eval_context): # no auto-saving of report as attachment, need to do it manually result = base64.b64encode(result) file_name = record.name_get()[0][1] file_name = re.sub(r'[^a-zA-Z0-9_-]', '_', file_name) file_name += ".pdf" self.pool.get('ir.attachment').create(cr, uid, { 'name': file_name, 'datas': result, 'datas_fname': file_name, 'res_model': self._name, 'res_id': record.id, 'type': 'binary' }, context=context) def _edi_import_attachments(self, cr, uid, record_id, edi, context=None): ir_attachment = self.pool.get('ir.attachment') for attachment in edi.get('__attachments', []): # check attachment data is non-empty and valid file_data = None try: file_data = base64.b64decode(attachment.get('content')) except TypeError: pass assert file_data, 'Incorrect/Missing attachment file content.' assert attachment.get('name'), 'Incorrect/Missing attachment name.' assert attachment.get('file_name'), 'Incorrect/Missing attachment file name.' assert attachment.get('file_name'), 'Incorrect/Missing attachment file name.' ir_attachment.create(cr, uid, {'name': attachment['name'], 'datas_fname': attachment['file_name'], 'res_model': self._name, 'res_id': record_id, # should be pure 7bit ASCII 'datas': str(attachment['content']), }, context=context) def _edi_get_object_by_external_id(self, cr, uid, external_id, model, context=None): """Returns browse_record representing object identified by the model and external_id, or None if no record was found with this external id. :param external_id: fully qualified external id, in the EDI form ``module:db_uuid:identifier``. :param model: model name the record belongs to. """ ir_model_data = self.pool.get('ir.model.data') # external_id is expected to have the form: ``module:db_uuid:model.random_name`` ext_id_members = split_external_id(external_id) db_uuid = self.pool.get('ir.config_parameter').get_param(cr, uid, 'database.uuid') module = ext_id_members['module'] ext_id = ext_id_members['id'] modules = [] ext_db_uuid = ext_id_members['db_uuid'] if ext_db_uuid: modules.append('%s:%s' % (module, ext_id_members['db_uuid'])) if ext_db_uuid is None or ext_db_uuid == db_uuid: # local records may also be registered without the db_uuid modules.append(module) data_ids = ir_model_data.search(cr, uid, [('model','=',model), ('name','=',ext_id), ('module','in',modules)]) if data_ids: model = self.pool.get(model) data = ir_model_data.browse(cr, uid, data_ids[0], context=context) if model.exists(cr, uid, [data.res_id]): return model.browse(cr, uid, data.res_id, context=context) # stale external-id, cleanup to allow re-import, as the corresponding record is gone ir_model_data.unlink(cr, 1, [data_ids[0]]) def edi_import_relation(self, cr, uid, model, value, external_id, context=None): """Imports a M2O/M2M relation EDI specification ``[external_id,value]`` for the given model, returning the corresponding database ID: * First, checks if the ``external_id`` is already known, in which case the corresponding database ID is directly returned, without doing anything else; * If the ``external_id`` is unknown, attempts to locate an existing record with the same ``value`` via name_search(). If found, the given external_id will be assigned to this local record (in addition to any existing one) * If previous steps gave no result, create a new record with the given value in the target model, assign it the given external_id, and return the new database ID :param str value: display name of the record to import :param str external_id: fully-qualified external ID of the record :return: database id of newly-imported or pre-existing record """ _logger.debug("%s: Importing EDI relationship [%r,%r]", model, external_id, value) target = self._edi_get_object_by_external_id(cr, uid, external_id, model, context=context) need_new_ext_id = False if not target: _logger.debug("%s: Importing EDI relationship [%r,%r] - ID not found, trying name_get.", self._name, external_id, value) target = self._edi_get_object_by_name(cr, uid, value, model, context=context) need_new_ext_id = True if not target: _logger.debug("%s: Importing EDI relationship [%r,%r] - name not found, creating it.", self._name, external_id, value) # also need_new_ext_id here, but already been set above model = self.pool.get(model) res_id, _ = model.name_create(cr, uid, value, context=context) target = model.browse(cr, uid, res_id, context=context) else: _logger.debug("%s: Importing EDI relationship [%r,%r] - record already exists with ID %s, using it", self._name, external_id, value, target.id) if need_new_ext_id: ext_id_members = split_external_id(external_id) # module name is never used bare when creating ir.model.data entries, in order # to avoid being taken as part of the module's data, and cleanup up at next update module = "%s:%s" % (ext_id_members['module'], ext_id_members['db_uuid']) # create a new ir.model.data entry for this value self._edi_external_id(cr, uid, target, existing_id=ext_id_members['id'], existing_module=module, context=context) return target.id def edi_import(self, cr, uid, edi, context=None): """Imports a dict representing an EDI document into the system. :param dict edi: EDI document to import :return: the database ID of the imported record """ assert self._name == edi.get('__import_model') or \ ('__import_model' not in edi and self._name == edi.get('__model')), \ "EDI Document Model and current model do not match: '%s' (EDI) vs '%s' (current)." % \ (edi.get('__model'), self._name) # First check the record is now already known in the database, in which case it is ignored ext_id_members = split_external_id(edi['__id']) existing = self._edi_get_object_by_external_id(cr, uid, ext_id_members['full'], self._name, context=context) if existing: _logger.info("'%s' EDI Document with ID '%s' is already known, skipping import!", self._name, ext_id_members['full']) return existing.id record_values = {} o2m_todo = {} # o2m values are processed after their parent already exists for field_name, field_value in edi.iteritems(): # skip metadata and empty fields if field_name.startswith('__') or field_value is None or field_value is False: continue field_info = self._all_columns.get(field_name) if not field_info: _logger.warning('Ignoring unknown field `%s` when importing `%s` EDI document.', field_name, self._name) continue field = field_info.column # skip function/related fields if isinstance(field, fields.function) and not field._fnct_inv: _logger.warning("Unexpected function field value is found in '%s' EDI document: '%s'." % (self._name, field_name)) continue relation_model = field._obj if field._type == 'many2one': record_values[field_name] = self.edi_import_relation(cr, uid, relation_model, field_value[1], field_value[0], context=context) elif field._type == 'many2many': record_values[field_name] = [self.edi_import_relation(cr, uid, relation_model, m2m_value[1], m2m_value[0], context=context) for m2m_value in field_value] elif field._type == 'one2many': # must wait until parent report is imported, as the parent relationship # is often required in o2m child records o2m_todo[field_name] = field_value else: record_values[field_name] = field_value module_ref = "%s:%s" % (ext_id_members['module'], ext_id_members['db_uuid']) record_id = self.pool.get('ir.model.data')._update(cr, uid, self._name, module_ref, record_values, xml_id=ext_id_members['id'], context=context) record_display, = self.name_get(cr, uid, [record_id], context=context) # process o2m values, connecting them to their parent on-the-fly for o2m_field, o2m_value in o2m_todo.iteritems(): field = self._all_columns[o2m_field].column dest_model = self.pool.get(field._obj) for o2m_line in o2m_value: # link to parent record: expects an (ext_id, name) pair o2m_line[field._fields_id] = (ext_id_members['full'], record_display[1]) dest_model.edi_import(cr, uid, o2m_line, context=context) # process the attachments, if any self._edi_import_attachments(cr, uid, record_id, edi, context=context) return record_id # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
nck0405/MyOwn
modules/templates/NYC/controllers.py
8
27529
# -*- coding: utf-8 -*- from gluon import * from s3 import S3CustomController, S3DataTable, S3Method, s3_request THEME = "NYC" # ============================================================================= class index(S3CustomController): """ Custom Home Page """ def __call__(self): output = {} T = current.T s3 = current.response.s3 auth = current.auth settings = current.deployment_settings roles = current.session.s3.roles system_roles = auth.get_system_roles() # Allow editing of page content from browser using CMS module if settings.has_module("cms"): ADMIN = system_roles.ADMIN in roles s3db = current.s3db table = s3db.cms_post ltable = s3db.cms_post_module module = "default" resource = "index" query = (ltable.module == module) & \ ((ltable.resource == None) | \ (ltable.resource == resource)) & \ (ltable.post_id == table.id) & \ (table.deleted != True) item = current.db(query).select(table.id, table.body, limitby=(0, 1)).first() if item: if ADMIN: item = DIV(XML(item.body), BR(), A(current.T("Edit"), _href=URL(c="cms", f="post", args=[item.id, "update"]), _class="action-btn")) else: item = DIV(XML(item.body)) elif ADMIN: if s3.crud.formstyle == "bootstrap": _class = "btn" else: _class = "action-btn" item = A(T("Edit"), _href=URL(c="cms", f="post", args="create", vars={"module": module, "resource": resource }), _class="%s cms-edit" % _class) else: item = "" else: item = "" output["item"] = item # Login/Registration forms self_registration = settings.get_security_registration_visible() registered = False login_form = None login_div = None register_form = None register_div = None # Check logged in and permissions if system_roles.AUTHENTICATED not in roles: login_buttons = DIV(A(T("Login"), _id="show-login", _class="tiny secondary button"), _id="login-buttons" ) # @ToDo: Move JS to static script = ''' $('#show-intro').click(function(e){ e.preventDefault() $('#intro').slideDown(400, function() { $('#login_box').hide() }); }) $('#show-login').click(function(e){ e.preventDefault() $('#login_form').show() $('#register_form').hide() $('#login_box').show() $('#intro').slideUp() })''' s3.jquery_ready.append(script) # This user isn't yet logged-in if current.request.cookies.has_key("registered"): # This browser has logged-in before registered = True if self_registration is True: # Provide a Registration box on front page login_buttons.append(A(T("Register"), _id="show-register", _class="tiny secondary button", # @ToDo: Move to CSS _style="margin-left:5px")) script = ''' $('#show-register').click(function(e){ e.preventDefault() $('#login_form').hide() $('#register_form').show() $('#login_box').show() $('#intro').slideUp() })''' s3.jquery_ready.append(script) register_form = auth.register() register_div = DIV(H3(T("Register")), P(XML(T("If you would like to help, then please %(sign_up_now)s") % \ dict(sign_up_now=B(T("sign-up now")))))) register_script = ''' $('#register-btn').click(function(e){ e.preventDefault() $('#register_form').show() $('#login_form').hide() }) $('#login-btn').click(function(e){ e.preventDefault() $('#register_form').hide() $('#login_form').show() })''' s3.jquery_ready.append(register_script) # Provide a login box on front page auth.messages.submit_button = T("Login") login_form = auth.login(inline=True) login_div = DIV(H3(T("Login")), P(XML(T("Registered users can %(login)s to access the system") % \ dict(login=B(T("login")))))) else: login_buttons = "" output["login_buttons"] = login_buttons output["self_registration"] = self_registration output["registered"] = registered output["login_div"] = login_div output["login_form"] = login_form output["register_div"] = register_div output["register_form"] = register_form output["items"] = network()() self._view(THEME, "index.html") return output # ----------------------------------------------------------------------------- class network(): """ Function to handle pagination for the network list on the homepage """ @staticmethod def __call__(): request = current.request get_vars = request.get_vars representation = request.extension resource = current.s3db.resource("org_group") totalrows = resource.count() display_start = int(get_vars.displayStart) if get_vars.displayStart else 0 display_length = int(get_vars.pageLength) if get_vars.pageLength else 10 limit = 4 * display_length list_fields = ("id", "name", "mission", "website", "meetings", ) default_orderby = orderby = "org_group.name asc" if representation == "aadata": query, orderby, left = resource.datatable_filter(list_fields, get_vars) if orderby is None: orderby = default_orderby if query: resource.add_filter(query) data = resource.select(list_fields, start=display_start, limit=limit, orderby=orderby, count=True, represent=True) filteredrows = data["numrows"] rfields = data["rfields"] data = data["rows"] dt = S3DataTable(rfields, data) dt.defaultActionButtons(resource) current.response.s3.no_formats = True if representation == "html": items = dt.html(totalrows, totalrows, "org_dt", dt_ajax_url=URL(c="default", f="index", args="network", extension="aadata", vars={"id": "org_dt"}, ), dt_pageLength=display_length, dt_pagination="true", ) elif representation == "aadata": draw = get_vars.get("draw") if draw: draw = int(draw) items = dt.json(totalrows, filteredrows, "org_dt", draw) else: from gluon.http import HTTP raise HTTP(415, ERROR.BAD_FORMAT) return items # ============================================================================= class contact(S3CustomController): """ Contact Form @ToDo: i18n if-required """ def __call__(self): request = current.request response = current.response s3 = response.s3 settings = current.deployment_settings if request.env.request_method == "POST": # Processs Form vars = request.post_vars result = current.msg.send_email(to=settings.get_mail_approver(), subject=vars.subject, message=vars.message, reply_to=vars.address, ) if result: response.confirmation = "Thankyou for your message - we'll be in touch shortly" T = current.T # Allow editing of page content from browser using CMS module if settings.has_module("cms"): ADMIN = current.auth.get_system_roles().ADMIN in \ current.session.s3.roles s3db = current.s3db table = s3db.cms_post ltable = s3db.cms_post_module module = "default" resource = "contact" query = (ltable.module == module) & \ ((ltable.resource == None) | \ (ltable.resource == resource)) & \ (ltable.post_id == table.id) & \ (table.deleted != True) item = current.db(query).select(table.id, table.body, limitby=(0, 1)).first() if item: if ADMIN: item = DIV(XML(item.body), BR(), A(T("Edit"), _href=URL(c="cms", f="post", args=[item.id, "update"]), _class="action-btn")) else: item = DIV(XML(item.body)) elif ADMIN: if s3.crud.formstyle == "bootstrap": _class = "btn" else: _class = "action-btn" item = A(T("Edit"), _href=URL(c="cms", f="post", args="create", vars={"module": module, "resource": resource }), _class="%s cms-edit" % _class) else: item = "" else: item = "" form = FORM(TABLE( TR(LABEL("Your name:", SPAN(" *", _class="req"), _for="name")), TR(INPUT(_name="name", _type="text", _size=62, _maxlength="255")), TR(LABEL("Your e-mail address:", SPAN(" *", _class="req"), _for="address")), TR(INPUT(_name="address", _type="text", _size=62, _maxlength="255")), TR(LABEL("Subject:", SPAN(" *", _class="req"), _for="subject")), TR(INPUT(_name="subject", _type="text", _size=62, _maxlength="255")), TR(LABEL("Message:", SPAN(" *", _class="req"), _for="name")), TR(TEXTAREA(_name="message", _class="resizable", _rows=5, _cols=62)), TR(INPUT(_type="submit", _value="Send e-mail")), ), _id="mailform" ) if s3.cdn: if s3.debug: s3.scripts.append("http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js") else: s3.scripts.append("http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js") else: if s3.debug: s3.scripts.append("/%s/static/scripts/jquery.validate.js" % request.application) else: s3.scripts.append("/%s/static/scripts/jquery.validate.min.js" % request.application) # @ToDo: Move to static with i18n s3.jquery_ready.append( '''$('#mailform').validate({ errorClass:'req', rules:{ name:{ required:true }, subject:{ required:true }, message:{ required:true }, name:{ required:true }, address: { required:true, email:true } }, messages:{ name:"Enter your name", subject:"Enter a subject", message:"Enter a message", address:{ required:"Please enter a valid email address", email:"Please enter a valid email address" } }, errorPlacement:function(error,element){ error.appendTo(element.parents('tr').prev().children()) }, submitHandler:function(form){ form.submit() } })''') # @ToDo: Move to static s3.jquery_ready.append( '''$('textarea.resizable:not(.textarea-processed)').each(function() { // Avoid non-processed teasers. if ($(this).is(('textarea.teaser:not(.teaser-processed)'))) { return false; } var textarea = $(this).addClass('textarea-processed'), staticOffset = null; // When wrapping the text area, work around an IE margin bug. See: // http://jaspan.com/ie-inherited-margin-bug-form-elements-and-haslayout $(this).wrap('<div class="resizable-textarea"><span></span></div>') .parent().append($('<div class="grippie"></div>').mousedown(startDrag)); var grippie = $('div.grippie', $(this).parent())[0]; grippie.style.marginRight = (grippie.offsetWidth - $(this)[0].offsetWidth) +'px'; function startDrag(e) { staticOffset = textarea.height() - e.pageY; textarea.css('opacity', 0.25); $(document).mousemove(performDrag).mouseup(endDrag); return false; } function performDrag(e) { textarea.height(Math.max(32, staticOffset + e.pageY) + 'px'); return false; } function endDrag(e) { $(document).unbind("mousemove", performDrag).unbind("mouseup", endDrag); textarea.css('opacity', 1); } });''') response.title = "Contact | NYC:Prepared" self._view(THEME, "contact.html") return dict(form=form, item=item, ) # ============================================================================= class register(S3CustomController): """ Registration Form """ def __call__(self): auth = current.auth response = current.response # Allow editing of page content from browser using CMS module ADMIN = auth.get_system_roles().ADMIN in \ current.session.s3.roles s3db = current.s3db table = s3db.cms_post ltable = s3db.cms_post_module module = "default" resource = "register" query = (ltable.module == module) & \ ((ltable.resource == None) | \ (ltable.resource == resource)) & \ (ltable.post_id == table.id) & \ (table.deleted != True) item = current.db(query).select(table.id, table.body, limitby=(0, 1)).first() if item: if ADMIN: item = DIV(XML(item.body), BR(), A(current.T("Edit"), _href=URL(c="cms", f="post", args=[item.id, "update"]), _class="action-btn")) else: item = DIV(XML(item.body)) elif ADMIN: if response.s3.crud.formstyle == "bootstrap": _class = "btn" else: _class = "action-btn" item = A(current.T("Edit"), _href=URL(c="cms", f="post", args="create", vars={"module": module, "resource": resource }), _class="%s cms-edit" % _class) else: item = "" form = auth.register() response.title = "Register | NYC Prepared" self._view(THEME, "register.html") return dict(form=form, item=item, ) # ============================================================================= class dashboard(S3CustomController): """ Custom controller for personal dashboard """ def __call__(self): auth = current.auth if not auth.s3_logged_in(): auth.permission.fail() # Use custom method current.s3db.set_method("pr", "person", method = "dashboard", action = PersonalDashboard, ) # Call for currently logged-in person r = s3_request("pr", "person", args=[str(auth.s3_logged_in_person()), "dashboard.%s" % auth.permission.format, ], r = current.request, ) return r() # ============================================================================= class PersonalDashboard(S3Method): """ Custom method for personal dashboard """ def apply_method(self, r, **attr): """ Entry point for REST API @param r: the request (S3Request) @param attr: REST controller parameters """ if r.record and r.representation in ("html", "aadata"): T = current.T db = current.db s3db = current.s3db auth = current.auth is_admin = auth.s3_has_role("ADMIN") accessible = auth.s3_accessible_query # Profile widgets profile_widgets = [] add_widget = profile_widgets.append dt_row_actions = self.dt_row_actions from s3 import FS # Organisations widget = {"label": T("My Organizations"), "icon": "organisation", "insert": False, "tablename": "org_organisation", "type": "datatable", "actions": dt_row_actions("org", "organisation"), "list_fields": ["name", (T("Type"), "organisation_organisation_type.organisation_type_id"), "phone", (T("Email"), "email.value"), "website", ], } if not is_admin: otable = s3db.org_organisation rows = db(accessible("update", "org_organisation")).select(otable.id) organisation_ids = [row.id for row in rows] widget["filter"] = FS("id").belongs(organisation_ids) add_widget(widget) # Facilities widget = {"label": T("My Facilities"), "icon": "facility", "insert": False, "tablename": "org_facility", "type": "datatable", "actions": dt_row_actions("org", "facility"), "list_fields": ["name", "code", "site_facility_type.facility_type_id", "organisation_id", "location_id", ], } if not is_admin: ftable = s3db.org_facility rows = db(accessible("update", "org_facility")).select(ftable.id) facility_ids = [row.id for row in rows] widget["filter"] = FS("id").belongs(facility_ids) add_widget(widget) # Networks (only if user can update any records) widget_filter = None if not is_admin: gtable = s3db.org_group rows = db(accessible("update", "org_group")).select(gtable.id) group_ids = [row.id for row in rows] if group_ids: widget_filter = FS("id").belongs(group_ids) if is_admin or widget_filter: widget = {"label": T("My Networks"), "icon": "org-network", "insert": False, "tablename": "org_group", "filter": widget_filter, "type": "datatable", "actions": dt_row_actions("org", "group"), } add_widget(widget) # Groups (only if user can update any records) widget_filter = None if not is_admin: gtable = s3db.pr_group rows = db(accessible("update", "pr_group")).select(gtable.id) group_ids = [row.id for row in rows] if group_ids: widget_filter = FS("id").belongs(group_ids) if is_admin or widget_filter: widget = {"label": T("My Groups"), "icon": "group", "insert": False, "tablename": "pr_group", "filter": widget_filter, "type": "datatable", "actions": dt_row_actions("hrm", "group"), "list_fields": [(T("Network"), "group_team.org_group_id"), "name", "description", (T("Chairperson"), "chairperson"), ], } add_widget(widget) # CMS Content from gluon.html import A, DIV, H2, TAG item = None title = T("Dashboard") if current.deployment_settings.has_module("cms"): name = "Dashboard" ctable = s3db.cms_post query = (ctable.name == name) & (ctable.deleted != True) row = db(query).select(ctable.id, ctable.title, ctable.body, limitby=(0, 1)).first() get_vars = {"page": name, "url": URL(args="dashboard", vars={}), } if row: title = row.title if is_admin: item = DIV(XML(row.body), DIV(A(T("Edit"), _href=URL(c="cms", f="post", args=[row.id, "update"], vars=get_vars, ), _class="action-btn", ), _class="cms-edit", ), ) else: item = DIV(XML(row.body)) elif is_admin: item = DIV(DIV(A(T("Edit"), _href=URL(c="cms", f="post", args="create", vars=get_vars, ), _class="action-btn", ), _class="cms-edit", ) ) # Rheader if r.representation == "html": # Dashboard title profile_header = TAG[""](DIV(DIV(H2(title), _class="medium-6 columns end", ), _class="row", ) ) # CMS content if item: profile_header.append(DIV(DIV(item, _class="medium-12 columns", ), _class="row", )) # Dashboard links dashboard_links = DIV(A(T("Personal Profile"), _href = URL(c="default", f="person"), _class = "action-btn", ), _class="dashboard-links", _style="padding:0.5rem 0;" ) profile_header.append(DIV(DIV(dashboard_links, _class="medium-12 columns", ), _class="row", )) else: profile_header = None # Configure profile tablename = r.tablename s3db.configure(tablename, profile_cols = 2, profile_header = profile_header, profile_widgets = profile_widgets, ) # Render profile from s3 import S3Profile profile = S3Profile() profile.tablename = tablename profile.request = r output = profile.profile(r, **attr) if r.representation == "html": output["title"] = \ current.response.title = T("Personal Dashboard") return output else: raise HTTP(405, current.ERROR.BAD_METHOD) # ------------------------------------------------------------------------- @staticmethod def dt_row_actions(c, f): """ Data table row actions """ return lambda r, list_id: [ {"label": current.deployment_settings.get_ui_label_update(), "url": URL(c=c, f=f, args=["[id]", "update"]), "_class": "action-btn edit", }, ] # END =========================================================================
mit
chen0510566/MissionPlanner
Lib/site-packages/numpy/oldnumeric/arrayfns.py
86
2532
"""Backward compatible with arrayfns from Numeric """ __all__ = ['array_set', 'construct3', 'digitize', 'error', 'find_mask', 'histogram', 'index_sort', 'interp', 'nz', 'reverse', 'span', 'to_corners', 'zmin_zmax'] import numpy as np from numpy import asarray class error(Exception): pass def array_set(vals1, indices, vals2): indices = asarray(indices) if indices.ndim != 1: raise ValueError, "index array must be 1-d" if not isinstance(vals1, np.ndarray): raise TypeError, "vals1 must be an ndarray" vals1 = asarray(vals1) vals2 = asarray(vals2) if vals1.ndim != vals2.ndim or vals1.ndim < 1: raise error, "vals1 and vals2 must have same number of dimensions (>=1)" vals1[indices] = vals2 from numpy import digitize from numpy import bincount as histogram def index_sort(arr): return asarray(arr).argsort(kind='heap') def interp(y, x, z, typ=None): """y(z) interpolated by treating y(x) as piecewise function """ res = np.interp(z, x, y) if typ is None or typ == 'd': return res if typ == 'f': return res.astype('f') raise error, "incompatible typecode" def nz(x): x = asarray(x,dtype=np.ubyte) if x.ndim != 1: raise TypeError, "intput must have 1 dimension." indxs = np.flatnonzero(x != 0) return indxs[-1].item()+1 def reverse(x, n): x = asarray(x,dtype='d') if x.ndim != 2: raise ValueError, "input must be 2-d" y = np.empty_like(x) if n == 0: y[...] = x[::-1,:] elif n == 1: y[...] = x[:,::-1] return y def span(lo, hi, num, d2=0): x = np.linspace(lo, hi, num) if d2 <= 0: return x else: ret = np.empty((d2,num),x.dtype) ret[...] = x return ret def zmin_zmax(z, ireg): z = asarray(z, dtype=float) ireg = asarray(ireg, dtype=int) if z.shape != ireg.shape or z.ndim != 2: raise ValueError, "z and ireg must be the same shape and 2-d" ix, iy = np.nonzero(ireg) # Now, add more indices x1m = ix - 1 y1m = iy-1 i1 = x1m>=0 i2 = y1m>=0 i3 = i1 & i2 nix = np.r_[ix, x1m[i1], x1m[i1], ix[i2] ] niy = np.r_[iy, iy[i1], y1m[i3], y1m[i2]] # remove any negative indices zres = z[nix,niy] return zres.min().item(), zres.max().item() def find_mask(fs, node_edges): raise NotImplementedError def to_corners(arr, nv, nvsum): raise NotImplementedError def construct3(mask, itype): raise NotImplementedError
gpl-3.0
WMD-group/effectivemasstheory
examples/pbs.py
2
6662
#! /usr/bin/env python """Calculate simple semiconductor properties from effective mass theory""" ################################################################################ # Aron Walsh 2014 # ################################################################################ import math as m import scipy.constants as sc from numpy import linspace #import matplotlib.pyplot as plt from optparse import OptionParser ######################## Set up optional arguments ############################# parser = OptionParser() parser.add_option("-c", "--electron-effective-mass", action="store", type="float", dest="e", default=0.1, help="Average electron (conduction band) effective mass") parser.add_option("-v", "--hole-effective-mass", action="store", type="float", dest="h", default=0.1, help="Average hole (valence band) effective mass") parser.add_option("-s", "--static-dielectric", action="store", type="float", dest="d0", default=170, help="Static (low-frequency) dielectric constant") parser.add_option("-o", "--optical-dielectric", action="store", type="float", dest="d1", default=17.2, help="Optical (high-frequency) dielectric constant") #########################defaults for CH3NH3PbI3################################ # #parser.add_option("-p", "--optical-phonon", # action="store", type="float", dest="lo", default=9.3, # help="Optical (polaron active) phonon in THz") ### Further options go here ### (options,args) = parser.parse_args() ########################### Begin main program ################################# print "*A program for semiconductor properties from effective mass theory* \n" # See, e.g. Fundamentals of Semiconductors, Yu and Cardona print "Aron Walsh (University of Bath) \nDate last edited: 22/11/2014 \n" # Get electron effective mass if options.e ==0: e = raw_input("What is the electron effective mass (e.g. 0.3 me)?") e = float(e) else: e = options.e # Get hole effective mass if options.h ==0: h = raw_input("What is the hole effective mass (e.g. 0.3 me)?") h = float(h) else: h = options.h # Get static (low frequency) dielectric constant if options.d0 ==0: d0 = raw_input("What is the static dielectric constant (e.g. 10)?") d0 = float(d0) else: d0 = options.d0 # Get optical (high frequency) dielectric constant if options.d1 ==0: d1 = raw_input("What is the optical dielectric constant (e.g. 5)?") d1 = float(d1) else: d1 = options.d1 # Get optical phonon frequency #if options.lo ==0: # lo = raw_input("What is the optical phonon frequency (e.g. 1 THz)?") # lo = float(lo) #else: # lo = options.lo # # Calculate properties # # Reduced effective mass mass=((e*h)/(e+h)) diel=(1/d1-1/d0) print ("*Effective mass \nHole mass: " + str(h) + " me") print ("Electron mass: " + str(e) + " me") print ("Reduced mass: %3.2f me\n" % (mass)) # Exciton Bohr radius radius_bohr=(d0/mass) radius_bohr_h=(d0/h) radius_bohr_e=(d0/e) radius=(d0/mass)*0.529177249 radius_h=(d0/h)*0.529177249 radius_e=(d0/e)*0.529177249 print ("*Shallow defects \nAcceptor radius: %3.2f A (%3.2f nm)" %(radius_h, radius_h/10)) print ("Donor radius: %3.2f A (%3.2f nm)\n" %(radius_e, radius_e/10)) # (Static) Exciton binding energy binding=((1/(d0*radius_bohr))*(13.605698066*1000)) print ("*Mott-Wannier analysis \nThermal exciton radius: %3.2f A" %(radius)) print ("Thermal exciton binding energy: %3.2f meV" %(binding)) # (Optical) Exciton binding energy radius_bohr_o=(d1/mass) radius_o=(d1/mass)*0.529177249 binding_o_ryd=1/(d1*radius_bohr_o) binding_o=binding_o_ryd*13.605698066*1000 print ("\nOptical exciton radius: %3.2f A" %(radius_o)) print ("Optical exciton binding energy: %3.2f meV" %(binding_o)) # Carrier polaron radius # From Mott (1968) radius_bh=(2/(h*diel))*0.529177249 print ("\nHole (band) polaron radius: %3.2f A" %(radius_bh)) radius_be=(2/(e*diel))*0.529177249 print ("Electron (band) polaron radius: %3.2f A\n" %(radius_be)) # Quantum dot properties print ("*Quantum dots") confine=radius_o*(sc.pi*sc.pi)/3.6 print ("Confinement radius: %3.0f nm" %(confine/10)) radius_qd=2 #nm radius_qd_bohr=radius_qd*18.8971616463 #change in band gap (spherical confinement + coulomb attraction + rydberg correction) delta_e_ryd=(sc.pi*sc.pi)/(2*mass*radius_qd_bohr*radius_qd_bohr)-(1.786/(d1*radius_qd_bohr))-(0.248*binding_o_ryd) delta_e=delta_e_ryd*13.605698066*1000 print ("r=2nm optical gap enhancement: %3.0f meV \n" %(delta_e)) # # AW: Should fix this at some stage # # Frohlich (lage polaron) properties # Speed of light in atomic units # c=1/sc.alpha # LO frequency (from THz -> Ry) # freq=lo*0.0003039659692 # Small polaron coupling constant # h_alpha=diel*m.sqrt(h/(2*freq)) # e_alpha=diel*m.sqrt(e/(2*freq)) # Small polaron mass (Feynman) # h_pol=h*(1+h_alpha/6) # h_pol=h*((1-0.0008*h_alpha*h_alpha)/(1-h_alpha/6+0.0034*h_alpha*h_alpha)) # radius_bhp=(2/(h_pol*diel))*0.529177249 # e_pol=e*(1+e_alpha/6) # e_pol=e*((1-0.0008*e_alpha*e_alpha)/(1-e_alpha/6+0.0034*e_alpha*e_alpha)) # radius_bep=(2/(e_pol*diel))*0.529177249 # print ("*Hole Polarons \nFrohlich coupling constant: " + str(h_alpha)) # print ("Effective polaron mass: " + str(h_pol) + " me") # print ("Polaron radius: " + str(radius_bhp) + " A \n") # print ("*Electron Polarons \nFrohlich coupling constant: " + str(e_alpha)) # print ("Effective polaron mass: " + str(e_pol) + " me") # print ("Polaron radius: " + str(radius_bep) + " A \n") # Mott transition # Exciton transition ~ 1/exciton volume (Optical properties of Solids - Mark Fox) mott=((1/(4/3*sc.pi*(radius_bohr**3)))*(188971616.463**3)) print ("*Mott criterion (critical concentrations) \nExciton: %3.0e cm-3" %(mott)) # Mott transition (holes) mott=(((0.26/radius_bohr_h)**3)*(188971616.463**3)) print ("Holes: %3.0e cm-3" %(mott)) # Mott transition (electrons) mott=(((0.26/radius_bohr_e)**3)*(188971616.463**3)) print ("Electrons: %3.0e cm-3" %(mott)) # Note that the value of 0.26 for the Mott Criteron is taken from: # "Universality aspects of the metal-nonmetal transition in condensed media" # Edwards and Seinko, PRB 17, 2575 (1978)
gpl-2.0
inveniosoftware/invenio-webhooks
tests/test_invenio_webhooks.py
2
2538
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015 CERN. # # Invenio 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. # # Invenio 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 Invenio; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """Module tests.""" from __future__ import absolute_import, print_function import pytest from flask import Flask, url_for from invenio_db import db from invenio_webhooks import InvenioWebhooks def test_version(): """Test version import.""" from invenio_webhooks import __version__ assert __version__ def test_init(): """Test extension initialization.""" app = Flask('testapp') ext = InvenioWebhooks(app) assert 'invenio-webhooks' in app.extensions app = Flask('testapp') ext = InvenioWebhooks() assert 'invenio-webhooks' not in app.extensions ext.init_app(app) assert 'invenio-webhooks' in app.extensions def test_alembic(app): """Test alembic recipes.""" ext = app.extensions['invenio-db'] with app.app_context(): if db.engine.name == 'sqlite': raise pytest.skip('Upgrades are not supported on SQLite.') assert not ext.alembic.compare_metadata() db.drop_all() ext.alembic.upgrade() assert not ext.alembic.compare_metadata() ext.alembic.downgrade(target='96e796392533') ext.alembic.upgrade() assert not ext.alembic.compare_metadata() def test_view(app): """Test view.""" with app.test_request_context(): view_url = url_for('invenio_webhooks.event_list', receiver_id='test_receiver') with app.test_client() as client: res = client.get(view_url) assert res.status_code == 405 res = client.post(view_url) assert res.status_code == 401
gpl-2.0
lscheinkman/nupic
tests/swarming/nupic/swarming/experiments/simpleV2/description.py
10
15403
# ---------------------------------------------------------------------- # 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/ # ---------------------------------------------------------------------- """ Template file used by the OPF Experiment Generator to generate the actual description.py file by replacing $XXXXXXXX tokens with desired values. This description.py file was generated by: '/Users/ronmarianetti/nupic/eng/lib/python2.6/site-packages/nupic/frameworks/opf/expGenerator/experiment_generator.py' """ from nupic.frameworks.opf.exp_description_api import ExperimentDescriptionAPI from nupic.frameworks.opf.exp_description_helpers import ( updateConfigFromSubConfig, applyValueGettersToContainer, DeferredDictLookup) from nupic.frameworks.opf.htm_prediction_model_callbacks import * from nupic.frameworks.opf.metrics import MetricSpec from nupic.frameworks.opf.opf_utils import (InferenceType, InferenceElement) from nupic.support import aggregationDivide from nupic.frameworks.opf.opf_task_driver import ( IterationPhaseSpecLearnOnly, IterationPhaseSpecInferOnly, IterationPhaseSpecLearnAndInfer) # Model Configuration Dictionary: # # Define the model parameters and adjust for any modifications if imported # from a sub-experiment. # # These fields might be modified by a sub-experiment; this dict is passed # between the sub-experiment and base experiment # # # NOTE: Use of DEFERRED VALUE-GETTERs: dictionary fields and list elements # within the config dictionary may be assigned futures derived from the # ValueGetterBase class, such as DeferredDictLookup. # This facility is particularly handy for enabling substitution of values in # the config dictionary from other values in the config dictionary, which is # needed by permutation.py-based experiments. These values will be resolved # during the call to applyValueGettersToContainer(), # which we call after the base experiment's config dictionary is updated from # the sub-experiment. See ValueGetterBase and # DeferredDictLookup for more details about value-getters. # # For each custom encoder parameter to be exposed to the sub-experiment/ # permutation overrides, define a variable in this section, using key names # beginning with a single underscore character to avoid collisions with # pre-defined keys (e.g., _dsEncoderFieldName2_N). # # Example: # config = dict( # _dsEncoderFieldName2_N = 70, # _dsEncoderFieldName2_W = 5, # dsEncoderSchema = [ # base=dict( # fieldname='Name2', type='ScalarEncoder', # name='Name2', minval=0, maxval=270, clipInput=True, # n=DeferredDictLookup('_dsEncoderFieldName2_N'), # w=DeferredDictLookup('_dsEncoderFieldName2_W')), # ], # ) # updateConfigFromSubConfig(config) # applyValueGettersToContainer(config) config = { # Type of model that the rest of these parameters apply to. 'model': "HTMPrediction", # Version that specifies the format of the config. 'version': 1, # Intermediate variables used to compute fields in modelParams and also # referenced from the control section. 'aggregationInfo': { 'days': 0, 'fields': [ (u'timestamp', 'first'), (u'gym', 'first'), (u'consumption', 'mean'), (u'address', 'first')], 'hours': 0, 'microseconds': 0, 'milliseconds': 0, 'minutes': 0, 'months': 0, 'seconds': 0, 'weeks': 0, 'years': 0}, 'predictAheadTime': None, # Model parameter dictionary. 'modelParams': { # The type of inference that this model will perform 'inferenceType': 'TemporalNextStep', 'sensorParams': { # Sensor diagnostic output verbosity control; # if > 0: sensor region will print out on screen what it's sensing # at each step 0: silent; >=1: some info; >=2: more info; # >=3: even more info (see compute() in py/regions/RecordSensor.py) 'verbosity' : 0, # Example: # dsEncoderSchema = [ # DeferredDictLookup('__field_name_encoder'), # ], # # (value generated from DS_ENCODER_SCHEMA) 'encoders': { 'address': { 'fieldname': u'address', 'n': 300, 'name': u'address', 'type': 'SDRCategoryEncoder', 'w': 21}, 'consumption': { 'clipInput': True, 'fieldname': u'consumption', 'maxval': 200, 'minval': 0, 'n': 1500, 'name': u'consumption', 'type': 'ScalarEncoder', 'w': 21}, 'gym': { 'fieldname': u'gym', 'n': 300, 'name': u'gym', 'type': 'SDRCategoryEncoder', 'w': 21}, 'timestamp_dayOfWeek': { 'dayOfWeek': (7, 3), 'fieldname': u'timestamp', 'name': u'timestamp_dayOfWeek', 'type': 'DateEncoder'}, 'timestamp_timeOfDay': { 'fieldname': u'timestamp', 'name': u'timestamp_timeOfDay', 'timeOfDay': (7, 8), 'type': 'DateEncoder'}}, # A dictionary specifying the period for automatically-generated # resets from a RecordSensor; # # None = disable automatically-generated resets (also disabled if # all of the specified values evaluate to 0). # Valid keys is the desired combination of the following: # days, hours, minutes, seconds, milliseconds, microseconds, weeks # # Example for 1.5 days: sensorAutoReset = dict(days=1,hours=12), # # (value generated from SENSOR_AUTO_RESET) 'sensorAutoReset' : None, }, 'spEnable': True, 'spParams': { # SP diagnostic output verbosity control; # 0: silent; >=1: some info; >=2: more info; 'spVerbosity' : 0, 'globalInhibition': 1, # Number of cell columns in the cortical region (same number for # SP and TM) # (see also tpNCellsPerCol) 'columnCount': 2048, 'inputWidth': 0, # SP inhibition control (absolute value); # Maximum number of active columns in the SP region's output (when # there are more, the weaker ones are suppressed) 'numActiveColumnsPerInhArea': 40, 'seed': 1956, # potentialPct # What percent of the columns's receptive field is available # for potential synapses. At initialization time, we will # choose potentialPct * (2*potentialRadius+1)^2 'potentialPct': 0.5, # 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. Typical value is 0.10. Cells whose activity # level before inhibition falls below minDutyCycleBeforeInh # will have their own internal synPermConnectedCell # threshold set below this default value. # (This concept applies to both SP and TM and so 'cells' # is correct here as opposed to 'columns') 'synPermConnected': 0.1, 'synPermActiveInc': 0.1, 'synPermInactiveDec': 0.01, }, # Controls whether TM is enabled or disabled; # TM is necessary for making temporal predictions, such as predicting # the next inputs. Without TM, the model is only capable of # reconstructing missing sensor inputs (via SP). 'tmEnable' : True, 'tmParams': { # TM diagnostic output verbosity control; # 0: silent; [1..6]: increasing levels of verbosity # (see verbosity in nupic/trunk/py/nupic/research/backtracking_tm.py and backtracking_tm_cpp.py) 'verbosity': 0, # Number of cell columns in the cortical region (same number for # SP and TM) # (see also tpNCellsPerCol) 'columnCount': 2048, # The number of cells (i.e., states), allocated per column. 'cellsPerColumn': 32, 'inputWidth': 2048, 'seed': 1960, # Temporal Pooler implementation selector (see _getTPClass in # CLARegion.py). 'temporalImp': 'cpp', # New Synapse formation count # NOTE: If None, use spNumActivePerInhArea # # TODO: need better explanation 'newSynapseCount': 15, # Maximum number of synapses per segment # > 0 for fixed-size CLA # -1 for non-fixed-size CLA # # TODO: for Ron: once the appropriate value is placed in TM # constructor, see if we should eliminate this parameter from # description.py. 'maxSynapsesPerSegment': 32, # Maximum number of segments per cell # > 0 for fixed-size CLA # -1 for non-fixed-size CLA # # TODO: for Ron: once the appropriate value is placed in TM # constructor, see if we should eliminate this parameter from # description.py. 'maxSegmentsPerCell': 128, # Initial Permanence # TODO: need better explanation 'initialPerm': 0.21, # Permanence Increment 'permanenceInc': 0.1, # Permanence Decrement # If set to None, will automatically default to tpPermanenceInc # value. 'permanenceDec' : 0.1, 'globalDecay': 0.0, 'maxAge': 0, # Minimum number of active synapses for a segment to be considered # during search for the best-matching segments. # None=use default # Replaces: tpMinThreshold 'minThreshold': 12, # Segment activation threshold. # A segment is active if it has >= tpSegmentActivationThreshold # connected synapses that are active due to infActiveState # None=use default # Replaces: tpActivationThreshold 'activationThreshold': 16, 'outputType': 'normal', # "Pay Attention Mode" length. This tells the TM how many new # elements to append to the end of a learned sequence at a time. # Smaller values are better for datasets with short sequences, # higher values are better for datasets with long sequences. 'pamLength': 1, }, 'clParams': { 'regionName' : 'SDRClassifierRegion', # Classifier diagnostic output verbosity control; # 0: silent; [1..6]: increasing levels of verbosity 'verbosity' : 0, # This controls how fast the classifier learns/forgets. Higher values # make it adapt faster and forget older patterns faster. 'alpha': 0.001, # This is set after the call to updateConfigFromSubConfig and is # computed from the aggregationInfo and predictAheadTime. 'steps': '1', }, 'trainSPNetOnlyIfRequested': False, }, } # end of config dictionary # Adjust base config dictionary for any modifications if imported from a # sub-experiment updateConfigFromSubConfig(config) # Compute predictionSteps based on the predictAheadTime and the aggregation # period, which may be permuted over. if config['predictAheadTime'] is not None: predictionSteps = int(round(aggregationDivide( config['predictAheadTime'], config['aggregationInfo']))) assert (predictionSteps >= 1) config['modelParams']['clParams']['steps'] = str(predictionSteps) # Adjust config by applying ValueGetterBase-derived # futures. NOTE: this MUST be called after updateConfigFromSubConfig() in order # to support value-getter-based substitutions from the sub-experiment (if any) applyValueGettersToContainer(config) control = { # The environment that the current model is being run in "environment": 'nupic', # Input stream specification per py/nupicengine/cluster/database/StreamDef.json. # 'dataset' : { u'info': u'test_NoProviders', u'streams': [ { u'columns': [u'*'], u'info': u'test data', u'source': u'file://swarming/test_data.csv'}], u'version': 1}, # Iteration count: maximum number of iterations. Each iteration corresponds # to one record from the (possibly aggregated) dataset. The task is # terminated when either number of iterations reaches iterationCount or # all records in the (possibly aggregated) database have been processed, # whichever occurs first. # # iterationCount of -1 = iterate over the entire dataset #'iterationCount' : ITERATION_COUNT, # Metrics: A list of MetricSpecs that instantiate the metrics that are # computed for this experiment 'metrics':[ MetricSpec(field=u'consumption', inferenceElement=InferenceElement.prediction, metric='rmse'), ], # Logged Metrics: A sequence of regular expressions that specify which of # the metrics from the Inference Specifications section MUST be logged for # every prediction. The regex's correspond to the automatically generated # metric labels. This is similar to the way the optimization metric is # specified in permutations.py. 'loggedMetrics': ['.*nupicScore.*'], } descriptionInterface = ExperimentDescriptionAPI(modelConfig=config, control=control)
agpl-3.0
st135yle/django-site
dbenv/lib/python3.4/site-packages/psycopg2/extras.py
8
42565
"""Miscellaneous goodies for psycopg2 This module is a generic place used to hold little helper functions and classes until a better place in the distribution is found. """ # psycopg/extras.py - miscellaneous extra goodies for psycopg # # Copyright (C) 2003-2010 Federico Di Gregorio <fog@debian.org> # # psycopg2 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. # # In addition, as a special exception, the copyright holders give # permission to link this program with the OpenSSL library (or with # modified versions of OpenSSL that use the same license as OpenSSL), # and distribute linked combinations including the two. # # You must obey the GNU Lesser General Public License in all respects for # all of the code used other than OpenSSL. # # psycopg2 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. import os as _os import sys as _sys import time as _time import re as _re try: import logging as _logging except: _logging = None import psycopg2 from psycopg2 import extensions as _ext from psycopg2.extensions import cursor as _cursor from psycopg2.extensions import connection as _connection from psycopg2.extensions import adapt as _A, quote_ident from psycopg2._psycopg import ( # noqa REPLICATION_PHYSICAL, REPLICATION_LOGICAL, ReplicationConnection as _replicationConnection, ReplicationCursor as _replicationCursor, ReplicationMessage) # expose the json adaptation stuff into the module from psycopg2._json import ( # noqa json, Json, register_json, register_default_json, register_default_jsonb) # Expose range-related objects from psycopg2._range import ( # noqa Range, NumericRange, DateRange, DateTimeRange, DateTimeTZRange, register_range, RangeAdapter, RangeCaster) # Expose ipaddress-related objects from psycopg2._ipaddress import register_ipaddress # noqa class DictCursorBase(_cursor): """Base class for all dict-like cursors.""" def __init__(self, *args, **kwargs): if 'row_factory' in kwargs: row_factory = kwargs['row_factory'] del kwargs['row_factory'] else: raise NotImplementedError( "DictCursorBase can't be instantiated without a row factory.") super(DictCursorBase, self).__init__(*args, **kwargs) self._query_executed = 0 self._prefetch = 0 self.row_factory = row_factory def fetchone(self): if self._prefetch: res = super(DictCursorBase, self).fetchone() if self._query_executed: self._build_index() if not self._prefetch: res = super(DictCursorBase, self).fetchone() return res def fetchmany(self, size=None): if self._prefetch: res = super(DictCursorBase, self).fetchmany(size) if self._query_executed: self._build_index() if not self._prefetch: res = super(DictCursorBase, self).fetchmany(size) return res def fetchall(self): if self._prefetch: res = super(DictCursorBase, self).fetchall() if self._query_executed: self._build_index() if not self._prefetch: res = super(DictCursorBase, self).fetchall() return res def __iter__(self): try: if self._prefetch: res = super(DictCursorBase, self).__iter__() first = next(res) if self._query_executed: self._build_index() if not self._prefetch: res = super(DictCursorBase, self).__iter__() first = next(res) yield first while 1: yield next(res) except StopIteration: return class DictConnection(_connection): """A connection that uses `DictCursor` automatically.""" def cursor(self, *args, **kwargs): kwargs.setdefault('cursor_factory', DictCursor) return super(DictConnection, self).cursor(*args, **kwargs) class DictCursor(DictCursorBase): """A cursor that keeps a list of column name -> index mappings.""" def __init__(self, *args, **kwargs): kwargs['row_factory'] = DictRow super(DictCursor, self).__init__(*args, **kwargs) self._prefetch = 1 def execute(self, query, vars=None): self.index = {} self._query_executed = 1 return super(DictCursor, self).execute(query, vars) def callproc(self, procname, vars=None): self.index = {} self._query_executed = 1 return super(DictCursor, self).callproc(procname, vars) def _build_index(self): if self._query_executed == 1 and self.description: for i in range(len(self.description)): self.index[self.description[i][0]] = i self._query_executed = 0 class DictRow(list): """A row object that allow by-column-name access to data.""" __slots__ = ('_index',) def __init__(self, cursor): self._index = cursor.index self[:] = [None] * len(cursor.description) def __getitem__(self, x): if not isinstance(x, (int, slice)): x = self._index[x] return list.__getitem__(self, x) def __setitem__(self, x, v): if not isinstance(x, (int, slice)): x = self._index[x] list.__setitem__(self, x, v) def items(self): return list(self.items()) def keys(self): return list(self._index.keys()) def values(self): return tuple(self[:]) def has_key(self, x): return x in self._index def get(self, x, default=None): try: return self[x] except: return default def iteritems(self): for n, v in self._index.items(): yield n, list.__getitem__(self, v) def iterkeys(self): return iter(self._index.keys()) def itervalues(self): return list.__iter__(self) def copy(self): return dict(iter(self.items())) def __contains__(self, x): return x in self._index def __getstate__(self): return self[:], self._index.copy() def __setstate__(self, data): self[:] = data[0] self._index = data[1] # drop the crusty Py2 methods if _sys.version_info[0] > 2: items = iteritems # noqa keys = iterkeys # noqa values = itervalues # noqa del iteritems, iterkeys, itervalues, has_key class RealDictConnection(_connection): """A connection that uses `RealDictCursor` automatically.""" def cursor(self, *args, **kwargs): kwargs.setdefault('cursor_factory', RealDictCursor) return super(RealDictConnection, self).cursor(*args, **kwargs) class RealDictCursor(DictCursorBase): """A cursor that uses a real dict as the base type for rows. Note that this cursor is extremely specialized and does not allow the normal access (using integer indices) to fetched data. If you need to access database rows both as a dictionary and a list, then use the generic `DictCursor` instead of `!RealDictCursor`. """ def __init__(self, *args, **kwargs): kwargs['row_factory'] = RealDictRow super(RealDictCursor, self).__init__(*args, **kwargs) self._prefetch = 0 def execute(self, query, vars=None): self.column_mapping = [] self._query_executed = 1 return super(RealDictCursor, self).execute(query, vars) def callproc(self, procname, vars=None): self.column_mapping = [] self._query_executed = 1 return super(RealDictCursor, self).callproc(procname, vars) def _build_index(self): if self._query_executed == 1 and self.description: for i in range(len(self.description)): self.column_mapping.append(self.description[i][0]) self._query_executed = 0 class RealDictRow(dict): """A `!dict` subclass representing a data record.""" __slots__ = ('_column_mapping') def __init__(self, cursor): dict.__init__(self) # Required for named cursors if cursor.description and not cursor.column_mapping: cursor._build_index() self._column_mapping = cursor.column_mapping def __setitem__(self, name, value): if type(name) == int: name = self._column_mapping[name] return dict.__setitem__(self, name, value) def __getstate__(self): return (self.copy(), self._column_mapping[:]) def __setstate__(self, data): self.update(data[0]) self._column_mapping = data[1] class NamedTupleConnection(_connection): """A connection that uses `NamedTupleCursor` automatically.""" def cursor(self, *args, **kwargs): kwargs.setdefault('cursor_factory', NamedTupleCursor) return super(NamedTupleConnection, self).cursor(*args, **kwargs) class NamedTupleCursor(_cursor): """A cursor that generates results as `~collections.namedtuple`. `!fetch*()` methods will return named tuples instead of regular tuples, so their elements can be accessed both as regular numeric items as well as attributes. >>> nt_cur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor) >>> rec = nt_cur.fetchone() >>> rec Record(id=1, num=100, data="abc'def") >>> rec[1] 100 >>> rec.data "abc'def" """ Record = None def execute(self, query, vars=None): self.Record = None return super(NamedTupleCursor, self).execute(query, vars) def executemany(self, query, vars): self.Record = None return super(NamedTupleCursor, self).executemany(query, vars) def callproc(self, procname, vars=None): self.Record = None return super(NamedTupleCursor, self).callproc(procname, vars) def fetchone(self): t = super(NamedTupleCursor, self).fetchone() if t is not None: nt = self.Record if nt is None: nt = self.Record = self._make_nt() return nt._make(t) def fetchmany(self, size=None): ts = super(NamedTupleCursor, self).fetchmany(size) nt = self.Record if nt is None: nt = self.Record = self._make_nt() return list(map(nt._make, ts)) def fetchall(self): ts = super(NamedTupleCursor, self).fetchall() nt = self.Record if nt is None: nt = self.Record = self._make_nt() return list(map(nt._make, ts)) def __iter__(self): try: it = super(NamedTupleCursor, self).__iter__() t = next(it) nt = self.Record if nt is None: nt = self.Record = self._make_nt() yield nt._make(t) while 1: yield nt._make(next(it)) except StopIteration: return try: from collections import namedtuple except ImportError as _exc: def _make_nt(self): raise self._exc else: def _make_nt(self, namedtuple=namedtuple): return namedtuple("Record", [d[0] for d in self.description or ()]) class LoggingConnection(_connection): """A connection that logs all queries to a file or logger__ object. .. __: http://docs.python.org/library/logging.html """ def initialize(self, logobj): """Initialize the connection to log to `!logobj`. The `!logobj` parameter can be an open file object or a Logger instance from the standard logging module. """ self._logobj = logobj if _logging and isinstance(logobj, _logging.Logger): self.log = self._logtologger else: self.log = self._logtofile def filter(self, msg, curs): """Filter the query before logging it. This is the method to overwrite to filter unwanted queries out of the log or to add some extra data to the output. The default implementation just does nothing. """ return msg def _logtofile(self, msg, curs): msg = self.filter(msg, curs) if msg: if _sys.version_info[0] >= 3 and isinstance(msg, bytes): msg = msg.decode(_ext.encodings[self.encoding], 'replace') self._logobj.write(msg + _os.linesep) def _logtologger(self, msg, curs): msg = self.filter(msg, curs) if msg: self._logobj.debug(msg) def _check(self): if not hasattr(self, '_logobj'): raise self.ProgrammingError( "LoggingConnection object has not been initialize()d") def cursor(self, *args, **kwargs): self._check() kwargs.setdefault('cursor_factory', LoggingCursor) return super(LoggingConnection, self).cursor(*args, **kwargs) class LoggingCursor(_cursor): """A cursor that logs queries using its connection logging facilities.""" def execute(self, query, vars=None): try: return super(LoggingCursor, self).execute(query, vars) finally: self.connection.log(self.query, self) def callproc(self, procname, vars=None): try: return super(LoggingCursor, self).callproc(procname, vars) finally: self.connection.log(self.query, self) class MinTimeLoggingConnection(LoggingConnection): """A connection that logs queries based on execution time. This is just an example of how to sub-class `LoggingConnection` to provide some extra filtering for the logged queries. Both the `initialize()` and `filter()` methods are overwritten to make sure that only queries executing for more than ``mintime`` ms are logged. Note that this connection uses the specialized cursor `MinTimeLoggingCursor`. """ def initialize(self, logobj, mintime=0): LoggingConnection.initialize(self, logobj) self._mintime = mintime def filter(self, msg, curs): t = (_time.time() - curs.timestamp) * 1000 if t > self._mintime: return msg + _os.linesep + " (execution time: %d ms)" % t def cursor(self, *args, **kwargs): kwargs.setdefault('cursor_factory', MinTimeLoggingCursor) return LoggingConnection.cursor(self, *args, **kwargs) class MinTimeLoggingCursor(LoggingCursor): """The cursor sub-class companion to `MinTimeLoggingConnection`.""" def execute(self, query, vars=None): self.timestamp = _time.time() return LoggingCursor.execute(self, query, vars) def callproc(self, procname, vars=None): self.timestamp = _time.time() return LoggingCursor.callproc(self, procname, vars) class LogicalReplicationConnection(_replicationConnection): def __init__(self, *args, **kwargs): kwargs['replication_type'] = REPLICATION_LOGICAL super(LogicalReplicationConnection, self).__init__(*args, **kwargs) class PhysicalReplicationConnection(_replicationConnection): def __init__(self, *args, **kwargs): kwargs['replication_type'] = REPLICATION_PHYSICAL super(PhysicalReplicationConnection, self).__init__(*args, **kwargs) class StopReplication(Exception): """ Exception used to break out of the endless loop in `~ReplicationCursor.consume_stream()`. Subclass of `~exceptions.Exception`. Intentionally *not* inherited from `~psycopg2.Error` as occurrence of this exception does not indicate an error. """ pass class ReplicationCursor(_replicationCursor): """A cursor used for communication on replication connections.""" def create_replication_slot(self, slot_name, slot_type=None, output_plugin=None): """Create streaming replication slot.""" command = "CREATE_REPLICATION_SLOT %s " % quote_ident(slot_name, self) if slot_type is None: slot_type = self.connection.replication_type if slot_type == REPLICATION_LOGICAL: if output_plugin is None: raise psycopg2.ProgrammingError( "output plugin name is required to create " "logical replication slot") command += "LOGICAL %s" % quote_ident(output_plugin, self) elif slot_type == REPLICATION_PHYSICAL: if output_plugin is not None: raise psycopg2.ProgrammingError( "cannot specify output plugin name when creating " "physical replication slot") command += "PHYSICAL" else: raise psycopg2.ProgrammingError( "unrecognized replication type: %s" % repr(slot_type)) self.execute(command) def drop_replication_slot(self, slot_name): """Drop streaming replication slot.""" command = "DROP_REPLICATION_SLOT %s" % quote_ident(slot_name, self) self.execute(command) def start_replication(self, slot_name=None, slot_type=None, start_lsn=0, timeline=0, options=None, decode=False): """Start replication stream.""" command = "START_REPLICATION " if slot_type is None: slot_type = self.connection.replication_type if slot_type == REPLICATION_LOGICAL: if slot_name: command += "SLOT %s " % quote_ident(slot_name, self) else: raise psycopg2.ProgrammingError( "slot name is required for logical replication") command += "LOGICAL " elif slot_type == REPLICATION_PHYSICAL: if slot_name: command += "SLOT %s " % quote_ident(slot_name, self) # don't add "PHYSICAL", before 9.4 it was just START_REPLICATION XXX/XXX else: raise psycopg2.ProgrammingError( "unrecognized replication type: %s" % repr(slot_type)) if type(start_lsn) is str: lsn = start_lsn.split('/') lsn = "%X/%08X" % (int(lsn[0], 16), int(lsn[1], 16)) else: lsn = "%X/%08X" % ((start_lsn >> 32) & 0xFFFFFFFF, start_lsn & 0xFFFFFFFF) command += lsn if timeline != 0: if slot_type == REPLICATION_LOGICAL: raise psycopg2.ProgrammingError( "cannot specify timeline for logical replication") command += " TIMELINE %d" % timeline if options: if slot_type == REPLICATION_PHYSICAL: raise psycopg2.ProgrammingError( "cannot specify output plugin options for physical replication") command += " (" for k, v in options.items(): if not command.endswith('('): command += ", " command += "%s %s" % (quote_ident(k, self), _A(str(v))) command += ")" self.start_replication_expert(command, decode=decode) # allows replication cursors to be used in select.select() directly def fileno(self): return self.connection.fileno() # a dbtype and adapter for Python UUID type class UUID_adapter(object): """Adapt Python's uuid.UUID__ type to PostgreSQL's uuid__. .. __: http://docs.python.org/library/uuid.html .. __: http://www.postgresql.org/docs/current/static/datatype-uuid.html """ def __init__(self, uuid): self._uuid = uuid def __conform__(self, proto): if proto is _ext.ISQLQuote: return self def getquoted(self): return ("'%s'::uuid" % self._uuid).encode('utf8') def __str__(self): return "'%s'::uuid" % self._uuid def register_uuid(oids=None, conn_or_curs=None): """Create the UUID type and an uuid.UUID adapter. :param oids: oid for the PostgreSQL :sql:`uuid` type, or 2-items sequence with oids of the type and the array. If not specified, use PostgreSQL standard oids. :param conn_or_curs: where to register the typecaster. If not specified, register it globally. """ import uuid if not oids: oid1 = 2950 oid2 = 2951 elif isinstance(oids, (list, tuple)): oid1, oid2 = oids else: oid1 = oids oid2 = 2951 _ext.UUID = _ext.new_type((oid1, ), "UUID", lambda data, cursor: data and uuid.UUID(data) or None) _ext.UUIDARRAY = _ext.new_array_type((oid2,), "UUID[]", _ext.UUID) _ext.register_type(_ext.UUID, conn_or_curs) _ext.register_type(_ext.UUIDARRAY, conn_or_curs) _ext.register_adapter(uuid.UUID, UUID_adapter) return _ext.UUID # a type, dbtype and adapter for PostgreSQL inet type class Inet(object): """Wrap a string to allow for correct SQL-quoting of inet values. Note that this adapter does NOT check the passed value to make sure it really is an inet-compatible address but DOES call adapt() on it to make sure it is impossible to execute an SQL-injection by passing an evil value to the initializer. """ def __init__(self, addr): self.addr = addr def __repr__(self): return "%s(%r)" % (self.__class__.__name__, self.addr) def prepare(self, conn): self._conn = conn def getquoted(self): obj = _A(self.addr) if hasattr(obj, 'prepare'): obj.prepare(self._conn) return obj.getquoted() + b"::inet" def __conform__(self, proto): if proto is _ext.ISQLQuote: return self def __str__(self): return str(self.addr) def register_inet(oid=None, conn_or_curs=None): """Create the INET type and an Inet adapter. :param oid: oid for the PostgreSQL :sql:`inet` type, or 2-items sequence with oids of the type and the array. If not specified, use PostgreSQL standard oids. :param conn_or_curs: where to register the typecaster. If not specified, register it globally. """ import warnings warnings.warn( "the inet adapter is deprecated, it's not very useful", DeprecationWarning) if not oid: oid1 = 869 oid2 = 1041 elif isinstance(oid, (list, tuple)): oid1, oid2 = oid else: oid1 = oid oid2 = 1041 _ext.INET = _ext.new_type((oid1, ), "INET", lambda data, cursor: data and Inet(data) or None) _ext.INETARRAY = _ext.new_array_type((oid2, ), "INETARRAY", _ext.INET) _ext.register_type(_ext.INET, conn_or_curs) _ext.register_type(_ext.INETARRAY, conn_or_curs) return _ext.INET def register_tstz_w_secs(oids=None, conn_or_curs=None): """The function used to register an alternate type caster for :sql:`TIMESTAMP WITH TIME ZONE` to deal with historical time zones with seconds in the UTC offset. These are now correctly handled by the default type caster, so currently the function doesn't do anything. """ import warnings warnings.warn("deprecated", DeprecationWarning) def wait_select(conn): """Wait until a connection or cursor has data available. The function is an example of a wait callback to be registered with `~psycopg2.extensions.set_wait_callback()`. This function uses :py:func:`~select.select()` to wait for data available. """ import select from psycopg2.extensions import POLL_OK, POLL_READ, POLL_WRITE while 1: try: state = conn.poll() if state == POLL_OK: break elif state == POLL_READ: select.select([conn.fileno()], [], []) elif state == POLL_WRITE: select.select([], [conn.fileno()], []) else: raise conn.OperationalError("bad state from poll: %s" % state) except KeyboardInterrupt: conn.cancel() # the loop will be broken by a server error continue def _solve_conn_curs(conn_or_curs): """Return the connection and a DBAPI cursor from a connection or cursor.""" if conn_or_curs is None: raise psycopg2.ProgrammingError("no connection or cursor provided") if hasattr(conn_or_curs, 'execute'): conn = conn_or_curs.connection curs = conn.cursor(cursor_factory=_cursor) else: conn = conn_or_curs curs = conn.cursor(cursor_factory=_cursor) return conn, curs class HstoreAdapter(object): """Adapt a Python dict to the hstore syntax.""" def __init__(self, wrapped): self.wrapped = wrapped def prepare(self, conn): self.conn = conn # use an old-style getquoted implementation if required if conn.server_version < 90000: self.getquoted = self._getquoted_8 def _getquoted_8(self): """Use the operators available in PG pre-9.0.""" if not self.wrapped: return b"''::hstore" adapt = _ext.adapt rv = [] for k, v in self.wrapped.items(): k = adapt(k) k.prepare(self.conn) k = k.getquoted() if v is not None: v = adapt(v) v.prepare(self.conn) v = v.getquoted() else: v = b'NULL' # XXX this b'ing is painfully inefficient! rv.append(b"(" + k + b" => " + v + b")") return b"(" + b'||'.join(rv) + b")" def _getquoted_9(self): """Use the hstore(text[], text[]) function.""" if not self.wrapped: return b"''::hstore" k = _ext.adapt(list(self.wrapped.keys())) k.prepare(self.conn) v = _ext.adapt(list(self.wrapped.values())) v.prepare(self.conn) return b"hstore(" + k.getquoted() + b", " + v.getquoted() + b")" getquoted = _getquoted_9 _re_hstore = _re.compile(r""" # hstore key: # a string of normal or escaped chars "((?: [^"\\] | \\. )*)" \s*=>\s* # hstore value (?: NULL # the value can be null - not catched # or a quoted string like the key | "((?: [^"\\] | \\. )*)" ) (?:\s*,\s*|$) # pairs separated by comma or end of string. """, _re.VERBOSE) @classmethod def parse(self, s, cur, _bsdec=_re.compile(r"\\(.)")): """Parse an hstore representation in a Python string. The hstore is represented as something like:: "a"=>"1", "b"=>"2" with backslash-escaped strings. """ if s is None: return None rv = {} start = 0 for m in self._re_hstore.finditer(s): if m is None or m.start() != start: raise psycopg2.InterfaceError( "error parsing hstore pair at char %d" % start) k = _bsdec.sub(r'\1', m.group(1)) v = m.group(2) if v is not None: v = _bsdec.sub(r'\1', v) rv[k] = v start = m.end() if start < len(s): raise psycopg2.InterfaceError( "error parsing hstore: unparsed data after char %d" % start) return rv @classmethod def parse_unicode(self, s, cur): """Parse an hstore returning unicode keys and values.""" if s is None: return None s = s.decode(_ext.encodings[cur.connection.encoding]) return self.parse(s, cur) @classmethod def get_oids(self, conn_or_curs): """Return the lists of OID of the hstore and hstore[] types. """ conn, curs = _solve_conn_curs(conn_or_curs) # Store the transaction status of the connection to revert it after use conn_status = conn.status # column typarray not available before PG 8.3 typarray = conn.server_version >= 80300 and "typarray" or "NULL" rv0, rv1 = [], [] # get the oid for the hstore curs.execute("""\ SELECT t.oid, %s FROM pg_type t JOIN pg_namespace ns ON typnamespace = ns.oid WHERE typname = 'hstore'; """ % typarray) for oids in curs: rv0.append(oids[0]) rv1.append(oids[1]) # revert the status of the connection as before the command if (conn_status != _ext.STATUS_IN_TRANSACTION and not conn.autocommit): conn.rollback() return tuple(rv0), tuple(rv1) def register_hstore(conn_or_curs, globally=False, str=False, oid=None, array_oid=None): r"""Register adapter and typecaster for `!dict`\-\ |hstore| conversions. :param conn_or_curs: a connection or cursor: the typecaster will be registered only on this object unless *globally* is set to `!True` :param globally: register the adapter globally, not only on *conn_or_curs* :param unicode: if `!True`, keys and values returned from the database will be `!unicode` instead of `!str`. The option is not available on Python 3 :param oid: the OID of the |hstore| type if known. If not, it will be queried on *conn_or_curs*. :param array_oid: the OID of the |hstore| array type if known. If not, it will be queried on *conn_or_curs*. The connection or cursor passed to the function will be used to query the database and look for the OID of the |hstore| type (which may be different across databases). If querying is not desirable (e.g. with :ref:`asynchronous connections <async-support>`) you may specify it in the *oid* parameter, which can be found using a query such as :sql:`SELECT 'hstore'::regtype::oid`. Analogously you can obtain a value for *array_oid* using a query such as :sql:`SELECT 'hstore[]'::regtype::oid`. Note that, when passing a dictionary from Python to the database, both strings and unicode keys and values are supported. Dictionaries returned from the database have keys/values according to the *unicode* parameter. The |hstore| contrib module must be already installed in the database (executing the ``hstore.sql`` script in your ``contrib`` directory). Raise `~psycopg2.ProgrammingError` if the type is not found. """ if oid is None: oid = HstoreAdapter.get_oids(conn_or_curs) if oid is None or not oid[0]: raise psycopg2.ProgrammingError( "hstore type not found in the database. " "please install it from your 'contrib/hstore.sql' file") else: array_oid = oid[1] oid = oid[0] if isinstance(oid, int): oid = (oid,) if array_oid is not None: if isinstance(array_oid, int): array_oid = (array_oid,) else: array_oid = tuple([x for x in array_oid if x]) # create and register the typecaster if _sys.version_info[0] < 3 and str: cast = HstoreAdapter.parse_unicode else: cast = HstoreAdapter.parse HSTORE = _ext.new_type(oid, "HSTORE", cast) _ext.register_type(HSTORE, not globally and conn_or_curs or None) _ext.register_adapter(dict, HstoreAdapter) if array_oid: HSTOREARRAY = _ext.new_array_type(array_oid, "HSTOREARRAY", HSTORE) _ext.register_type(HSTOREARRAY, not globally and conn_or_curs or None) class CompositeCaster(object): """Helps conversion of a PostgreSQL composite type into a Python object. The class is usually created by the `register_composite()` function. You may want to create and register manually instances of the class if querying the database at registration time is not desirable (such as when using an :ref:`asynchronous connections <async-support>`). """ def __init__(self, name, oid, attrs, array_oid=None, schema=None): self.name = name self.schema = schema self.oid = oid self.array_oid = array_oid self.attnames = [a[0] for a in attrs] self.atttypes = [a[1] for a in attrs] self._create_type(name, self.attnames) self.typecaster = _ext.new_type((oid,), name, self.parse) if array_oid: self.array_typecaster = _ext.new_array_type( (array_oid,), "%sARRAY" % name, self.typecaster) else: self.array_typecaster = None def parse(self, s, curs): if s is None: return None tokens = self.tokenize(s) if len(tokens) != len(self.atttypes): raise psycopg2.DataError( "expecting %d components for the type %s, %d found instead" % (len(self.atttypes), self.name, len(tokens))) values = [curs.cast(oid, token) for oid, token in zip(self.atttypes, tokens)] return self.make(values) def make(self, values): """Return a new Python object representing the data being casted. *values* is the list of attributes, already casted into their Python representation. You can subclass this method to :ref:`customize the composite cast <custom-composite>`. """ return self._ctor(values) _re_tokenize = _re.compile(r""" \(? ([,)]) # an empty token, representing NULL | \(? " ((?: [^"] | "")*) " [,)] # or a quoted string | \(? ([^",)]+) [,)] # or an unquoted string """, _re.VERBOSE) _re_undouble = _re.compile(r'(["\\])\1') @classmethod def tokenize(self, s): rv = [] for m in self._re_tokenize.finditer(s): if m is None: raise psycopg2.InterfaceError("can't parse type: %r" % s) if m.group(1) is not None: rv.append(None) elif m.group(2) is not None: rv.append(self._re_undouble.sub(r"\1", m.group(2))) else: rv.append(m.group(3)) return rv def _create_type(self, name, attnames): try: from collections import namedtuple except ImportError: self.type = tuple self._ctor = self.type else: self.type = namedtuple(name, attnames) self._ctor = self.type._make @classmethod def _from_db(self, name, conn_or_curs): """Return a `CompositeCaster` instance for the type *name*. Raise `ProgrammingError` if the type is not found. """ conn, curs = _solve_conn_curs(conn_or_curs) # Store the transaction status of the connection to revert it after use conn_status = conn.status # Use the correct schema if '.' in name: schema, tname = name.split('.', 1) else: tname = name schema = 'public' # column typarray not available before PG 8.3 typarray = conn.server_version >= 80300 and "typarray" or "NULL" # get the type oid and attributes curs.execute("""\ SELECT t.oid, %s, attname, atttypid FROM pg_type t JOIN pg_namespace ns ON typnamespace = ns.oid JOIN pg_attribute a ON attrelid = typrelid WHERE typname = %%s AND nspname = %%s AND attnum > 0 AND NOT attisdropped ORDER BY attnum; """ % typarray, (tname, schema)) recs = curs.fetchall() # revert the status of the connection as before the command if (conn_status != _ext.STATUS_IN_TRANSACTION and not conn.autocommit): conn.rollback() if not recs: raise psycopg2.ProgrammingError( "PostgreSQL type '%s' not found" % name) type_oid = recs[0][0] array_oid = recs[0][1] type_attrs = [(r[2], r[3]) for r in recs] return self(tname, type_oid, type_attrs, array_oid=array_oid, schema=schema) def register_composite(name, conn_or_curs, globally=False, factory=None): """Register a typecaster to convert a composite type into a tuple. :param name: the name of a PostgreSQL composite type, e.g. created using the |CREATE TYPE|_ command :param conn_or_curs: a connection or cursor used to find the type oid and components; the typecaster is registered in a scope limited to this object, unless *globally* is set to `!True` :param globally: if `!False` (default) register the typecaster only on *conn_or_curs*, otherwise register it globally :param factory: if specified it should be a `CompositeCaster` subclass: use it to :ref:`customize how to cast composite types <custom-composite>` :return: the registered `CompositeCaster` or *factory* instance responsible for the conversion """ if factory is None: factory = CompositeCaster caster = factory._from_db(name, conn_or_curs) _ext.register_type(caster.typecaster, not globally and conn_or_curs or None) if caster.array_typecaster is not None: _ext.register_type( caster.array_typecaster, not globally and conn_or_curs or None) return caster def _paginate(seq, page_size): """Consume an iterable and return it in chunks. Every chunk is at most `page_size`. Never return an empty chunk. """ page = [] it = iter(seq) while 1: try: for i in range(page_size): page.append(next(it)) yield page page = [] except StopIteration: if page: yield page return def execute_batch(cur, sql, argslist, page_size=100): r"""Execute groups of statements in fewer server roundtrips. Execute *sql* several times, against all parameters set (sequences or mappings) found in *argslist*. The function is semantically similar to .. parsed-literal:: *cur*\.\ `~cursor.executemany`\ (\ *sql*\ , *argslist*\ ) but has a different implementation: Psycopg will join the statements into fewer multi-statement commands, each one containing at most *page_size* statements, resulting in a reduced number of server roundtrips. After the execution of the functtion the `cursor.rowcount` property will **not** contain a total result. """ for page in _paginate(argslist, page_size=page_size): sqls = [cur.mogrify(sql, args) for args in page] cur.execute(b";".join(sqls)) def execute_values(cur, sql, argslist, template=None, page_size=100): '''Execute a statement using :sql:`VALUES` with a sequence of parameters. :param cur: the cursor to use to execute the query. :param sql: the query to execute. It must contain a single ``%s`` placeholder, which will be replaced by a `VALUES list`__. Example: ``"INSERT INTO mytable (id, f1, f2) VALUES %s"``. :param argslist: sequence of sequences or dictionaries with the arguments to send to the query. The type and content must be consistent with *template*. :param template: the snippet to merge to every item in *argslist* to compose the query. If *argslist* items are sequences it should contain positional placeholders (e.g. ``"(%s, %s, %s)"``, or ``"(%s, %s, 42)``" if there are constants value...); If *argslist* is items are mapping it should contain named placeholders (e.g. ``"(%(id)s, %(f1)s, 42)"``). If not specified, assume the arguments are sequence and use a simple positional template (i.e. ``(%s, %s, ...)``), with the number of placeholders sniffed by the first element in *argslist*. :param page_size: maximum number of *argslist* items to include in every statement. If there are more items the function will execute more than one statement. .. __: https://www.postgresql.org/docs/current/static/queries-values.html After the execution of the functtion the `cursor.rowcount` property will **not** contain a total result. While :sql:`INSERT` is an obvious candidate for this function it is possible to use it with other statements, for example:: >>> cur.execute( ... "create table test (id int primary key, v1 int, v2 int)") >>> execute_values(cur, ... "INSERT INTO test (id, v1, v2) VALUES %s", ... [(1, 2, 3), (4, 5, 6), (7, 8, 9)]) >>> execute_values(cur, ... """UPDATE test SET v1 = data.v1 FROM (VALUES %s) AS data (id, v1) ... WHERE test.id = data.id""", ... [(1, 20), (4, 50)]) >>> cur.execute("select * from test order by id") >>> cur.fetchall() [(1, 20, 3), (4, 50, 6), (7, 8, 9)]) ''' # we can't just use sql % vals because vals is bytes: if sql is bytes # there will be some decoding error because of stupid codec used, and Py3 # doesn't implement % on bytes. if not isinstance(sql, bytes): sql = sql.encode(_ext.encodings[cur.connection.encoding]) pre, post = _split_sql(sql) for page in _paginate(argslist, page_size=page_size): if template is None: template = b'(' + b','.join([b'%s'] * len(page[0])) + b')' parts = pre[:] for args in page: parts.append(cur.mogrify(template, args)) parts.append(b',') parts[-1:] = post cur.execute(b''.join(parts)) def _split_sql(sql): """Split *sql* on a single ``%s`` placeholder. Split on the %s, perform %% replacement and return pre, post lists of snippets. """ curr = pre = [] post = [] tokens = _re.split(br'(%.)', sql) for token in tokens: if len(token) != 2 or token[:1] != b'%': curr.append(token) continue if token[1:] == b's': if curr is pre: curr = post else: raise ValueError( "the query contains more than one '%s' placeholder") elif token[1:] == b'%': curr.append(b'%') else: raise ValueError("unsupported format character: '%s'" % token[1:].decode('ascii', 'replace')) if curr is pre: raise ValueError("the query doesn't contain any '%s' placeholder") return pre, post
mit
espadrine/opera
chromium/src/third_party/protobuf/python/google/protobuf/internal/wire_format.py
561
8431
# Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # http://code.google.com/p/protobuf/ # # 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. """Constants and static functions to support protocol buffer wire format.""" __author__ = 'robinson@google.com (Will Robinson)' import struct from google.protobuf import descriptor from google.protobuf import message TAG_TYPE_BITS = 3 # Number of bits used to hold type info in a proto tag. TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1 # 0x7 # These numbers identify the wire type of a protocol buffer value. # We use the least-significant TAG_TYPE_BITS bits of the varint-encoded # tag-and-type to store one of these WIRETYPE_* constants. # These values must match WireType enum in google/protobuf/wire_format.h. WIRETYPE_VARINT = 0 WIRETYPE_FIXED64 = 1 WIRETYPE_LENGTH_DELIMITED = 2 WIRETYPE_START_GROUP = 3 WIRETYPE_END_GROUP = 4 WIRETYPE_FIXED32 = 5 _WIRETYPE_MAX = 5 # Bounds for various integer types. INT32_MAX = int((1 << 31) - 1) INT32_MIN = int(-(1 << 31)) UINT32_MAX = (1 << 32) - 1 INT64_MAX = (1 << 63) - 1 INT64_MIN = -(1 << 63) UINT64_MAX = (1 << 64) - 1 # "struct" format strings that will encode/decode the specified formats. FORMAT_UINT32_LITTLE_ENDIAN = '<I' FORMAT_UINT64_LITTLE_ENDIAN = '<Q' FORMAT_FLOAT_LITTLE_ENDIAN = '<f' FORMAT_DOUBLE_LITTLE_ENDIAN = '<d' # We'll have to provide alternate implementations of AppendLittleEndian*() on # any architectures where these checks fail. if struct.calcsize(FORMAT_UINT32_LITTLE_ENDIAN) != 4: raise AssertionError('Format "I" is not a 32-bit number.') if struct.calcsize(FORMAT_UINT64_LITTLE_ENDIAN) != 8: raise AssertionError('Format "Q" is not a 64-bit number.') def PackTag(field_number, wire_type): """Returns an unsigned 32-bit integer that encodes the field number and wire type information in standard protocol message wire format. Args: field_number: Expected to be an integer in the range [1, 1 << 29) wire_type: One of the WIRETYPE_* constants. """ if not 0 <= wire_type <= _WIRETYPE_MAX: raise message.EncodeError('Unknown wire type: %d' % wire_type) return (field_number << TAG_TYPE_BITS) | wire_type def UnpackTag(tag): """The inverse of PackTag(). Given an unsigned 32-bit number, returns a (field_number, wire_type) tuple. """ return (tag >> TAG_TYPE_BITS), (tag & TAG_TYPE_MASK) def ZigZagEncode(value): """ZigZag Transform: Encodes signed integers so that they can be effectively used with varint encoding. See wire_format.h for more details. """ if value >= 0: return value << 1 return (value << 1) ^ (~0) def ZigZagDecode(value): """Inverse of ZigZagEncode().""" if not value & 0x1: return value >> 1 return (value >> 1) ^ (~0) # The *ByteSize() functions below return the number of bytes required to # serialize "field number + type" information and then serialize the value. def Int32ByteSize(field_number, int32): return Int64ByteSize(field_number, int32) def Int32ByteSizeNoTag(int32): return _VarUInt64ByteSizeNoTag(0xffffffffffffffff & int32) def Int64ByteSize(field_number, int64): # Have to convert to uint before calling UInt64ByteSize(). return UInt64ByteSize(field_number, 0xffffffffffffffff & int64) def UInt32ByteSize(field_number, uint32): return UInt64ByteSize(field_number, uint32) def UInt64ByteSize(field_number, uint64): return TagByteSize(field_number) + _VarUInt64ByteSizeNoTag(uint64) def SInt32ByteSize(field_number, int32): return UInt32ByteSize(field_number, ZigZagEncode(int32)) def SInt64ByteSize(field_number, int64): return UInt64ByteSize(field_number, ZigZagEncode(int64)) def Fixed32ByteSize(field_number, fixed32): return TagByteSize(field_number) + 4 def Fixed64ByteSize(field_number, fixed64): return TagByteSize(field_number) + 8 def SFixed32ByteSize(field_number, sfixed32): return TagByteSize(field_number) + 4 def SFixed64ByteSize(field_number, sfixed64): return TagByteSize(field_number) + 8 def FloatByteSize(field_number, flt): return TagByteSize(field_number) + 4 def DoubleByteSize(field_number, double): return TagByteSize(field_number) + 8 def BoolByteSize(field_number, b): return TagByteSize(field_number) + 1 def EnumByteSize(field_number, enum): return UInt32ByteSize(field_number, enum) def StringByteSize(field_number, string): return BytesByteSize(field_number, string.encode('utf-8')) def BytesByteSize(field_number, b): return (TagByteSize(field_number) + _VarUInt64ByteSizeNoTag(len(b)) + len(b)) def GroupByteSize(field_number, message): return (2 * TagByteSize(field_number) # START and END group. + message.ByteSize()) def MessageByteSize(field_number, message): return (TagByteSize(field_number) + _VarUInt64ByteSizeNoTag(message.ByteSize()) + message.ByteSize()) def MessageSetItemByteSize(field_number, msg): # First compute the sizes of the tags. # There are 2 tags for the beginning and ending of the repeated group, that # is field number 1, one with field number 2 (type_id) and one with field # number 3 (message). total_size = (2 * TagByteSize(1) + TagByteSize(2) + TagByteSize(3)) # Add the number of bytes for type_id. total_size += _VarUInt64ByteSizeNoTag(field_number) message_size = msg.ByteSize() # The number of bytes for encoding the length of the message. total_size += _VarUInt64ByteSizeNoTag(message_size) # The size of the message. total_size += message_size return total_size def TagByteSize(field_number): """Returns the bytes required to serialize a tag with this field number.""" # Just pass in type 0, since the type won't affect the tag+type size. return _VarUInt64ByteSizeNoTag(PackTag(field_number, 0)) # Private helper function for the *ByteSize() functions above. def _VarUInt64ByteSizeNoTag(uint64): """Returns the number of bytes required to serialize a single varint using boundary value comparisons. (unrolled loop optimization -WPierce) uint64 must be unsigned. """ if uint64 <= 0x7f: return 1 if uint64 <= 0x3fff: return 2 if uint64 <= 0x1fffff: return 3 if uint64 <= 0xfffffff: return 4 if uint64 <= 0x7ffffffff: return 5 if uint64 <= 0x3ffffffffff: return 6 if uint64 <= 0x1ffffffffffff: return 7 if uint64 <= 0xffffffffffffff: return 8 if uint64 <= 0x7fffffffffffffff: return 9 if uint64 > UINT64_MAX: raise message.EncodeError('Value out of range: %d' % uint64) return 10 NON_PACKABLE_TYPES = ( descriptor.FieldDescriptor.TYPE_STRING, descriptor.FieldDescriptor.TYPE_GROUP, descriptor.FieldDescriptor.TYPE_MESSAGE, descriptor.FieldDescriptor.TYPE_BYTES ) def IsTypePackable(field_type): """Return true iff packable = true is valid for fields of this type. Args: field_type: a FieldDescriptor::Type value. Returns: True iff fields of this type are packable. """ return field_type not in NON_PACKABLE_TYPES
bsd-3-clause
awkspace/ansible
lib/ansible/modules/network/f5/_bigip_gtm_facts.py
21
32103
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2017, F5 Networks Inc. # 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': ['deprecated'], 'supported_by': 'certified'} DOCUMENTATION = r''' --- module: bigip_gtm_facts short_description: Collect facts from F5 BIG-IP GTM devices description: - Collect facts from F5 BIG-IP GTM devices. version_added: 2.3 options: include: description: - Fact category to collect. required: True choices: - pool - wide_ip - server filter: description: - Perform regex filter of response. Filtering is done on the name of the resource. Valid filters are anything that can be provided to Python's C(re) module. deprecated: removed_in: '2.11' alternative: bigip_device_facts why: > The bigip_gtm_facts module is an outlier as all facts are being collected in the bigip_device_facts module. Additionally, the M(bigip_device_facts) module is easier to maintain and use. extends_documentation_fragment: f5 notes: - This module is deprecated. Use the C(bigip_device_facts) module instead. author: - Tim Rupp (@caphrim007) ''' EXAMPLES = r''' - name: Get pool facts bigip_gtm_facts: server: lb.mydomain.com user: admin password: secret include: pool filter: my_pool delegate_to: localhost ''' RETURN = r''' wide_ip: description: Contains the lb method for the wide ip and the pools that are within the wide ip. returned: changed type: list sample: wide_ip: - enabled: True failure_rcode: noerror failure_rcode_response: disabled failure_rcode_ttl: 0 full_path: /Common/foo.ok.com last_resort_pool: "" minimal_response: enabled name: foo.ok.com partition: Common persist_cidr_ipv4: 32 persist_cidr_ipv6: 128 persistence: disabled pool_lb_mode: round-robin pools: - name: d3qw order: 0 partition: Common ratio: 1 ttl_persistence: 3600 type: naptr pool: description: Contains the pool object status and enabled status. returned: changed type: list sample: pool: - alternate_mode: round-robin dynamic_ratio: disabled enabled: True fallback_mode: return-to-dns full_path: /Common/d3qw load_balancing_mode: round-robin manual_resume: disabled max_answers_returned: 1 members: - disabled: True flags: a full_path: ok3.com member_order: 0 name: ok3.com order: 10 preference: 10 ratio: 1 service: 80 name: d3qw partition: Common qos_hit_ratio: 5 qos_hops: 0 qos_kilobytes_second: 3 qos_lcs: 30 qos_packet_rate: 1 qos_rtt: 50 qos_topology: 0 qos_vs_capacity: 0 qos_vs_score: 0 availability_state: offline enabled_state: disabled ttl: 30 type: naptr verify_member_availability: disabled server: description: Contains the virtual server enabled and availability status, and address. returned: changed type: list sample: server: - addresses: - device_name: /Common/qweqwe name: 10.10.10.10 translation: none datacenter: /Common/xfxgh enabled: True expose_route_domains: no full_path: /Common/qweqwe iq_allow_path: yes iq_allow_service_check: yes iq_allow_snmp: yes limit_cpu_usage: 0 limit_cpu_usage_status: disabled limit_max_bps: 0 limit_max_bps_status: disabled limit_max_connections: 0 limit_max_connections_status: disabled limit_max_pps: 0 limit_max_pps_status: disabled limit_mem_avail: 0 limit_mem_avail_status: disabled link_discovery: disabled monitor: /Common/bigip name: qweqwe partition: Common product: single-bigip virtual_server_discovery: disabled virtual_servers: - destination: 10.10.10.10:0 enabled: True full_path: jsdfhsd limit_max_bps: 0 limit_max_bps_status: disabled limit_max_connections: 0 limit_max_connections_status: disabled limit_max_pps: 0 limit_max_pps_status: disabled name: jsdfhsd translation_address: none translation_port: 0 ''' import re from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six import iteritems from ansible.module_utils.parsing.convert_bool import BOOLEANS_TRUE from distutils.version import LooseVersion try: from f5.bigip import ManagementRoot from icontrol.exceptions import iControlUnexpectedHTTPError from f5.utils.responses.handlers import Stats HAS_F5SDK = True except ImportError: HAS_F5SDK = False try: from library.module_utils.network.f5.common import F5BaseClient except ImportError: from ansible.module_utils.network.f5.common import F5BaseClient try: from library.module_utils.network.f5.common import F5ModuleError from library.module_utils.network.f5.common import AnsibleF5Parameters from library.module_utils.network.f5.common import cleanup_tokens from library.module_utils.network.f5.common import f5_argument_spec except ImportError: from ansible.module_utils.network.f5.common import F5ModuleError from ansible.module_utils.network.f5.common import AnsibleF5Parameters from ansible.module_utils.network.f5.common import cleanup_tokens from ansible.module_utils.network.f5.common import f5_argument_spec class F5Client(F5BaseClient): def __init__(self, *args, **kwargs): super(F5Client, self).__init__(*args, **kwargs) self.provider = self.merge_provider_params() @property def api(self): if self._client: return self._client try: result = ManagementRoot( self.provider['server'], self.provider['user'], self.provider['password'], port=self.provider['server_port'], verify=self.provider['validate_certs'], token='tmos' ) self._client = result return self._client except Exception as ex: error = 'Unable to connect to {0} on port {1}. The reported error was "{2}".'.format( self.provider['server'], self.provider['server_port'], str(ex) ) raise F5ModuleError(error) class BaseManager(object): def __init__(self, *args, **kwargs): self.module = kwargs.get('module', None) self.client = kwargs.get('client', None) self.kwargs = kwargs self.types = dict( a_s='a', aaaas='aaaa', cnames='cname', mxs='mx', naptrs='naptr', srvs='srv' ) def filter_matches_name(self, name): if self.want.filter is None: return True matches = re.match(self.want.filter, str(name)) if matches: return True else: return False def version_is_less_than_12(self): version = self.client.api.tmos_version if LooseVersion(version) < LooseVersion('12.0.0'): return True else: return False def get_facts_from_collection(self, collection, collection_type=None): results = [] for item in collection: if not self.filter_matches_name(item.name): continue facts = self.format_facts(item, collection_type) results.append(facts) return results def read_stats_from_device(self, resource): stats = Stats(resource.stats.load()) return stats.stat class UntypedManager(BaseManager): def exec_module(self): results = [] facts = self.read_facts() for item in facts: attrs = item.to_return() filtered = [(k, v) for k, v in iteritems(attrs) if self.filter_matches_name(k)] if filtered: results.append(dict(filtered)) return results class TypedManager(BaseManager): def exec_module(self): results = [] for collection, type in iteritems(self.types): facts = self.read_facts(collection) if not facts: continue for x in facts: x.update({'type': type}) for item in facts: attrs = item.to_return() filtered = [(k, v) for k, v in iteritems(attrs) if self.filter_matches_name(k)] if filtered: results.append(dict(filtered)) return results class Parameters(AnsibleF5Parameters): @property def include(self): requested = self._values['include'] valid = ['pool', 'wide_ip', 'server', 'all'] if any(x for x in requested if x not in valid): raise F5ModuleError( "The valid 'include' choices are {0}".format(', '.join(valid)) ) if 'all' in requested: return ['all'] else: return requested class BaseParameters(Parameters): @property def enabled(self): if self._values['enabled'] is None: return None elif self._values['enabled'] in BOOLEANS_TRUE: return True else: return False @property def disabled(self): if self._values['disabled'] is None: return None elif self._values['disabled'] in BOOLEANS_TRUE: return True else: return False def _remove_internal_keywords(self, resource): resource.pop('kind', None) resource.pop('generation', None) resource.pop('selfLink', None) resource.pop('isSubcollection', None) resource.pop('fullPath', None) def to_return(self): result = {} for returnable in self.returnables: result[returnable] = getattr(self, returnable) result = self._filter_params(result) return result class PoolParameters(BaseParameters): api_map = { 'alternateMode': 'alternate_mode', 'dynamicRatio': 'dynamic_ratio', 'fallbackMode': 'fallback_mode', 'fullPath': 'full_path', 'loadBalancingMode': 'load_balancing_mode', 'manualResume': 'manual_resume', 'maxAnswersReturned': 'max_answers_returned', 'qosHitRatio': 'qos_hit_ratio', 'qosHops': 'qos_hops', 'qosKilobytesSecond': 'qos_kilobytes_second', 'qosLcs': 'qos_lcs', 'qosPacketRate': 'qos_packet_rate', 'qosRtt': 'qos_rtt', 'qosTopology': 'qos_topology', 'qosVsCapacity': 'qos_vs_capacity', 'qosVsScore': 'qos_vs_score', 'verifyMemberAvailability': 'verify_member_availability', 'membersReference': 'members' } returnables = [ 'alternate_mode', 'dynamic_ratio', 'enabled', 'disabled', 'fallback_mode', 'load_balancing_mode', 'manual_resume', 'max_answers_returned', 'members', 'name', 'partition', 'qos_hit_ratio', 'qos_hops', 'qos_kilobytes_second', 'qos_lcs', 'qos_packet_rate', 'qos_rtt', 'qos_topology', 'qos_vs_capacity', 'qos_vs_score', 'ttl', 'type', 'full_path', 'availability_state', 'enabled_state', 'availability_status' ] @property def max_answers_returned(self): if self._values['max_answers_returned'] is None: return None return int(self._values['max_answers_returned']) @property def members(self): result = [] if self._values['members'] is None or 'items' not in self._values['members']: return result for item in self._values['members']['items']: self._remove_internal_keywords(item) if 'disabled' in item: if item['disabled'] in BOOLEANS_TRUE: item['disabled'] = True else: item['disabled'] = False if 'enabled' in item: if item['enabled'] in BOOLEANS_TRUE: item['enabled'] = True else: item['enabled'] = False if 'fullPath' in item: item['full_path'] = item.pop('fullPath') if 'memberOrder' in item: item['member_order'] = int(item.pop('memberOrder')) # Cast some attributes to integer for x in ['order', 'preference', 'ratio', 'service']: if x in item: item[x] = int(item[x]) result.append(item) return result @property def qos_hit_ratio(self): if self._values['qos_hit_ratio'] is None: return None return int(self._values['qos_hit_ratio']) @property def qos_hops(self): if self._values['qos_hops'] is None: return None return int(self._values['qos_hops']) @property def qos_kilobytes_second(self): if self._values['qos_kilobytes_second'] is None: return None return int(self._values['qos_kilobytes_second']) @property def qos_lcs(self): if self._values['qos_lcs'] is None: return None return int(self._values['qos_lcs']) @property def qos_packet_rate(self): if self._values['qos_packet_rate'] is None: return None return int(self._values['qos_packet_rate']) @property def qos_rtt(self): if self._values['qos_rtt'] is None: return None return int(self._values['qos_rtt']) @property def qos_topology(self): if self._values['qos_topology'] is None: return None return int(self._values['qos_topology']) @property def qos_vs_capacity(self): if self._values['qos_vs_capacity'] is None: return None return int(self._values['qos_vs_capacity']) @property def qos_vs_score(self): if self._values['qos_vs_score'] is None: return None return int(self._values['qos_vs_score']) @property def availability_state(self): if self._values['stats'] is None: return None try: result = self._values['stats']['status_availabilityState'] return result['description'] except AttributeError: return None @property def enabled_state(self): if self._values['stats'] is None: return None try: result = self._values['stats']['status_enabledState'] return result['description'] except AttributeError: return None @property def availability_status(self): # This fact is a combination of the availability_state and enabled_state # # The purpose of the fact is to give a higher-level view of the availability # of the pool, that can be used in playbooks. If you need further detail, # consider using the following facts together. # # - availability_state # - enabled_state # if self.enabled_state == 'enabled': if self.availability_state == 'offline': return 'red' elif self.availability_state == 'available': return 'green' elif self.availability_state == 'unknown': return 'blue' else: return 'none' else: # disabled return 'black' class WideIpParameters(BaseParameters): api_map = { 'fullPath': 'full_path', 'failureRcode': 'failure_return_code', 'failureRcodeResponse': 'failure_return_code_response', 'failureRcodeTtl': 'failure_return_code_ttl', 'lastResortPool': 'last_resort_pool', 'minimalResponse': 'minimal_response', 'persistCidrIpv4': 'persist_cidr_ipv4', 'persistCidrIpv6': 'persist_cidr_ipv6', 'poolLbMode': 'pool_lb_mode', 'ttlPersistence': 'ttl_persistence' } returnables = [ 'full_path', 'description', 'enabled', 'disabled', 'failure_return_code', 'failure_return_code_response', 'failure_return_code_ttl', 'last_resort_pool', 'minimal_response', 'persist_cidr_ipv4', 'persist_cidr_ipv6', 'pool_lb_mode', 'ttl_persistence', 'pools' ] @property def pools(self): result = [] if self._values['pools'] is None: return [] for pool in self._values['pools']: del pool['nameReference'] for x in ['order', 'ratio']: if x in pool: pool[x] = int(pool[x]) result.append(pool) return result @property def failure_return_code_ttl(self): if self._values['failure_return_code_ttl'] is None: return None return int(self._values['failure_return_code_ttl']) @property def persist_cidr_ipv4(self): if self._values['persist_cidr_ipv4'] is None: return None return int(self._values['persist_cidr_ipv4']) @property def persist_cidr_ipv6(self): if self._values['persist_cidr_ipv6'] is None: return None return int(self._values['persist_cidr_ipv6']) @property def ttl_persistence(self): if self._values['ttl_persistence'] is None: return None return int(self._values['ttl_persistence']) class ServerParameters(BaseParameters): api_map = { 'fullPath': 'full_path', 'exposeRouteDomains': 'expose_route_domains', 'iqAllowPath': 'iq_allow_path', 'iqAllowServiceCheck': 'iq_allow_service_check', 'iqAllowSnmp': 'iq_allow_snmp', 'limitCpuUsage': 'limit_cpu_usage', 'limitCpuUsageStatus': 'limit_cpu_usage_status', 'limitMaxBps': 'limit_max_bps', 'limitMaxBpsStatus': 'limit_max_bps_status', 'limitMaxConnections': 'limit_max_connections', 'limitMaxConnectionsStatus': 'limit_max_connections_status', 'limitMaxPps': 'limit_max_pps', 'limitMaxPpsStatus': 'limit_max_pps_status', 'limitMemAvail': 'limit_mem_available', 'limitMemAvailStatus': 'limit_mem_available_status', 'linkDiscovery': 'link_discovery', 'proberFallback': 'prober_fallback', 'proberPreference': 'prober_preference', 'virtualServerDiscovery': 'virtual_server_discovery', 'devicesReference': 'devices', 'virtualServersReference': 'virtual_servers' } returnables = [ 'datacenter', 'enabled', 'disabled', 'expose_route_domains', 'iq_allow_path', 'full_path', 'iq_allow_service_check', 'iq_allow_snmp', 'limit_cpu_usage', 'limit_cpu_usage_status', 'limit_max_bps', 'limit_max_bps_status', 'limit_max_connections', 'limit_max_connections_status', 'limit_max_pps', 'limit_max_pps_status', 'limit_mem_available', 'limit_mem_available_status', 'link_discovery', 'monitor', 'product', 'prober_fallback', 'prober_preference', 'virtual_server_discovery', 'addresses', 'devices', 'virtual_servers' ] @property def product(self): if self._values['product'] is None: return None if self._values['product'] in ['single-bigip', 'redundant-bigip']: return 'bigip' return self._values['product'] @property def devices(self): result = [] if self._values['devices'] is None or 'items' not in self._values['devices']: return result for item in self._values['devices']['items']: self._remove_internal_keywords(item) if 'fullPath' in item: item['full_path'] = item.pop('fullPath') result.append(item) return result @property def virtual_servers(self): result = [] if self._values['virtual_servers'] is None or 'items' not in self._values['virtual_servers']: return result for item in self._values['virtual_servers']['items']: self._remove_internal_keywords(item) if 'disabled' in item: if item['disabled'] in BOOLEANS_TRUE: item['disabled'] = True else: item['disabled'] = False if 'enabled' in item: if item['enabled'] in BOOLEANS_TRUE: item['enabled'] = True else: item['enabled'] = False if 'fullPath' in item: item['full_path'] = item.pop('fullPath') if 'limitMaxBps' in item: item['limit_max_bps'] = int(item.pop('limitMaxBps')) if 'limitMaxBpsStatus' in item: item['limit_max_bps_status'] = item.pop('limitMaxBpsStatus') if 'limitMaxConnections' in item: item['limit_max_connections'] = int(item.pop('limitMaxConnections')) if 'limitMaxConnectionsStatus' in item: item['limit_max_connections_status'] = item.pop('limitMaxConnectionsStatus') if 'limitMaxPps' in item: item['limit_max_pps'] = int(item.pop('limitMaxPps')) if 'limitMaxPpsStatus' in item: item['limit_max_pps_status'] = item.pop('limitMaxPpsStatus') if 'translationAddress' in item: item['translation_address'] = item.pop('translationAddress') if 'translationPort' in item: item['translation_port'] = int(item.pop('translationPort')) result.append(item) return result @property def limit_cpu_usage(self): if self._values['limit_cpu_usage'] is None: return None return int(self._values['limit_cpu_usage']) @property def limit_max_bps(self): if self._values['limit_max_bps'] is None: return None return int(self._values['limit_max_bps']) @property def limit_max_connections(self): if self._values['limit_max_connections'] is None: return None return int(self._values['limit_max_connections']) @property def limit_max_pps(self): if self._values['limit_max_pps'] is None: return None return int(self._values['limit_max_pps']) @property def limit_mem_available(self): if self._values['limit_mem_available'] is None: return None return int(self._values['limit_mem_available']) class PoolFactManager(BaseManager): def __init__(self, *args, **kwargs): self.module = kwargs.get('module', None) self.client = kwargs.get('client', None) super(PoolFactManager, self).__init__(**kwargs) self.kwargs = kwargs def exec_module(self): if self.version_is_less_than_12(): manager = self.get_manager('untyped') else: manager = self.get_manager('typed') facts = manager.exec_module() result = dict(pool=facts) return result def get_manager(self, type): if type == 'typed': return TypedPoolFactManager(**self.kwargs) elif type == 'untyped': return UntypedPoolFactManager(**self.kwargs) class TypedPoolFactManager(TypedManager): def __init__(self, *args, **kwargs): self.module = kwargs.get('module', None) self.client = kwargs.get('client', None) super(TypedPoolFactManager, self).__init__(**kwargs) self.want = PoolParameters(params=self.module.params) def read_facts(self, collection): results = [] collection = self.read_collection_from_device(collection) for resource in collection: attrs = resource.attrs attrs['stats'] = self.read_stats_from_device(resource) params = PoolParameters(params=attrs) results.append(params) return results def read_collection_from_device(self, collection_name): pools = self.client.api.tm.gtm.pools collection = getattr(pools, collection_name) result = collection.get_collection( requests_params=dict( params='expandSubcollections=true' ) ) return result class UntypedPoolFactManager(UntypedManager): def __init__(self, *args, **kwargs): self.client = kwargs.get('client', None) self.module = kwargs.get('module', None) super(UntypedPoolFactManager, self).__init__(**kwargs) self.want = PoolParameters(params=self.module.params) def read_facts(self): results = [] collection = self.read_collection_from_device() for resource in collection: attrs = resource.attrs attrs['stats'] = self.read_stats_from_device(resource) params = PoolParameters(params=attrs) results.append(params) return results def read_collection_from_device(self): result = self.client.api.tm.gtm.pools.get_collection( requests_params=dict( params='expandSubcollections=true' ) ) return result class WideIpFactManager(BaseManager): def exec_module(self): if self.version_is_less_than_12(): manager = self.get_manager('untyped') else: manager = self.get_manager('typed') facts = manager.exec_module() result = dict(wide_ip=facts) return result def get_manager(self, type): if type == 'typed': return TypedWideIpFactManager(**self.kwargs) elif type == 'untyped': return UntypedWideIpFactManager(**self.kwargs) class TypedWideIpFactManager(TypedManager): def __init__(self, *args, **kwargs): self.client = kwargs.get('client', None) self.module = kwargs.get('module', None) super(TypedWideIpFactManager, self).__init__(**kwargs) self.want = WideIpParameters(params=self.module.params) def read_facts(self, collection): results = [] collection = self.read_collection_from_device(collection) for resource in collection: attrs = resource.attrs params = WideIpParameters(params=attrs) results.append(params) return results def read_collection_from_device(self, collection_name): wideips = self.client.api.tm.gtm.wideips collection = getattr(wideips, collection_name) result = collection.get_collection( requests_params=dict( params='expandSubcollections=true' ) ) return result class UntypedWideIpFactManager(UntypedManager): def __init__(self, *args, **kwargs): self.client = kwargs.get('client', None) self.module = kwargs.get('module', None) super(UntypedWideIpFactManager, self).__init__(**kwargs) self.want = WideIpParameters(params=self.module.params) def read_facts(self): results = [] collection = self.read_collection_from_device() for resource in collection: attrs = resource.attrs params = WideIpParameters(params=attrs) results.append(params) return results def read_collection_from_device(self): result = self.client.api.tm.gtm.wideips.get_collection( requests_params=dict( params='expandSubcollections=true' ) ) return result class ServerFactManager(UntypedManager): def __init__(self, *args, **kwargs): self.client = kwargs.get('client', None) self.module = kwargs.get('module', None) super(ServerFactManager, self).__init__(**kwargs) self.want = ServerParameters(params=self.module.params) def exec_module(self): facts = super(ServerFactManager, self).exec_module() result = dict(server=facts) return result def read_facts(self): results = [] collection = self.read_collection_from_device() for resource in collection: attrs = resource.attrs params = ServerParameters(params=attrs) results.append(params) return results def read_collection_from_device(self): result = self.client.api.tm.gtm.servers.get_collection( requests_params=dict( params='expandSubcollections=true' ) ) return result class ModuleManager(object): def __init__(self, *args, **kwargs): self.module = kwargs.get('module', None) self.client = kwargs.get('client', None) self.kwargs = kwargs self.want = Parameters(params=self.module.params) def exec_module(self): if not self.gtm_provisioned(): raise F5ModuleError( "GTM must be provisioned to use this module." ) if 'all' in self.want.include: names = ['pool', 'wide_ip', 'server'] else: names = self.want.include managers = [self.get_manager(name) for name in names] result = self.execute_managers(managers) if result: result['changed'] = True else: result['changed'] = False self._announce_deprecations() return result def _announce_deprecations(self): warnings = [] if self.want: warnings += self.want._values.get('__warnings', []) for warning in warnings: self.module.deprecate( msg=warning['msg'], version=warning['version'] ) def execute_managers(self, managers): results = dict() for manager in managers: result = manager.exec_module() results.update(result) return results def get_manager(self, which): if 'pool' == which: return PoolFactManager(**self.kwargs) if 'wide_ip' == which: return WideIpFactManager(**self.kwargs) if 'server' == which: return ServerFactManager(**self.kwargs) def gtm_provisioned(self): resource = self.client.api.tm.sys.dbs.db.load( name='provisioned.cpu.gtm' ) if int(resource.value) == 0: return False return True class ArgumentSpec(object): def __init__(self): self.supports_check_mode = False argument_spec = dict( include=dict( type='list', choices=[ 'pool', 'wide_ip', 'server', ], required=True ), filter=dict() ) self.argument_spec = {} self.argument_spec.update(f5_argument_spec) self.argument_spec.update(argument_spec) def main(): spec = ArgumentSpec() module = AnsibleModule( argument_spec=spec.argument_spec, supports_check_mode=spec.supports_check_mode ) if not HAS_F5SDK: module.fail_json(msg="The python f5-sdk module is required") client = F5Client(**module.params) try: mm = ModuleManager(module=module, client=client) results = mm.exec_module() cleanup_tokens(client) module.exit_json(**results) except F5ModuleError as ex: cleanup_tokens(client) module.fail_json(msg=str(ex)) if __name__ == '__main__': main()
gpl-3.0
ljhljh235/AutoRest
src/generator/AutoRest.Python.Tests/Expected/AcceptanceTests/ModelFlattening/setup.py
28
1139
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- # coding: utf-8 from setuptools import setup, find_packages NAME = "autorestresourceflatteningtestservice" VERSION = "1.0.0" # To install the library, run the following # # python setup.py install # # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, version=VERSION, description="AutoRestResourceFlatteningTestService", author_email="", url="", keywords=["Swagger", "AutoRestResourceFlatteningTestService"], install_requires=REQUIRES, packages=find_packages(), include_package_data=True, long_description="""\ Resource Flattening for AutoRest """ )
mit
rvalyi/OpenUpgrade
addons/auth_openid/__openerp__.py
62
1630
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010-2012 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/>. # ############################################################################## { 'name': 'OpenID Authentification', 'version': '2.0', 'category': 'Tools', 'description': """ Allow users to login through OpenID. ==================================== """, 'author': 'OpenERP s.a.', 'maintainer': 'OpenERP s.a.', 'website': 'http://www.openerp.com', 'depends': ['base', 'web'], 'data': [ 'res_users.xml', 'views/auth_openid.xml', ], 'qweb': ['static/src/xml/auth_openid.xml'], 'external_dependencies': { 'python' : ['openid'], }, 'installable': True, 'auto_install': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
x303597316/hue
desktop/core/ext-py/Django-1.6.10/django/core/handlers/base.py
74
12481
from __future__ import unicode_literals import logging import sys import types from django import http from django.conf import settings from django.core import urlresolvers from django.core import signals from django.core.exceptions import MiddlewareNotUsed, PermissionDenied, SuspiciousOperation from django.db import connections, transaction from django.utils.encoding import force_text from django.utils.module_loading import import_by_path from django.utils import six from django.views import debug logger = logging.getLogger('django.request') class BaseHandler(object): # Changes that are always applied to a response (in this order). response_fixes = [ http.fix_location_header, http.conditional_content_removal, ] def __init__(self): self._request_middleware = self._view_middleware = self._template_response_middleware = self._response_middleware = self._exception_middleware = None def load_middleware(self): """ Populate middleware lists from settings.MIDDLEWARE_CLASSES. Must be called after the environment is fixed (see __call__ in subclasses). """ self._view_middleware = [] self._template_response_middleware = [] self._response_middleware = [] self._exception_middleware = [] request_middleware = [] for middleware_path in settings.MIDDLEWARE_CLASSES: mw_class = import_by_path(middleware_path) try: mw_instance = mw_class() except MiddlewareNotUsed: continue if hasattr(mw_instance, 'process_request'): request_middleware.append(mw_instance.process_request) if hasattr(mw_instance, 'process_view'): self._view_middleware.append(mw_instance.process_view) if hasattr(mw_instance, 'process_template_response'): self._template_response_middleware.insert(0, mw_instance.process_template_response) if hasattr(mw_instance, 'process_response'): self._response_middleware.insert(0, mw_instance.process_response) if hasattr(mw_instance, 'process_exception'): self._exception_middleware.insert(0, mw_instance.process_exception) # We only assign to this when initialization is complete as it is used # as a flag for initialization being complete. self._request_middleware = request_middleware def make_view_atomic(self, view): non_atomic_requests = getattr(view, '_non_atomic_requests', set()) for db in connections.all(): if (db.settings_dict['ATOMIC_REQUESTS'] and db.alias not in non_atomic_requests): view = transaction.atomic(using=db.alias)(view) return view def get_response(self, request): "Returns an HttpResponse object for the given HttpRequest" # Setup default url resolver for this thread, this code is outside # the try/except so we don't get a spurious "unbound local # variable" exception in the event an exception is raised before # resolver is set urlconf = settings.ROOT_URLCONF urlresolvers.set_urlconf(urlconf) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) try: response = None # Apply request middleware for middleware_method in self._request_middleware: response = middleware_method(request) if response: break if response is None: if hasattr(request, 'urlconf'): # Reset url resolver with a custom urlconf. urlconf = request.urlconf urlresolvers.set_urlconf(urlconf) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) resolver_match = resolver.resolve(request.path_info) callback, callback_args, callback_kwargs = resolver_match request.resolver_match = resolver_match # Apply view middleware for middleware_method in self._view_middleware: response = middleware_method(request, callback, callback_args, callback_kwargs) if response: break if response is None: wrapped_callback = self.make_view_atomic(callback) try: response = wrapped_callback(request, *callback_args, **callback_kwargs) except Exception as e: # If the view raised an exception, run it through exception # middleware, and if the exception middleware returns a # response, use that. Otherwise, reraise the exception. for middleware_method in self._exception_middleware: response = middleware_method(request, e) if response: break if response is None: raise # Complain if the view returned None (a common error). if response is None: if isinstance(callback, types.FunctionType): # FBV view_name = callback.__name__ else: # CBV view_name = callback.__class__.__name__ + '.__call__' raise ValueError("The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name)) # If the response supports deferred rendering, apply template # response middleware and then render the response if hasattr(response, 'render') and callable(response.render): for middleware_method in self._template_response_middleware: response = middleware_method(request, response) response = response.render() except http.Http404 as e: logger.warning('Not Found: %s', request.path, extra={ 'status_code': 404, 'request': request }) if settings.DEBUG: response = debug.technical_404_response(request, e) else: try: callback, param_dict = resolver.resolve404() response = callback(request, **param_dict) except: signals.got_request_exception.send(sender=self.__class__, request=request) response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) except PermissionDenied: logger.warning( 'Forbidden (Permission denied): %s', request.path, extra={ 'status_code': 403, 'request': request }) try: callback, param_dict = resolver.resolve403() response = callback(request, **param_dict) except: signals.got_request_exception.send( sender=self.__class__, request=request) response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) except SuspiciousOperation as e: # The request logger receives events for any problematic request # The security logger receives events for all SuspiciousOperations security_logger = logging.getLogger('django.security.%s' % e.__class__.__name__) security_logger.error(force_text(e)) try: callback, param_dict = resolver.resolve400() response = callback(request, **param_dict) except: signals.got_request_exception.send( sender=self.__class__, request=request) response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) except SystemExit: # Allow sys.exit() to actually exit. See tickets #1023 and #4701 raise except: # Handle everything else. # Get the exception info now, in case another exception is thrown later. signals.got_request_exception.send(sender=self.__class__, request=request) response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) try: # Apply response middleware, regardless of the response for middleware_method in self._response_middleware: response = middleware_method(request, response) response = self.apply_response_fixes(request, response) except: # Any exception should be gathered and handled signals.got_request_exception.send(sender=self.__class__, request=request) response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) return response def handle_uncaught_exception(self, request, resolver, exc_info): """ Processing for any otherwise uncaught exceptions (those that will generate HTTP 500 responses). Can be overridden by subclasses who want customised 500 handling. Be *very* careful when overriding this because the error could be caused by anything, so assuming something like the database is always available would be an error. """ if settings.DEBUG_PROPAGATE_EXCEPTIONS: raise logger.error('Internal Server Error: %s', request.path, exc_info=exc_info, extra={ 'status_code': 500, 'request': request } ) if settings.DEBUG: return debug.technical_500_response(request, *exc_info) # If Http500 handler is not installed, re-raise last exception if resolver.urlconf_module is None: six.reraise(*exc_info) # Return an HttpResponse that displays a friendly error message. callback, param_dict = resolver.resolve500() return callback(request, **param_dict) def apply_response_fixes(self, request, response): """ Applies each of the functions in self.response_fixes to the request and response, modifying the response in the process. Returns the new response. """ for func in self.response_fixes: response = func(request, response) return response def get_path_info(environ): """ Returns the HTTP request's PATH_INFO as a unicode string. """ path_info = environ.get('PATH_INFO', str('/')) # Under Python 3, strings in environ are decoded with ISO-8859-1; # re-encode to recover the original bytestring provided by the web server. if six.PY3: path_info = path_info.encode('iso-8859-1') # It'd be better to implement URI-to-IRI decoding, see #19508. return path_info.decode('utf-8') def get_script_name(environ): """ Returns the equivalent of the HTTP request's SCRIPT_NAME environment variable. If Apache mod_rewrite has been used, returns what would have been the script name prior to any rewriting (so it's the script name as seen from the client's perspective), unless the FORCE_SCRIPT_NAME setting is set (to anything). """ if settings.FORCE_SCRIPT_NAME is not None: return force_text(settings.FORCE_SCRIPT_NAME) # If Apache's mod_rewrite had a whack at the URL, Apache set either # SCRIPT_URL or REDIRECT_URL to the full resource URL before applying any # rewrites. Unfortunately not every Web server (lighttpd!) passes this # information through all the time, so FORCE_SCRIPT_NAME, above, is still # needed. script_url = environ.get('SCRIPT_URL', environ.get('REDIRECT_URL', str(''))) if script_url: script_name = script_url[:-len(environ.get('PATH_INFO', str('')))] else: script_name = environ.get('SCRIPT_NAME', str('')) # Under Python 3, strings in environ are decoded with ISO-8859-1; # re-encode to recover the original bytestring provided by the web server. if six.PY3: script_name = script_name.encode('iso-8859-1') # It'd be better to implement URI-to-IRI decoding, see #19508. return script_name.decode('utf-8')
apache-2.0
damilare/opencore
opencore/utilities/converters/tests.py
3
7994
# -*- coding: iso-8859-15 -*- # Copyright (C) 2008-2009 Open Society Institute # Thomas Moroz: tmoroz.org # 2010-2011 Large Blue # Fergus Doyle: fergus.doyle@largeblue.com # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License Version 2 as published # by the Free Software Foundation. You may not use, modify or distribute # this program under any other version of the GNU General Public License. # # 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. import unittest class BaseConverterTests(unittest.TestCase): def _getTargetClass(self): from opencore.utilities.converters.baseconverter import BaseConverter return BaseConverter def _makeOne(self, content_type='text/plain', content_description='Testing', depends_on='ls', ): class Derived(self._getTargetClass()): def __init__(self): pass # suppress st00pid error checking derived = Derived() derived.content_type = (content_type,) derived.content_description = content_description derived.depends_on = depends_on return derived def test_getDescription(self): converter = self._makeOne() self.assertEqual(converter.getDescription(), 'Testing') def test_getType(self): converter = self._makeOne() self.assertEqual(converter.getType(), ('text/plain',)) def test_getDependency(self): converter = self._makeOne() self.assertEqual(converter.getDependency(), 'ls') def test_isAvailable_empty_depends_on(self): converter = self._makeOne(depends_on='') self.assertEqual(converter.isAvailable(), 'always') def test_isAvailable_missing_depends_on(self): converter = self._makeOne(depends_on='nonesuchanimalcanexist') self.assertEqual(converter.isAvailable(), 'no') def test_isAvailable_valid_depends_on(self): converter = self._makeOne(depends_on='ls') self.assertEqual(converter.isAvailable(), 'yes') def test_hanging_converter(self): from opencore.utilities.converters.baseconverter import BaseConverter class HangingConverter(BaseConverter): content_type = "Up Your Nose" content_description = "With a Rubber Hose" timeout = 0.5 def convert(self): return self.execute('grep . /dev/zero') out = HangingConverter().convert() self.assertEqual(0, len(out.read())) class ConverterTests(unittest.TestCase): def testHTML(self): body = u'<html><body> alle Vögel Über Flügel und Tümpel</body></html>' utf8doc = u'alle Vögel Über Flügel und Tümpel'.encode('utf-8') import tempfile doc = tempfile.NamedTemporaryFile() doc.write(body.encode('iso-8859-15')) doc.flush() from opencore.utilities.converters import html C = html.Converter() stream, enc = C.convert(doc.name, 'iso-8859-15', 'text/html') text = stream.read().strip() self.assertEqual(enc, 'utf-8') self.assertEqual(text, utf8doc) import tempfile doc = tempfile.NamedTemporaryFile() doc.write(body.encode('utf-8')) doc.flush() stream, enc = C.convert(doc.name, 'utf8', 'text/html') text = stream.read().strip() self.assertEqual(enc, 'utf-8') self.assertEqual(text, utf8doc) def testHTMLWithEntities(self): body = (u'<html><body> alle V&ouml;gel &Uuml;ber Fl&uuml;gel ' u'und T&uuml;mpel</body></html>') utf8doc = u'alle Vögel Über Flügel und Tümpel'.encode('utf-8') from opencore.utilities.converters import html import tempfile C = html.Converter() doc = tempfile.NamedTemporaryFile() doc.write(body.encode('iso-8859-15')) doc.flush() stream, enc = C.convert(doc.name, 'iso-8859-15', 'text/html') text = stream.read().strip() self.assertEqual(enc, 'utf-8') self.assertEqual(text, utf8doc) doc = tempfile.NamedTemporaryFile() doc.write(body.encode('utf-8')) doc.flush() stream, enc = C.convert(doc.name, 'utf8', 'text/html') text = stream.read().strip() self.assertEqual(enc, 'utf-8') self.assertEqual(text, utf8doc) def testHTMLWithNumericEntities(self): body = (u'<html><body>Non&#160;breaking&#160;space.</body></html>') utf8doc = u'Non breaking space.'.encode('utf-8') from opencore.utilities.converters import html import tempfile C = html.Converter() doc = tempfile.NamedTemporaryFile() doc.write(body.encode('iso-8859-15')) doc.flush() stream, enc = C.convert(doc.name, 'iso-8859-15', 'text/html') text = stream.read().strip() self.assertEqual(enc, 'utf-8') self.assertEqual(text, utf8doc) doc = tempfile.NamedTemporaryFile() doc.write(body.encode('utf-8')) doc.flush() stream, enc = C.convert(doc.name, 'utf8', 'text/html') text = stream.read().strip() self.assertEqual(enc, 'utf-8') self.assertEqual(text, utf8doc) def testXML(self): body = ('<?xml version="1.0" encoding="iso-8859-15" ?><body> ' 'alle Vögel Über Flügel und Tümpel</body>') utf8doc = u'alle Vögel Über Flügel und Tümpel'.encode('utf-8') from opencore.utilities.converters import sgml import tempfile C = sgml.Converter() doc = tempfile.NamedTemporaryFile() doc.write(body) doc.flush() # encoding should be taken from the preamble stream, enc = C.convert(doc.name, 'utf8', 'text/html') text = stream.read().strip() self.assertEqual(enc, 'utf-8') self.assertEqual(text, utf8doc) def testOpenOffice(self): import os fn = os.path.join(os.path.dirname(__file__), 'fixtures', 'test.sxw') from opencore.utilities.converters import ooffice C = ooffice.Converter() # encoding should be taken from the preamble stream, enc = C.convert(fn, 'utf8', 'text/html') expected = (u'Viel Vögel sprangen artig in den Tüpel und über ' u'Feld und Wüste') expected_words = [w.strip() for w in expected.encode(enc).split() if w.strip()] got_words = [w.strip() for w in stream.read().split() if w.strip()] self.assertEqual(got_words, expected_words) def testPDF(self): import os fn = os.path.join(os.path.dirname(__file__), 'fixtures', 'test.pdf') from opencore.utilities.converters import pdf C = pdf.Converter() if C.isAvailable() == 'yes': # encoding should be taken from the preamble stream, enc = C.convert(fn, 'utf8', 'text/html') expected = (u'Viel Vögel sprangen artig in den Tüpel und über ' u'Feld und Wüste') expected_words = [w.strip() for w in expected.encode(enc).split() if w.strip()] got_words = [w.strip() for w in stream.read().split() if w.strip()] self.assertEqual(got_words, expected_words) else: import logging logging.debug('Omitting test for PDF converter as the converter is unavailable')
gpl-2.0
Antiun/connector-magento
magentoerpconnect_order_comment/__openerp__.py
11
2018
# -*- coding: utf-8 -*- ############################################################################## # # Author: David BEAL Copyright 2014 Akretion # # 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': 'Magento Connector - Order comment', 'version': '0.1', 'category': 'Connector', 'depends': ['magentoerpconnect', ], 'author': "Akretion,Odoo Community Association (OCA)", 'license': 'AGPL-3', 'website': 'http://www.odoo-magento-connector.com', 'description': """ Sale order comments synchronisation =================================== Extension for **Magento Connector** Features -------- * Import sale comments in the same time than 'sale order' * Move messages from canceled order to replacing sale order (edited sale order in magento) * Export messages from OpenERP sale order to Magento comment * Export of moved messages to Magento Settings / options ------------------ * Ability to require Magento to send email to customer for each comment received. Unactive by default (Connectors/Magento/Store menu). """, 'images': [], 'demo': [], 'external_dependencies': { 'python': ['bs4'], }, 'data': [ 'magento_model_view.xml', ], 'installable': False, 'application': False, }
agpl-3.0
lwbrooke/slackbot
fangorn/records.py
1
3467
from .configuration import config from collections import namedtuple from datetime import datetime, timezone from os.path import expanduser import falcon import json import marshmallow class TinnitusRecorder: def __init__(self): self._schema = SlashCommandDataSchema(config['slack']['tinnitus_command']['token']) self._record_writer = TinnitusWriter(config['records']['tinnitus']['path']) def on_post(self, req, resp): data, err = self._schema.load(req.params) if err: resp.body = json.dumps({ 'text': 'invalid command format: {}'.format(req.params['text']), 'attachments': [ { 'text': json.dumps(err) } ], 'response_type': 'ephemeral' }) resp.status = falcon.HTTP_OK return record = {**data.text, **{'recorded_time': datetime.now(timezone.utc).isoformat()}} self._record_writer.write_record(record) resp.body = json.dumps({ 'text': 'record successfuly written\near: {ear}\naudibility: {audibility}\ndecibels: {decibels}'.format(**data.text), 'response_type': 'ephemeral' }) resp.status = falcon.HTTP_OK CommandData = namedtuple('CommandData', ('text', 'command', 'response_url', 'token')) class SlashCommandDataSchema(marshmallow.Schema): command = marshmallow.fields.String(required=True) token = marshmallow.fields.String(required=True) text = marshmallow.fields.Method(deserialize='_parse_text', required=True) response_url = marshmallow.fields.Url(required=True) def __init__(self, command_token, *args, **kwargs): super().__init__(*args, **kwargs) self._token = command_token @marshmallow.validates('token') def _matches_token(self, value): if value != self._token: raise marshmallow.ValidationError('invalid token') def _parse_text(self, text): text = text.strip() if len(text) < 3 or len(text) > 5: raise marshmallow.ValidationError('text must be 4 to 6 characters') i = iter(text) ear = next(i).lower() audibility = next(i) decibels = ''.join(i) errors = [] if ear != 'l' and ear != 'r': errors.append('l or r are the only valid ear choices.') try: audibility = int(audibility) if audibility < 0 or audibility > 2: errors.append('audibility must be between 0 and 2.') except ValueError: errors.append('audibility must be an integer.') try: decibels = int(decibels) if decibels < 0 or decibels > 200: errors.append('decibels must be between 0 and 200.') except ValueError: errors.append('decibels must be an integer.') if errors: raise marshmallow.ValidationError(' '.join(errors)) return { 'ear': ear, 'audibility': audibility, 'decibels': decibels } @marshmallow.post_load def _post_load(self, data): return CommandData(**data) class TinnitusWriter: def __init__(self, record_file_path): self._path = expanduser(record_file_path) def write_record(self, record): with open(self._path, 'a') as f_out: f_out.write(json.dumps(record) + '\n')
apache-2.0
rizac/gfzreport
gfzreport/templates/network/__init__.py
2
8938
#!/usr/bin/env ptatioython # -*- coding: utf-8 -*- ''' Created on May 18, 2016 @author: riccardo ''' from __future__ import print_function import os import sys # @UnusedImport from gfzreport.templates.network.core.utils import relpath from gfzreport.templates.network.core import get_noise_pdfs_content, gen_title,\ get_net_desc, geofonstations_df, otherstations_df, get_map_df, get_figdirective_vars from gfzreport.sphinxbuild.core.extensions import mapfigure # from gfzreport.templates.utils import makedirs, copyfiles, validate_outdir,\ # cleanup_onerr, setupdir, get_rst_template from gfzreport.templates import utils from collections import OrderedDict def run(network, start_after, area_margins_in_deg, out_path, noise_pdf, inst_uptimes, move_data_files, update_config_only, confirm, network_station_marker, nonnetwork_station_marker, network_station_color, nonnetwork_station_color): templater = Templater(out_path, update_config_only, move_data_files, confirm) return templater(network, start_after, area_margins_in_deg, noise_pdf, inst_uptimes, network_station_marker, nonnetwork_station_marker, network_station_color, nonnetwork_station_color) class Templater(utils.Templater): def getdestpath(self, out_path, network, start_after, area_margins_in_deg, noise_pdf, inst_uptimes, network_station_marker, nonnetwork_station_marker, network_station_color, nonnetwork_station_color): '''This method must return the *real* destination directory of this object. In the most simple scenario, it can also just return `out_path` :param out_path: initial output path (passed in the `__init__` call) :param args, kwargs: the arguments passed to this object when called as function and forwarded to this method ''' return os.path.abspath(os.path.join(out_path, "%s_%s" % (str(network), str(start_after)))) def getdatafiles(self, destpath, destdatapath, network, start_after, area_margins_in_deg, noise_pdf, inst_uptimes, network_station_marker, nonnetwork_station_marker, network_station_color, nonnetwork_station_color): '''This method must return the data files to be copied into `destdatapath`. It must return a dict of `{destdir: files, ...}` where: * `destdir` is a string, usually `destdatapath` or a sub-directory of it, denoting the destination directory where to copy the files * `files`: a list of files to be copied in the corresponding `destdir`. It can be a list of strings denoting each a single file, a directory or a glob pattern. If string, it will be converted to the 1-element list `[files]` Use `collections.OrderedDict` to preserve the order of the keys For each item `destdir, files`, and for each `filepath` in `files`, the function will call: :ref:`gfzreport.templates.utils.copyfiles(filepath, destdir, self._mv_data_files)` Thus `filepath` can be a file (copy/move that file into `destdir`) a directory (copy/move each file into `destdir`) or a glob expression (copy/move each matching file into `destdir`) :param destpath: the destination directory, as returned from `self.getdestpath` :param destdatapath: the destination directory for the data files, currently the subdirectory 'data' of `destpath` (do not rely on it as it might change in the future) :param args, kwargs: the arguments passed to this object when called as function and forwarded to this method :return: a dict of destination paths (ususally sub-directories of `self.destdatapath` mapped to lists of strings (files/ directories/ glob patterns). An empty dict or None (or pass) are valid (don't copy anything into `destdatadir`) This function can safely raise as Exceptions will be caught and displayed in their message displayed printed ''' noise_pdf_destdir = os.path.join(destdatapath, "noise_pdf") inst_uptimes_destdir = os.path.join(destdatapath, "inst_uptimes") return OrderedDict([[inst_uptimes_destdir, inst_uptimes], [noise_pdf_destdir, noise_pdf]]) def getrstkwargs(self, destpath, destdatapath, datafiles, network, start_after, area_margins_in_deg, noise_pdf, inst_uptimes, network_station_marker, nonnetwork_station_marker, network_station_color, nonnetwork_station_color): '''This method accepts all arguments passed to this object when called as function and should return a dict of keyword arguments used to render the rst template, if the latter has been implemented as a jinja template. You can return an empty dict or None (or pass) if the rst in the current source folder is "fixed" and not variable according to the arguments. Note that at this point you can access `self.destpath`, `self.destdatapath` and `self.datafiles` :param destpath: the destination directory, as returned from `self.getdestpath` :param destdatapath: the destination directory for the data files, currently the subdirectory 'data' of `destpath` (do not rely on it as it might change in the future) :param datafiles: a dict as returned from self.getdatafiles`, where each key represents a data destination directory and each value is a list of files that have been copied or moved inthere. The keys of the dict are surely existing folders and are usually sub-directories of `destdatapath` (or equal to `destdatapath`) :param args, kwargs: the arguments passed to this object when called as function and forwarded to this method :return: a dict of key-> values to be used for rendering the rst if the latter is a jinja template. This function can safely raise as Exceptions will be caught and displayed in their message displayed printed ''' # get the destination data paths. Use getdatafiles implemented for # moving data files, and check that they are not empty # the two paths will also be used later inst_uptimes_dst, noise_pdf_dst = datafiles.keys() assert len(os.listdir(inst_uptimes_dst)), "'%s' empty" % inst_uptimes_dst assert len(os.listdir(noise_pdf_dst)), "'%s' empty" % noise_pdf_dst try: geofon_df = geofonstations_df(network, start_after) except Exception as exc: raise Exception(("error while fetching network stations ('%s')\n" "check arguments and internet connection") % str(exc)) try: others_df = otherstations_df(geofon_df, area_margins_in_deg) except Exception as exc: raise Exception(("error while fetching other stations within network " "stations boundaries ('%s')\n" "check arguments and internet connection") % str(exc)) map_df = get_map_df(geofon_df, others_df) # convert area margins into plotmap map_margins arg: mymapdefaults = dict(mapmargins=", ".join("%sdeg" % str(m) for m in area_margins_in_deg), sizes=50, fontsize=8, figmargins="1,2,9,0", legend_ncol=2) # building template, see template.rst: return dict( title=gen_title(network, geofon_df), network_description=get_net_desc(geofon_df), stations_table={'content': geofon_df.to_csv(sep=" ", quotechar='"', na_rep=" ", # this makes to_csv # quoting it (otherwise it might # result in row misalign) index=False), }, stations_map={'content': map_df.to_csv(sep=" ", quotechar='"', index=False), 'options': mapfigure.get_defargs(**mymapdefaults) }, noise_pdfs={'dirpath': relpath(noise_pdf_dst, destpath), 'content': get_noise_pdfs_content(noise_pdf_dst, geofon_df) }, inst_uptimes=get_figdirective_vars(inst_uptimes_dst, destpath) ) # if __name__ == '__main__': # main() # pylint:disable=no-value-for-parameter
gpl-3.0
Gravecorp/Gap
packages/IronPython.StdLib.2.7.3/content/Lib/encodings/cp869.py
593
33221
""" Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP869.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_map) 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_map)[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='cp869', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: None, # UNDEFINED 0x0081: None, # UNDEFINED 0x0082: None, # UNDEFINED 0x0083: None, # UNDEFINED 0x0084: None, # UNDEFINED 0x0085: None, # UNDEFINED 0x0086: 0x0386, # GREEK CAPITAL LETTER ALPHA WITH TONOS 0x0087: None, # UNDEFINED 0x0088: 0x00b7, # MIDDLE DOT 0x0089: 0x00ac, # NOT SIGN 0x008a: 0x00a6, # BROKEN BAR 0x008b: 0x2018, # LEFT SINGLE QUOTATION MARK 0x008c: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x008d: 0x0388, # GREEK CAPITAL LETTER EPSILON WITH TONOS 0x008e: 0x2015, # HORIZONTAL BAR 0x008f: 0x0389, # GREEK CAPITAL LETTER ETA WITH TONOS 0x0090: 0x038a, # GREEK CAPITAL LETTER IOTA WITH TONOS 0x0091: 0x03aa, # GREEK CAPITAL LETTER IOTA WITH DIALYTIKA 0x0092: 0x038c, # GREEK CAPITAL LETTER OMICRON WITH TONOS 0x0093: None, # UNDEFINED 0x0094: None, # UNDEFINED 0x0095: 0x038e, # GREEK CAPITAL LETTER UPSILON WITH TONOS 0x0096: 0x03ab, # GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA 0x0097: 0x00a9, # COPYRIGHT SIGN 0x0098: 0x038f, # GREEK CAPITAL LETTER OMEGA WITH TONOS 0x0099: 0x00b2, # SUPERSCRIPT TWO 0x009a: 0x00b3, # SUPERSCRIPT THREE 0x009b: 0x03ac, # GREEK SMALL LETTER ALPHA WITH TONOS 0x009c: 0x00a3, # POUND SIGN 0x009d: 0x03ad, # GREEK SMALL LETTER EPSILON WITH TONOS 0x009e: 0x03ae, # GREEK SMALL LETTER ETA WITH TONOS 0x009f: 0x03af, # GREEK SMALL LETTER IOTA WITH TONOS 0x00a0: 0x03ca, # GREEK SMALL LETTER IOTA WITH DIALYTIKA 0x00a1: 0x0390, # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS 0x00a2: 0x03cc, # GREEK SMALL LETTER OMICRON WITH TONOS 0x00a3: 0x03cd, # GREEK SMALL LETTER UPSILON WITH TONOS 0x00a4: 0x0391, # GREEK CAPITAL LETTER ALPHA 0x00a5: 0x0392, # GREEK CAPITAL LETTER BETA 0x00a6: 0x0393, # GREEK CAPITAL LETTER GAMMA 0x00a7: 0x0394, # GREEK CAPITAL LETTER DELTA 0x00a8: 0x0395, # GREEK CAPITAL LETTER EPSILON 0x00a9: 0x0396, # GREEK CAPITAL LETTER ZETA 0x00aa: 0x0397, # GREEK CAPITAL LETTER ETA 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF 0x00ac: 0x0398, # GREEK CAPITAL LETTER THETA 0x00ad: 0x0399, # GREEK CAPITAL LETTER IOTA 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x039a, # GREEK CAPITAL LETTER KAPPA 0x00b6: 0x039b, # GREEK CAPITAL LETTER LAMDA 0x00b7: 0x039c, # GREEK CAPITAL LETTER MU 0x00b8: 0x039d, # GREEK CAPITAL LETTER NU 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x039e, # GREEK CAPITAL LETTER XI 0x00be: 0x039f, # GREEK CAPITAL LETTER OMICRON 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x03a0, # GREEK CAPITAL LETTER PI 0x00c7: 0x03a1, # GREEK CAPITAL LETTER RHO 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x03a3, # GREEK CAPITAL LETTER SIGMA 0x00d0: 0x03a4, # GREEK CAPITAL LETTER TAU 0x00d1: 0x03a5, # GREEK CAPITAL LETTER UPSILON 0x00d2: 0x03a6, # GREEK CAPITAL LETTER PHI 0x00d3: 0x03a7, # GREEK CAPITAL LETTER CHI 0x00d4: 0x03a8, # GREEK CAPITAL LETTER PSI 0x00d5: 0x03a9, # GREEK CAPITAL LETTER OMEGA 0x00d6: 0x03b1, # GREEK SMALL LETTER ALPHA 0x00d7: 0x03b2, # GREEK SMALL LETTER BETA 0x00d8: 0x03b3, # GREEK SMALL LETTER GAMMA 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x03b4, # GREEK SMALL LETTER DELTA 0x00de: 0x03b5, # GREEK SMALL LETTER EPSILON 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x03b6, # GREEK SMALL LETTER ZETA 0x00e1: 0x03b7, # GREEK SMALL LETTER ETA 0x00e2: 0x03b8, # GREEK SMALL LETTER THETA 0x00e3: 0x03b9, # GREEK SMALL LETTER IOTA 0x00e4: 0x03ba, # GREEK SMALL LETTER KAPPA 0x00e5: 0x03bb, # GREEK SMALL LETTER LAMDA 0x00e6: 0x03bc, # GREEK SMALL LETTER MU 0x00e7: 0x03bd, # GREEK SMALL LETTER NU 0x00e8: 0x03be, # GREEK SMALL LETTER XI 0x00e9: 0x03bf, # GREEK SMALL LETTER OMICRON 0x00ea: 0x03c0, # GREEK SMALL LETTER PI 0x00eb: 0x03c1, # GREEK SMALL LETTER RHO 0x00ec: 0x03c3, # GREEK SMALL LETTER SIGMA 0x00ed: 0x03c2, # GREEK SMALL LETTER FINAL SIGMA 0x00ee: 0x03c4, # GREEK SMALL LETTER TAU 0x00ef: 0x0384, # GREEK TONOS 0x00f0: 0x00ad, # SOFT HYPHEN 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: 0x03c5, # GREEK SMALL LETTER UPSILON 0x00f3: 0x03c6, # GREEK SMALL LETTER PHI 0x00f4: 0x03c7, # GREEK SMALL LETTER CHI 0x00f5: 0x00a7, # SECTION SIGN 0x00f6: 0x03c8, # GREEK SMALL LETTER PSI 0x00f7: 0x0385, # GREEK DIALYTIKA TONOS 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x00a8, # DIAERESIS 0x00fa: 0x03c9, # GREEK SMALL LETTER OMEGA 0x00fb: 0x03cb, # GREEK SMALL LETTER UPSILON WITH DIALYTIKA 0x00fc: 0x03b0, # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS 0x00fd: 0x03ce, # GREEK SMALL LETTER OMEGA WITH TONOS 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Decoding Table decoding_table = ( u'\x00' # 0x0000 -> NULL u'\x01' # 0x0001 -> START OF HEADING u'\x02' # 0x0002 -> START OF TEXT u'\x03' # 0x0003 -> END OF TEXT u'\x04' # 0x0004 -> END OF TRANSMISSION u'\x05' # 0x0005 -> ENQUIRY u'\x06' # 0x0006 -> ACKNOWLEDGE u'\x07' # 0x0007 -> BELL u'\x08' # 0x0008 -> BACKSPACE u'\t' # 0x0009 -> HORIZONTAL TABULATION u'\n' # 0x000a -> LINE FEED u'\x0b' # 0x000b -> VERTICAL TABULATION u'\x0c' # 0x000c -> FORM FEED u'\r' # 0x000d -> CARRIAGE RETURN u'\x0e' # 0x000e -> SHIFT OUT u'\x0f' # 0x000f -> SHIFT IN u'\x10' # 0x0010 -> DATA LINK ESCAPE u'\x11' # 0x0011 -> DEVICE CONTROL ONE u'\x12' # 0x0012 -> DEVICE CONTROL TWO u'\x13' # 0x0013 -> DEVICE CONTROL THREE u'\x14' # 0x0014 -> DEVICE CONTROL FOUR u'\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE u'\x16' # 0x0016 -> SYNCHRONOUS IDLE u'\x17' # 0x0017 -> END OF TRANSMISSION BLOCK u'\x18' # 0x0018 -> CANCEL u'\x19' # 0x0019 -> END OF MEDIUM u'\x1a' # 0x001a -> SUBSTITUTE u'\x1b' # 0x001b -> ESCAPE u'\x1c' # 0x001c -> FILE SEPARATOR u'\x1d' # 0x001d -> GROUP SEPARATOR u'\x1e' # 0x001e -> RECORD SEPARATOR u'\x1f' # 0x001f -> UNIT SEPARATOR u' ' # 0x0020 -> SPACE u'!' # 0x0021 -> EXCLAMATION MARK u'"' # 0x0022 -> QUOTATION MARK u'#' # 0x0023 -> NUMBER SIGN u'$' # 0x0024 -> DOLLAR SIGN u'%' # 0x0025 -> PERCENT SIGN u'&' # 0x0026 -> AMPERSAND u"'" # 0x0027 -> APOSTROPHE u'(' # 0x0028 -> LEFT PARENTHESIS u')' # 0x0029 -> RIGHT PARENTHESIS u'*' # 0x002a -> ASTERISK u'+' # 0x002b -> PLUS SIGN u',' # 0x002c -> COMMA u'-' # 0x002d -> HYPHEN-MINUS u'.' # 0x002e -> FULL STOP u'/' # 0x002f -> SOLIDUS u'0' # 0x0030 -> DIGIT ZERO u'1' # 0x0031 -> DIGIT ONE u'2' # 0x0032 -> DIGIT TWO u'3' # 0x0033 -> DIGIT THREE u'4' # 0x0034 -> DIGIT FOUR u'5' # 0x0035 -> DIGIT FIVE u'6' # 0x0036 -> DIGIT SIX u'7' # 0x0037 -> DIGIT SEVEN u'8' # 0x0038 -> DIGIT EIGHT u'9' # 0x0039 -> DIGIT NINE u':' # 0x003a -> COLON u';' # 0x003b -> SEMICOLON u'<' # 0x003c -> LESS-THAN SIGN u'=' # 0x003d -> EQUALS SIGN u'>' # 0x003e -> GREATER-THAN SIGN u'?' # 0x003f -> QUESTION MARK u'@' # 0x0040 -> COMMERCIAL AT u'A' # 0x0041 -> LATIN CAPITAL LETTER A u'B' # 0x0042 -> LATIN CAPITAL LETTER B u'C' # 0x0043 -> LATIN CAPITAL LETTER C u'D' # 0x0044 -> LATIN CAPITAL LETTER D u'E' # 0x0045 -> LATIN CAPITAL LETTER E u'F' # 0x0046 -> LATIN CAPITAL LETTER F u'G' # 0x0047 -> LATIN CAPITAL LETTER G u'H' # 0x0048 -> LATIN CAPITAL LETTER H u'I' # 0x0049 -> LATIN CAPITAL LETTER I u'J' # 0x004a -> LATIN CAPITAL LETTER J u'K' # 0x004b -> LATIN CAPITAL LETTER K u'L' # 0x004c -> LATIN CAPITAL LETTER L u'M' # 0x004d -> LATIN CAPITAL LETTER M u'N' # 0x004e -> LATIN CAPITAL LETTER N u'O' # 0x004f -> LATIN CAPITAL LETTER O u'P' # 0x0050 -> LATIN CAPITAL LETTER P u'Q' # 0x0051 -> LATIN CAPITAL LETTER Q u'R' # 0x0052 -> LATIN CAPITAL LETTER R u'S' # 0x0053 -> LATIN CAPITAL LETTER S u'T' # 0x0054 -> LATIN CAPITAL LETTER T u'U' # 0x0055 -> LATIN CAPITAL LETTER U u'V' # 0x0056 -> LATIN CAPITAL LETTER V u'W' # 0x0057 -> LATIN CAPITAL LETTER W u'X' # 0x0058 -> LATIN CAPITAL LETTER X u'Y' # 0x0059 -> LATIN CAPITAL LETTER Y u'Z' # 0x005a -> LATIN CAPITAL LETTER Z u'[' # 0x005b -> LEFT SQUARE BRACKET u'\\' # 0x005c -> REVERSE SOLIDUS u']' # 0x005d -> RIGHT SQUARE BRACKET u'^' # 0x005e -> CIRCUMFLEX ACCENT u'_' # 0x005f -> LOW LINE u'`' # 0x0060 -> GRAVE ACCENT u'a' # 0x0061 -> LATIN SMALL LETTER A u'b' # 0x0062 -> LATIN SMALL LETTER B u'c' # 0x0063 -> LATIN SMALL LETTER C u'd' # 0x0064 -> LATIN SMALL LETTER D u'e' # 0x0065 -> LATIN SMALL LETTER E u'f' # 0x0066 -> LATIN SMALL LETTER F u'g' # 0x0067 -> LATIN SMALL LETTER G u'h' # 0x0068 -> LATIN SMALL LETTER H u'i' # 0x0069 -> LATIN SMALL LETTER I u'j' # 0x006a -> LATIN SMALL LETTER J u'k' # 0x006b -> LATIN SMALL LETTER K u'l' # 0x006c -> LATIN SMALL LETTER L u'm' # 0x006d -> LATIN SMALL LETTER M u'n' # 0x006e -> LATIN SMALL LETTER N u'o' # 0x006f -> LATIN SMALL LETTER O u'p' # 0x0070 -> LATIN SMALL LETTER P u'q' # 0x0071 -> LATIN SMALL LETTER Q u'r' # 0x0072 -> LATIN SMALL LETTER R u's' # 0x0073 -> LATIN SMALL LETTER S u't' # 0x0074 -> LATIN SMALL LETTER T u'u' # 0x0075 -> LATIN SMALL LETTER U u'v' # 0x0076 -> LATIN SMALL LETTER V u'w' # 0x0077 -> LATIN SMALL LETTER W u'x' # 0x0078 -> LATIN SMALL LETTER X u'y' # 0x0079 -> LATIN SMALL LETTER Y u'z' # 0x007a -> LATIN SMALL LETTER Z u'{' # 0x007b -> LEFT CURLY BRACKET u'|' # 0x007c -> VERTICAL LINE u'}' # 0x007d -> RIGHT CURLY BRACKET u'~' # 0x007e -> TILDE u'\x7f' # 0x007f -> DELETE u'\ufffe' # 0x0080 -> UNDEFINED u'\ufffe' # 0x0081 -> UNDEFINED u'\ufffe' # 0x0082 -> UNDEFINED u'\ufffe' # 0x0083 -> UNDEFINED u'\ufffe' # 0x0084 -> UNDEFINED u'\ufffe' # 0x0085 -> UNDEFINED u'\u0386' # 0x0086 -> GREEK CAPITAL LETTER ALPHA WITH TONOS u'\ufffe' # 0x0087 -> UNDEFINED u'\xb7' # 0x0088 -> MIDDLE DOT u'\xac' # 0x0089 -> NOT SIGN u'\xa6' # 0x008a -> BROKEN BAR u'\u2018' # 0x008b -> LEFT SINGLE QUOTATION MARK u'\u2019' # 0x008c -> RIGHT SINGLE QUOTATION MARK u'\u0388' # 0x008d -> GREEK CAPITAL LETTER EPSILON WITH TONOS u'\u2015' # 0x008e -> HORIZONTAL BAR u'\u0389' # 0x008f -> GREEK CAPITAL LETTER ETA WITH TONOS u'\u038a' # 0x0090 -> GREEK CAPITAL LETTER IOTA WITH TONOS u'\u03aa' # 0x0091 -> GREEK CAPITAL LETTER IOTA WITH DIALYTIKA u'\u038c' # 0x0092 -> GREEK CAPITAL LETTER OMICRON WITH TONOS u'\ufffe' # 0x0093 -> UNDEFINED u'\ufffe' # 0x0094 -> UNDEFINED u'\u038e' # 0x0095 -> GREEK CAPITAL LETTER UPSILON WITH TONOS u'\u03ab' # 0x0096 -> GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA u'\xa9' # 0x0097 -> COPYRIGHT SIGN u'\u038f' # 0x0098 -> GREEK CAPITAL LETTER OMEGA WITH TONOS u'\xb2' # 0x0099 -> SUPERSCRIPT TWO u'\xb3' # 0x009a -> SUPERSCRIPT THREE u'\u03ac' # 0x009b -> GREEK SMALL LETTER ALPHA WITH TONOS u'\xa3' # 0x009c -> POUND SIGN u'\u03ad' # 0x009d -> GREEK SMALL LETTER EPSILON WITH TONOS u'\u03ae' # 0x009e -> GREEK SMALL LETTER ETA WITH TONOS u'\u03af' # 0x009f -> GREEK SMALL LETTER IOTA WITH TONOS u'\u03ca' # 0x00a0 -> GREEK SMALL LETTER IOTA WITH DIALYTIKA u'\u0390' # 0x00a1 -> GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS u'\u03cc' # 0x00a2 -> GREEK SMALL LETTER OMICRON WITH TONOS u'\u03cd' # 0x00a3 -> GREEK SMALL LETTER UPSILON WITH TONOS u'\u0391' # 0x00a4 -> GREEK CAPITAL LETTER ALPHA u'\u0392' # 0x00a5 -> GREEK CAPITAL LETTER BETA u'\u0393' # 0x00a6 -> GREEK CAPITAL LETTER GAMMA u'\u0394' # 0x00a7 -> GREEK CAPITAL LETTER DELTA u'\u0395' # 0x00a8 -> GREEK CAPITAL LETTER EPSILON u'\u0396' # 0x00a9 -> GREEK CAPITAL LETTER ZETA u'\u0397' # 0x00aa -> GREEK CAPITAL LETTER ETA u'\xbd' # 0x00ab -> VULGAR FRACTION ONE HALF u'\u0398' # 0x00ac -> GREEK CAPITAL LETTER THETA u'\u0399' # 0x00ad -> GREEK CAPITAL LETTER IOTA u'\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK u'\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK u'\u2591' # 0x00b0 -> LIGHT SHADE u'\u2592' # 0x00b1 -> MEDIUM SHADE u'\u2593' # 0x00b2 -> DARK SHADE u'\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL u'\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT u'\u039a' # 0x00b5 -> GREEK CAPITAL LETTER KAPPA u'\u039b' # 0x00b6 -> GREEK CAPITAL LETTER LAMDA u'\u039c' # 0x00b7 -> GREEK CAPITAL LETTER MU u'\u039d' # 0x00b8 -> GREEK CAPITAL LETTER NU u'\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT u'\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL u'\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT u'\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT u'\u039e' # 0x00bd -> GREEK CAPITAL LETTER XI u'\u039f' # 0x00be -> GREEK CAPITAL LETTER OMICRON u'\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT u'\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT u'\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL u'\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL u'\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT u'\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL u'\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL u'\u03a0' # 0x00c6 -> GREEK CAPITAL LETTER PI u'\u03a1' # 0x00c7 -> GREEK CAPITAL LETTER RHO u'\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT u'\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT u'\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL u'\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL u'\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT u'\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL u'\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL u'\u03a3' # 0x00cf -> GREEK CAPITAL LETTER SIGMA u'\u03a4' # 0x00d0 -> GREEK CAPITAL LETTER TAU u'\u03a5' # 0x00d1 -> GREEK CAPITAL LETTER UPSILON u'\u03a6' # 0x00d2 -> GREEK CAPITAL LETTER PHI u'\u03a7' # 0x00d3 -> GREEK CAPITAL LETTER CHI u'\u03a8' # 0x00d4 -> GREEK CAPITAL LETTER PSI u'\u03a9' # 0x00d5 -> GREEK CAPITAL LETTER OMEGA u'\u03b1' # 0x00d6 -> GREEK SMALL LETTER ALPHA u'\u03b2' # 0x00d7 -> GREEK SMALL LETTER BETA u'\u03b3' # 0x00d8 -> GREEK SMALL LETTER GAMMA u'\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT u'\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT u'\u2588' # 0x00db -> FULL BLOCK u'\u2584' # 0x00dc -> LOWER HALF BLOCK u'\u03b4' # 0x00dd -> GREEK SMALL LETTER DELTA u'\u03b5' # 0x00de -> GREEK SMALL LETTER EPSILON u'\u2580' # 0x00df -> UPPER HALF BLOCK u'\u03b6' # 0x00e0 -> GREEK SMALL LETTER ZETA u'\u03b7' # 0x00e1 -> GREEK SMALL LETTER ETA u'\u03b8' # 0x00e2 -> GREEK SMALL LETTER THETA u'\u03b9' # 0x00e3 -> GREEK SMALL LETTER IOTA u'\u03ba' # 0x00e4 -> GREEK SMALL LETTER KAPPA u'\u03bb' # 0x00e5 -> GREEK SMALL LETTER LAMDA u'\u03bc' # 0x00e6 -> GREEK SMALL LETTER MU u'\u03bd' # 0x00e7 -> GREEK SMALL LETTER NU u'\u03be' # 0x00e8 -> GREEK SMALL LETTER XI u'\u03bf' # 0x00e9 -> GREEK SMALL LETTER OMICRON u'\u03c0' # 0x00ea -> GREEK SMALL LETTER PI u'\u03c1' # 0x00eb -> GREEK SMALL LETTER RHO u'\u03c3' # 0x00ec -> GREEK SMALL LETTER SIGMA u'\u03c2' # 0x00ed -> GREEK SMALL LETTER FINAL SIGMA u'\u03c4' # 0x00ee -> GREEK SMALL LETTER TAU u'\u0384' # 0x00ef -> GREEK TONOS u'\xad' # 0x00f0 -> SOFT HYPHEN u'\xb1' # 0x00f1 -> PLUS-MINUS SIGN u'\u03c5' # 0x00f2 -> GREEK SMALL LETTER UPSILON u'\u03c6' # 0x00f3 -> GREEK SMALL LETTER PHI u'\u03c7' # 0x00f4 -> GREEK SMALL LETTER CHI u'\xa7' # 0x00f5 -> SECTION SIGN u'\u03c8' # 0x00f6 -> GREEK SMALL LETTER PSI u'\u0385' # 0x00f7 -> GREEK DIALYTIKA TONOS u'\xb0' # 0x00f8 -> DEGREE SIGN u'\xa8' # 0x00f9 -> DIAERESIS u'\u03c9' # 0x00fa -> GREEK SMALL LETTER OMEGA u'\u03cb' # 0x00fb -> GREEK SMALL LETTER UPSILON WITH DIALYTIKA u'\u03b0' # 0x00fc -> GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS u'\u03ce' # 0x00fd -> GREEK SMALL LETTER OMEGA WITH TONOS u'\u25a0' # 0x00fe -> BLACK SQUARE u'\xa0' # 0x00ff -> NO-BREAK SPACE ) ### Encoding Map encoding_map = { 0x0000: 0x0000, # NULL 0x0001: 0x0001, # START OF HEADING 0x0002: 0x0002, # START OF TEXT 0x0003: 0x0003, # END OF TEXT 0x0004: 0x0004, # END OF TRANSMISSION 0x0005: 0x0005, # ENQUIRY 0x0006: 0x0006, # ACKNOWLEDGE 0x0007: 0x0007, # BELL 0x0008: 0x0008, # BACKSPACE 0x0009: 0x0009, # HORIZONTAL TABULATION 0x000a: 0x000a, # LINE FEED 0x000b: 0x000b, # VERTICAL TABULATION 0x000c: 0x000c, # FORM FEED 0x000d: 0x000d, # CARRIAGE RETURN 0x000e: 0x000e, # SHIFT OUT 0x000f: 0x000f, # SHIFT IN 0x0010: 0x0010, # DATA LINK ESCAPE 0x0011: 0x0011, # DEVICE CONTROL ONE 0x0012: 0x0012, # DEVICE CONTROL TWO 0x0013: 0x0013, # DEVICE CONTROL THREE 0x0014: 0x0014, # DEVICE CONTROL FOUR 0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE 0x0016: 0x0016, # SYNCHRONOUS IDLE 0x0017: 0x0017, # END OF TRANSMISSION BLOCK 0x0018: 0x0018, # CANCEL 0x0019: 0x0019, # END OF MEDIUM 0x001a: 0x001a, # SUBSTITUTE 0x001b: 0x001b, # ESCAPE 0x001c: 0x001c, # FILE SEPARATOR 0x001d: 0x001d, # GROUP SEPARATOR 0x001e: 0x001e, # RECORD SEPARATOR 0x001f: 0x001f, # UNIT SEPARATOR 0x0020: 0x0020, # SPACE 0x0021: 0x0021, # EXCLAMATION MARK 0x0022: 0x0022, # QUOTATION MARK 0x0023: 0x0023, # NUMBER SIGN 0x0024: 0x0024, # DOLLAR SIGN 0x0025: 0x0025, # PERCENT SIGN 0x0026: 0x0026, # AMPERSAND 0x0027: 0x0027, # APOSTROPHE 0x0028: 0x0028, # LEFT PARENTHESIS 0x0029: 0x0029, # RIGHT PARENTHESIS 0x002a: 0x002a, # ASTERISK 0x002b: 0x002b, # PLUS SIGN 0x002c: 0x002c, # COMMA 0x002d: 0x002d, # HYPHEN-MINUS 0x002e: 0x002e, # FULL STOP 0x002f: 0x002f, # SOLIDUS 0x0030: 0x0030, # DIGIT ZERO 0x0031: 0x0031, # DIGIT ONE 0x0032: 0x0032, # DIGIT TWO 0x0033: 0x0033, # DIGIT THREE 0x0034: 0x0034, # DIGIT FOUR 0x0035: 0x0035, # DIGIT FIVE 0x0036: 0x0036, # DIGIT SIX 0x0037: 0x0037, # DIGIT SEVEN 0x0038: 0x0038, # DIGIT EIGHT 0x0039: 0x0039, # DIGIT NINE 0x003a: 0x003a, # COLON 0x003b: 0x003b, # SEMICOLON 0x003c: 0x003c, # LESS-THAN SIGN 0x003d: 0x003d, # EQUALS SIGN 0x003e: 0x003e, # GREATER-THAN SIGN 0x003f: 0x003f, # QUESTION MARK 0x0040: 0x0040, # COMMERCIAL AT 0x0041: 0x0041, # LATIN CAPITAL LETTER A 0x0042: 0x0042, # LATIN CAPITAL LETTER B 0x0043: 0x0043, # LATIN CAPITAL LETTER C 0x0044: 0x0044, # LATIN CAPITAL LETTER D 0x0045: 0x0045, # LATIN CAPITAL LETTER E 0x0046: 0x0046, # LATIN CAPITAL LETTER F 0x0047: 0x0047, # LATIN CAPITAL LETTER G 0x0048: 0x0048, # LATIN CAPITAL LETTER H 0x0049: 0x0049, # LATIN CAPITAL LETTER I 0x004a: 0x004a, # LATIN CAPITAL LETTER J 0x004b: 0x004b, # LATIN CAPITAL LETTER K 0x004c: 0x004c, # LATIN CAPITAL LETTER L 0x004d: 0x004d, # LATIN CAPITAL LETTER M 0x004e: 0x004e, # LATIN CAPITAL LETTER N 0x004f: 0x004f, # LATIN CAPITAL LETTER O 0x0050: 0x0050, # LATIN CAPITAL LETTER P 0x0051: 0x0051, # LATIN CAPITAL LETTER Q 0x0052: 0x0052, # LATIN CAPITAL LETTER R 0x0053: 0x0053, # LATIN CAPITAL LETTER S 0x0054: 0x0054, # LATIN CAPITAL LETTER T 0x0055: 0x0055, # LATIN CAPITAL LETTER U 0x0056: 0x0056, # LATIN CAPITAL LETTER V 0x0057: 0x0057, # LATIN CAPITAL LETTER W 0x0058: 0x0058, # LATIN CAPITAL LETTER X 0x0059: 0x0059, # LATIN CAPITAL LETTER Y 0x005a: 0x005a, # LATIN CAPITAL LETTER Z 0x005b: 0x005b, # LEFT SQUARE BRACKET 0x005c: 0x005c, # REVERSE SOLIDUS 0x005d: 0x005d, # RIGHT SQUARE BRACKET 0x005e: 0x005e, # CIRCUMFLEX ACCENT 0x005f: 0x005f, # LOW LINE 0x0060: 0x0060, # GRAVE ACCENT 0x0061: 0x0061, # LATIN SMALL LETTER A 0x0062: 0x0062, # LATIN SMALL LETTER B 0x0063: 0x0063, # LATIN SMALL LETTER C 0x0064: 0x0064, # LATIN SMALL LETTER D 0x0065: 0x0065, # LATIN SMALL LETTER E 0x0066: 0x0066, # LATIN SMALL LETTER F 0x0067: 0x0067, # LATIN SMALL LETTER G 0x0068: 0x0068, # LATIN SMALL LETTER H 0x0069: 0x0069, # LATIN SMALL LETTER I 0x006a: 0x006a, # LATIN SMALL LETTER J 0x006b: 0x006b, # LATIN SMALL LETTER K 0x006c: 0x006c, # LATIN SMALL LETTER L 0x006d: 0x006d, # LATIN SMALL LETTER M 0x006e: 0x006e, # LATIN SMALL LETTER N 0x006f: 0x006f, # LATIN SMALL LETTER O 0x0070: 0x0070, # LATIN SMALL LETTER P 0x0071: 0x0071, # LATIN SMALL LETTER Q 0x0072: 0x0072, # LATIN SMALL LETTER R 0x0073: 0x0073, # LATIN SMALL LETTER S 0x0074: 0x0074, # LATIN SMALL LETTER T 0x0075: 0x0075, # LATIN SMALL LETTER U 0x0076: 0x0076, # LATIN SMALL LETTER V 0x0077: 0x0077, # LATIN SMALL LETTER W 0x0078: 0x0078, # LATIN SMALL LETTER X 0x0079: 0x0079, # LATIN SMALL LETTER Y 0x007a: 0x007a, # LATIN SMALL LETTER Z 0x007b: 0x007b, # LEFT CURLY BRACKET 0x007c: 0x007c, # VERTICAL LINE 0x007d: 0x007d, # RIGHT CURLY BRACKET 0x007e: 0x007e, # TILDE 0x007f: 0x007f, # DELETE 0x00a0: 0x00ff, # NO-BREAK SPACE 0x00a3: 0x009c, # POUND SIGN 0x00a6: 0x008a, # BROKEN BAR 0x00a7: 0x00f5, # SECTION SIGN 0x00a8: 0x00f9, # DIAERESIS 0x00a9: 0x0097, # COPYRIGHT SIGN 0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00ac: 0x0089, # NOT SIGN 0x00ad: 0x00f0, # SOFT HYPHEN 0x00b0: 0x00f8, # DEGREE SIGN 0x00b1: 0x00f1, # PLUS-MINUS SIGN 0x00b2: 0x0099, # SUPERSCRIPT TWO 0x00b3: 0x009a, # SUPERSCRIPT THREE 0x00b7: 0x0088, # MIDDLE DOT 0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00bd: 0x00ab, # VULGAR FRACTION ONE HALF 0x0384: 0x00ef, # GREEK TONOS 0x0385: 0x00f7, # GREEK DIALYTIKA TONOS 0x0386: 0x0086, # GREEK CAPITAL LETTER ALPHA WITH TONOS 0x0388: 0x008d, # GREEK CAPITAL LETTER EPSILON WITH TONOS 0x0389: 0x008f, # GREEK CAPITAL LETTER ETA WITH TONOS 0x038a: 0x0090, # GREEK CAPITAL LETTER IOTA WITH TONOS 0x038c: 0x0092, # GREEK CAPITAL LETTER OMICRON WITH TONOS 0x038e: 0x0095, # GREEK CAPITAL LETTER UPSILON WITH TONOS 0x038f: 0x0098, # GREEK CAPITAL LETTER OMEGA WITH TONOS 0x0390: 0x00a1, # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS 0x0391: 0x00a4, # GREEK CAPITAL LETTER ALPHA 0x0392: 0x00a5, # GREEK CAPITAL LETTER BETA 0x0393: 0x00a6, # GREEK CAPITAL LETTER GAMMA 0x0394: 0x00a7, # GREEK CAPITAL LETTER DELTA 0x0395: 0x00a8, # GREEK CAPITAL LETTER EPSILON 0x0396: 0x00a9, # GREEK CAPITAL LETTER ZETA 0x0397: 0x00aa, # GREEK CAPITAL LETTER ETA 0x0398: 0x00ac, # GREEK CAPITAL LETTER THETA 0x0399: 0x00ad, # GREEK CAPITAL LETTER IOTA 0x039a: 0x00b5, # GREEK CAPITAL LETTER KAPPA 0x039b: 0x00b6, # GREEK CAPITAL LETTER LAMDA 0x039c: 0x00b7, # GREEK CAPITAL LETTER MU 0x039d: 0x00b8, # GREEK CAPITAL LETTER NU 0x039e: 0x00bd, # GREEK CAPITAL LETTER XI 0x039f: 0x00be, # GREEK CAPITAL LETTER OMICRON 0x03a0: 0x00c6, # GREEK CAPITAL LETTER PI 0x03a1: 0x00c7, # GREEK CAPITAL LETTER RHO 0x03a3: 0x00cf, # GREEK CAPITAL LETTER SIGMA 0x03a4: 0x00d0, # GREEK CAPITAL LETTER TAU 0x03a5: 0x00d1, # GREEK CAPITAL LETTER UPSILON 0x03a6: 0x00d2, # GREEK CAPITAL LETTER PHI 0x03a7: 0x00d3, # GREEK CAPITAL LETTER CHI 0x03a8: 0x00d4, # GREEK CAPITAL LETTER PSI 0x03a9: 0x00d5, # GREEK CAPITAL LETTER OMEGA 0x03aa: 0x0091, # GREEK CAPITAL LETTER IOTA WITH DIALYTIKA 0x03ab: 0x0096, # GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA 0x03ac: 0x009b, # GREEK SMALL LETTER ALPHA WITH TONOS 0x03ad: 0x009d, # GREEK SMALL LETTER EPSILON WITH TONOS 0x03ae: 0x009e, # GREEK SMALL LETTER ETA WITH TONOS 0x03af: 0x009f, # GREEK SMALL LETTER IOTA WITH TONOS 0x03b0: 0x00fc, # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS 0x03b1: 0x00d6, # GREEK SMALL LETTER ALPHA 0x03b2: 0x00d7, # GREEK SMALL LETTER BETA 0x03b3: 0x00d8, # GREEK SMALL LETTER GAMMA 0x03b4: 0x00dd, # GREEK SMALL LETTER DELTA 0x03b5: 0x00de, # GREEK SMALL LETTER EPSILON 0x03b6: 0x00e0, # GREEK SMALL LETTER ZETA 0x03b7: 0x00e1, # GREEK SMALL LETTER ETA 0x03b8: 0x00e2, # GREEK SMALL LETTER THETA 0x03b9: 0x00e3, # GREEK SMALL LETTER IOTA 0x03ba: 0x00e4, # GREEK SMALL LETTER KAPPA 0x03bb: 0x00e5, # GREEK SMALL LETTER LAMDA 0x03bc: 0x00e6, # GREEK SMALL LETTER MU 0x03bd: 0x00e7, # GREEK SMALL LETTER NU 0x03be: 0x00e8, # GREEK SMALL LETTER XI 0x03bf: 0x00e9, # GREEK SMALL LETTER OMICRON 0x03c0: 0x00ea, # GREEK SMALL LETTER PI 0x03c1: 0x00eb, # GREEK SMALL LETTER RHO 0x03c2: 0x00ed, # GREEK SMALL LETTER FINAL SIGMA 0x03c3: 0x00ec, # GREEK SMALL LETTER SIGMA 0x03c4: 0x00ee, # GREEK SMALL LETTER TAU 0x03c5: 0x00f2, # GREEK SMALL LETTER UPSILON 0x03c6: 0x00f3, # GREEK SMALL LETTER PHI 0x03c7: 0x00f4, # GREEK SMALL LETTER CHI 0x03c8: 0x00f6, # GREEK SMALL LETTER PSI 0x03c9: 0x00fa, # GREEK SMALL LETTER OMEGA 0x03ca: 0x00a0, # GREEK SMALL LETTER IOTA WITH DIALYTIKA 0x03cb: 0x00fb, # GREEK SMALL LETTER UPSILON WITH DIALYTIKA 0x03cc: 0x00a2, # GREEK SMALL LETTER OMICRON WITH TONOS 0x03cd: 0x00a3, # GREEK SMALL LETTER UPSILON WITH TONOS 0x03ce: 0x00fd, # GREEK SMALL LETTER OMEGA WITH TONOS 0x2015: 0x008e, # HORIZONTAL BAR 0x2018: 0x008b, # LEFT SINGLE QUOTATION MARK 0x2019: 0x008c, # RIGHT SINGLE QUOTATION MARK 0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL 0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL 0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT 0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT 0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL 0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL 0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT 0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x2580: 0x00df, # UPPER HALF BLOCK 0x2584: 0x00dc, # LOWER HALF BLOCK 0x2588: 0x00db, # FULL BLOCK 0x2591: 0x00b0, # LIGHT SHADE 0x2592: 0x00b1, # MEDIUM SHADE 0x2593: 0x00b2, # DARK SHADE 0x25a0: 0x00fe, # BLACK SQUARE }
mpl-2.0
xinwu/horizon
openstack_dashboard/contrib/sahara/content/data_processing/jobs/tabs.py
25
1331
# 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 logging from django.utils.translation import ugettext_lazy as _ from horizon import tabs from openstack_dashboard.contrib.sahara.api import sahara as saharaclient LOG = logging.getLogger(__name__) class GeneralTab(tabs.Tab): name = _("General Info") slug = "job_details_tab" template_name = ("project/data_processing.jobs/_details.html") def get_context_data(self, request): job_id = self.tab_group.kwargs['job_id'] try: job = saharaclient.job_get(request, job_id) except Exception as e: job = {} LOG.error("Unable to fetch job template details: %s" % str(e)) return {"job": job} class JobDetailsTabs(tabs.TabGroup): slug = "job_details" tabs = (GeneralTab,) sticky = True
apache-2.0
DarthMaulware/EquationGroupLeaks
Leak #5 - Lost In Translation/windows/Resources/Ops/PyScripts/lib/util/menu.py
1
6238
import math import os SPACER = None QUIT_OPTION = 'Done' INVALID_CHOICE = (-1) def clear_screen(): os.system(('cls' if (os.name == 'nt') else 'clear')) class Menu(object, ): def __init__(self, heading, choices, choice_heading, prompt): self.heading = heading self.choices = choices self.choice_heading = choice_heading self.prompt = prompt def __str__(self): if self.heading: print ('%s\n' % self.heading) if self.choice_heading: settings = [self.choice_heading] has_heading = True else: settings = [] has_heading = False settings += self._get_table_data() settings.append([SPACER]) settings.append([QUIT_OPTION]) final_string = self._draw_table(settings, has_heading) return final_string def show(self, default=None): print self choice = raw_input((('%s [%s] ' % (self.prompt, default)) if (default is not None) else self.prompt)) try: choice = int(choice) except ValueError: if (choice == ''): choice = default else: choice = None if ((not choice) or (choice > (len(self.choices) + 1)) or (choice < 1)): return (choice, INVALID_CHOICE) if (choice == (len(self.choices) + 1)): return (choice, QUIT_OPTION) result = self._handle_choice(choice) return result def _get_table_data(self): return self.choices def _handle_choice(self, choice): try: row_data = self.choices[(choice - 1)] return (choice, row_data) except KeyError: return (choice, INVALID_CHOICE) except IndexError: return (choice, INVALID_CHOICE) def _draw_table(self, table, has_heading): max_column_lengths = self._find_max_column_size(table) final_string = '' len_zeroes_rounded_up = math.ceil(math.log10(len(table))) max_padding = int((len_zeroes_rounded_up + len('1) '))) row_counter = (0 if has_heading else 1) for row in table: if (row[0] == SPACER): row_string = '' row_counter -= 1 elif ((row_counter == 0) and has_heading): row_string = (' ' * max_padding) row_string += (self._draw_row(row, max_column_lengths).rstrip() + '\n') row_string += self._draw_heading_dashes(max_column_lengths, max_padding) else: padding = ((max_padding - len(str(row_counter))) - len(') ')) row_string = (((' ' * padding) + str(row_counter)) + ') ') row_string += self._draw_row(row, max_column_lengths) final_string += ('%s\n' % row_string.rstrip()) row_counter += 1 return final_string def _find_max_column_size(self, table): max_row_length = max([len(row) for row in table if row]) max_column_lengths = ([0] * max_row_length) for row in table: if (row[0] == SPACER): break for row_item_index in range(len(row)): row_item = str(row[row_item_index]) if (len(row_item) > max_column_lengths[row_item_index]): max_column_lengths[row_item_index] = len(row_item) return max_column_lengths def _draw_heading_dashes(self, max_column_lengths, padding): dash_string = (' ' * padding) for column_index in range(len(max_column_lengths)): dash_string += ('-' * max_column_lengths[column_index]) dash_string += ' ' return dash_string def _draw_row(self, row, max_column_lengths): column_counter = 0 row_string = '' for row_item in row: if hasattr(row_item, '__iter__'): row_string += row_item[0] else: row_string += row_item space_between = (' ' * ((max_column_lengths[column_counter] + 2) - len(row_item))) row_string += space_between column_counter += 1 return row_string class ListMenu(Menu, ): def __init__(self, heading, choices, choice_heading, prompt): Menu.__init__(self, heading, choices, choice_heading, prompt) if self.choice_heading: self.choice_heading = [choice_heading] def _get_table_data(self): settings = [[choice] for choice in self.choices] return settings def _find_max_column_size(self, table): max_length = 0 for row in table: if (row[0] == SPACER): break row_item = row[0] if hasattr(row_item, '__iter__'): row_item = row_item[0] if (len(row_item) > max_length): max_length = len(row_item) return [max_length] class FunctionMenu(ListMenu, ): def _handle_choice(self, choice): value = self.choices[(choice - 1)] if (len(value) == 2): function = value[1] function_result = function() else: function = value[1] function_result = function(*value[2:]) return (choice, function_result) class SettingsMenu(Menu, ): def __init__(self, heading, choices, prompt): Menu.__init__(self, heading, choices, ['Name', 'Current Value'], prompt) self.choices = self._map_choice_list(choices) def show(self): (choice, result) = Menu.show(self) while (result != QUIT_OPTION): (choice, result) = Menu.show(self) return dict(self.choices) def _map_choice_list(self, choices): if hasattr(choices, 'items'): choice_list = [[k, v] for (k, v) in choices.items()] else: choice_list = [[k, v] for (k, v) in choices] return choice_list def _handle_choice(self, choice): name = self.choices[(choice - 1)][0] new_value = raw_input(("Enter a new value for '%s' > " % name)) self.choices[(choice - 1)][1] = new_value self.choices = self._map_choice_list(self.choices) return (self.choices, None)
unlicense
xme1226/sahara
sahara/db/api.py
4
10563
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """Defines interface for DB access. Functions in this module are imported into the sahara.db namespace. Call these functions from sahara.db namespace, not the sahara.db.api namespace. All functions in this module return objects that implement a dictionary-like interface. **Related Flags** :db_backend: string to lookup in the list of LazyPluggable backends. `sqlalchemy` is the only supported backend right now. :sql_connection: string specifying the sqlalchemy connection to use, like: `mysql://user:password@localhost/sahara`. """ from oslo.config import cfg from oslo.db import api as db_api from oslo.db import options from sahara.openstack.common import log as logging CONF = cfg.CONF options.set_defaults(CONF) _BACKEND_MAPPING = { 'sqlalchemy': 'sahara.db.sqlalchemy.api', } IMPL = db_api.DBAPI.from_config(CONF, backend_mapping=_BACKEND_MAPPING) LOG = logging.getLogger(__name__) def setup_db(): """Set up database, create tables, etc. Return True on success, False otherwise """ return IMPL.setup_db() def drop_db(): """Drop database. Return True on success, False otherwise """ return IMPL.drop_db() # Helpers for building constraints / equality checks def constraint(**conditions): """Return a constraint object suitable for use with some updates.""" return IMPL.constraint(**conditions) def equal_any(*values): """Return an equality condition object suitable for use in a constraint. Equal_any conditions require that a model object's attribute equal any one of the given values. """ return IMPL.equal_any(*values) def not_equal(*values): """Return an inequality condition object suitable for use in a constraint. Not_equal conditions require that a model object's attribute differs from all of the given values. """ return IMPL.not_equal(*values) def to_dict(func): def decorator(*args, **kwargs): res = func(*args, **kwargs) if isinstance(res, list): return [item.to_dict() for item in res] if res: return res.to_dict() else: return None return decorator # Cluster ops @to_dict def cluster_get(context, cluster): """Return the cluster or None if it does not exist.""" return IMPL.cluster_get(context, cluster) @to_dict def cluster_get_all(context, **kwargs): """Get all clusters filtered by **kwargs. e.g. cluster_get_all(plugin_name='vanilla', hadoop_version='1.1') """ return IMPL.cluster_get_all(context, **kwargs) @to_dict def cluster_create(context, values): """Create a cluster from the values dictionary.""" return IMPL.cluster_create(context, values) @to_dict def cluster_update(context, cluster, values): """Set the given properties on cluster and update it.""" return IMPL.cluster_update(context, cluster, values) def cluster_destroy(context, cluster): """Destroy the cluster or raise if it does not exist.""" IMPL.cluster_destroy(context, cluster) # Node Group ops def node_group_add(context, cluster, values): """Create a Node Group from the values dictionary.""" return IMPL.node_group_add(context, cluster, values) def node_group_update(context, node_group, values): """Set the given properties on node_group and update it.""" IMPL.node_group_update(context, node_group, values) def node_group_remove(context, node_group): """Destroy the node_group or raise if it does not exist.""" IMPL.node_group_remove(context, node_group) # Instance ops def instance_add(context, node_group, values): """Create an Instance from the values dictionary.""" return IMPL.instance_add(context, node_group, values) def instance_update(context, instance, values): """Set the given properties on Instance and update it.""" IMPL.instance_update(context, instance, values) def instance_remove(context, instance): """Destroy the Instance or raise if it does not exist.""" IMPL.instance_remove(context, instance) # Volumes ops def append_volume(context, instance, volume_id): """Append volume_id to instance.""" IMPL.append_volume(context, instance, volume_id) def remove_volume(context, instance, volume_id): """Remove volume_id in instance.""" IMPL.remove_volume(context, instance, volume_id) # Cluster Template ops @to_dict def cluster_template_get(context, cluster_template): """Return the cluster_template or None if it does not exist.""" return IMPL.cluster_template_get(context, cluster_template) @to_dict def cluster_template_get_all(context): """Get all cluster_templates.""" return IMPL.cluster_template_get_all(context) @to_dict def cluster_template_create(context, values): """Create a cluster_template from the values dictionary.""" return IMPL.cluster_template_create(context, values) def cluster_template_destroy(context, cluster_template): """Destroy the cluster_template or raise if it does not exist.""" IMPL.cluster_template_destroy(context, cluster_template) # Node Group Template ops @to_dict def node_group_template_get(context, node_group_template): """Return the Node Group Template or None if it does not exist.""" return IMPL.node_group_template_get(context, node_group_template) @to_dict def node_group_template_get_all(context): """Get all Node Group Templates.""" return IMPL.node_group_template_get_all(context) @to_dict def node_group_template_create(context, values): """Create a Node Group Template from the values dictionary.""" return IMPL.node_group_template_create(context, values) def node_group_template_destroy(context, node_group_template): """Destroy the Node Group Template or raise if it does not exist.""" IMPL.node_group_template_destroy(context, node_group_template) # Data Source ops @to_dict def data_source_get(context, data_source): """Return the Data Source or None if it does not exist.""" return IMPL.data_source_get(context, data_source) @to_dict def data_source_get_all(context): """Get all Data Sources.""" return IMPL.data_source_get_all(context) @to_dict def data_source_create(context, values): """Create a Data Source from the values dictionary.""" return IMPL.data_source_create(context, values) def data_source_destroy(context, data_source): """Destroy the Data Source or raise if it does not exist.""" IMPL.data_source_destroy(context, data_source) # JobExecutions ops @to_dict def job_execution_get(context, job_execution): """Return the JobExecution or None if it does not exist.""" return IMPL.job_execution_get(context, job_execution) @to_dict def job_execution_get_all(context, **kwargs): """Get all JobExecutions filtered by **kwargs. e.g. job_execution_get_all(cluster_id=12, input_id=123) """ return IMPL.job_execution_get_all(context, **kwargs) def job_execution_count(context, **kwargs): """Count number of JobExecutions filtered by **kwargs. e.g. job_execution_count(cluster_id=12, input_id=123) """ return IMPL.job_execution_count(context, **kwargs) @to_dict def job_execution_create(context, values): """Create a JobExecution from the values dictionary.""" return IMPL.job_execution_create(context, values) @to_dict def job_execution_update(context, job_execution, values): """Create a JobExecution from the values dictionary.""" return IMPL.job_execution_update(context, job_execution, values) def job_execution_destroy(context, job_execution): """Destroy the JobExecution or raise if it does not exist.""" IMPL.job_execution_destroy(context, job_execution) # Job ops @to_dict def job_get(context, job): """Return the Job or None if it does not exist.""" return IMPL.job_get(context, job) @to_dict def job_get_all(context): """Get all Jobs.""" return IMPL.job_get_all(context) @to_dict def job_create(context, values): """Create a Job from the values dictionary.""" return IMPL.job_create(context, values) def job_update(context, job, values): """Update a Job from the values dictionary.""" return IMPL.job_update(context, job, values) def job_destroy(context, job): """Destroy the Job or raise if it does not exist.""" IMPL.job_destroy(context, job) @to_dict def job_binary_get_all(context): """Get all JobBinarys.""" return IMPL.job_binary_get_all(context) @to_dict def job_binary_get(context, job_binary): """Return the JobBinary or None if it does not exist.""" return IMPL.job_binary_get(context, job_binary) @to_dict def job_binary_create(context, values): """Create a JobBinary from the values dictionary.""" return IMPL.job_binary_create(context, values) def job_binary_destroy(context, job_binary): """Destroy the JobBinary or raise if it does not exist.""" IMPL.job_binary_destroy(context, job_binary) @to_dict def job_binary_internal_get_all(context): """Get all JobBinaryInternals.""" return IMPL.job_binary_internal_get_all(context) @to_dict def job_binary_internal_get(context, job_binary_internal): """Return the JobBinaryInternal or None if it does not exist.""" return IMPL.job_binary_internal_get(context, job_binary_internal) @to_dict def job_binary_internal_create(context, values): """Create a JobBinaryInternal from the values dictionary.""" return IMPL.job_binary_internal_create(context, values) def job_binary_internal_destroy(context, job_binary_internal): """Destroy the JobBinaryInternal or raise if it does not exist.""" IMPL.job_binary_internal_destroy(context, job_binary_internal) def job_binary_internal_get_raw_data(context, job_binary_internal_id): """Return the binary data field from the specified JobBinaryInternal.""" return IMPL.job_binary_internal_get_raw_data(context, job_binary_internal_id)
apache-2.0
suyashphadtare/vestasi-erp-final
erpnext/support/doctype/newsletter/newsletter.py
31
4539
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe import frappe.utils from frappe.utils import cstr from frappe import throw, _ from frappe.model.document import Document import erpnext.tasks class Newsletter(Document): def onload(self): if self.email_sent: self.get("__onload").status_count = dict(frappe.db.sql("""select status, count(name) from `tabBulk Email` where ref_doctype=%s and ref_docname=%s group by status""", (self.doctype, self.name))) or None def test_send(self, doctype="Lead"): self.recipients = self.test_email_id.split(",") self.send_to_doctype = "Lead" self.send_bulk() frappe.msgprint(_("Scheduled to send to {0}").format(self.test_email_id)) def send_emails(self): """send emails to leads and customers""" if self.email_sent: throw(_("Newsletter has already been sent")) self.recipients = self.get_recipients() if getattr(frappe.local, "is_ajax", False): # to avoid request timed out! self.validate_send() # hack! event="bulk_long" to queue in longjob queue erpnext.tasks.send_newsletter.delay(frappe.local.site, self.name, event="bulk_long") else: self.send_bulk() frappe.msgprint(_("Scheduled to send to {0} recipients").format(len(self.recipients))) frappe.db.set(self, "email_sent", 1) def get_recipients(self): self.email_field = None if self.send_to_type=="Contact": self.send_to_doctype = "Contact" if self.contact_type == "Customer": return frappe.db.sql_list("""select email_id from tabContact where ifnull(email_id, '') != '' and ifnull(customer, '') != ''""") elif self.contact_type == "Supplier": return frappe.db.sql_list("""select email_id from tabContact where ifnull(email_id, '') != '' and ifnull(supplier, '') != ''""") elif self.send_to_type=="Lead": self.send_to_doctype = "Lead" conditions = [] if self.lead_source and self.lead_source != "All": conditions.append(" and source='%s'" % self.lead_source.replace("'", "\'")) if self.lead_status and self.lead_status != "All": conditions.append(" and status='%s'" % self.lead_status.replace("'", "\'")) if conditions: conditions = "".join(conditions) return frappe.db.sql_list("""select email_id from tabLead where ifnull(email_id, '') != '' %s""" % (conditions or "")) elif self.send_to_type=="Employee": self.send_to_doctype = "Employee" self.email_field = "company_email" return frappe.db.sql_list("""select if(ifnull(company_email, '')!='', company_email, personal_email) as email_id from `tabEmployee` where status='Active'""") elif self.email_list: email_list = [cstr(email).strip() for email in self.email_list.split(",")] for email in email_list: create_lead(email) self.send_to_doctype = "Lead" return email_list def send_bulk(self): if not self.get("recipients"): # in case it is called via worker self.recipients = self.get_recipients() self.validate_send() sender = self.send_from or frappe.utils.get_formatted_email(self.owner) from frappe.utils.email_lib.bulk import send if not frappe.flags.in_test: frappe.db.auto_commit_on_many_writes = True send(recipients = self.recipients, sender = sender, subject = self.subject, message = self.message, doctype = self.send_to_doctype, email_field = self.get("email_field") or "email_id", ref_doctype = self.doctype, ref_docname = self.name) if not frappe.flags.in_test: frappe.db.auto_commit_on_many_writes = False def validate_send(self): if self.get("__islocal"): throw(_("Please save the Newsletter before sending")) @frappe.whitelist() def get_lead_options(): return { "sources": ["All"] + filter(None, frappe.db.sql_list("""select distinct source from tabLead""")), "statuses": ["All"] + filter(None, frappe.db.sql_list("""select distinct status from tabLead""")) } def create_lead(email_id): """create a lead if it does not exist""" from email.utils import parseaddr from frappe.model.naming import get_default_naming_series real_name, email_id = parseaddr(email_id) if frappe.db.get_value("Lead", {"email_id": email_id}): return lead = frappe.get_doc({ "doctype": "Lead", "email_id": email_id, "lead_name": real_name or email_id, "status": "Lead", "naming_series": get_default_naming_series("Lead"), "company": frappe.db.get_default("company"), "source": "Email" }) lead.insert()
agpl-3.0
theplaymate/ferra
scripts/tracing/draw_functrace.py
170
3543
#!/usr/bin/python """ Copyright 2008 (c) Frederic Weisbecker <fweisbec@gmail.com> Licensed under the terms of the GNU GPL License version 2 This script parses a trace provided by the function tracer in kernel/trace/trace_functions.c The resulted trace is processed into a tree to produce a more human view of the call stack by drawing textual but hierarchical tree of calls. Only the functions's names and the the call time are provided. Usage: Be sure that you have CONFIG_FUNCTION_TRACER # mkdir /debugfs # mount -t debug debug /debug # echo function > /debug/tracing/current_tracer $ cat /debug/tracing/trace_pipe > ~/raw_trace_func Wait some times but not too much, the script is a bit slow. Break the pipe (Ctrl + Z) $ scripts/draw_functrace.py < raw_trace_func > draw_functrace Then you have your drawn trace in draw_functrace """ import sys, re class CallTree: """ This class provides a tree representation of the functions call stack. If a function has no parent in the kernel (interrupt, syscall, kernel thread...) then it is attached to a virtual parent called ROOT. """ ROOT = None def __init__(self, func, time = None, parent = None): self._func = func self._time = time if parent is None: self._parent = CallTree.ROOT else: self._parent = parent self._children = [] def calls(self, func, calltime): """ If a function calls another one, call this method to insert it into the tree at the appropriate place. @return: A reference to the newly created child node. """ child = CallTree(func, calltime, self) self._children.append(child) return child def getParent(self, func): """ Retrieve the last parent of the current node that has the name given by func. If this function is not on a parent, then create it as new child of root @return: A reference to the parent. """ tree = self while tree != CallTree.ROOT and tree._func != func: tree = tree._parent if tree == CallTree.ROOT: child = CallTree.ROOT.calls(func, None) return child return tree def __repr__(self): return self.__toString("", True) def __toString(self, branch, lastChild): if self._time is not None: s = "%s----%s (%s)\n" % (branch, self._func, self._time) else: s = "%s----%s\n" % (branch, self._func) i = 0 if lastChild: branch = branch[:-1] + " " while i < len(self._children): if i != len(self._children) - 1: s += "%s" % self._children[i].__toString(branch +\ " |", False) else: s += "%s" % self._children[i].__toString(branch +\ " |", True) i += 1 return s class BrokenLineException(Exception): """If the last line is not complete because of the pipe breakage, we want to stop the processing and ignore this line. """ pass class CommentLineException(Exception): """ If the line is a comment (as in the beginning of the trace file), just ignore it. """ pass def parseLine(line): line = line.strip() if line.startswith("#"): raise CommentLineException m = re.match("[^]]+?\\] +([0-9.]+): (\\w+) <-(\\w+)", line) if m is None: raise BrokenLineException return (m.group(1), m.group(2), m.group(3)) def main(): CallTree.ROOT = CallTree("Root (Nowhere)", None, None) tree = CallTree.ROOT for line in sys.stdin: try: calltime, callee, caller = parseLine(line) except BrokenLineException: break except CommentLineException: continue tree = tree.getParent(caller) tree = tree.calls(callee, calltime) print CallTree.ROOT if __name__ == "__main__": main()
gpl-2.0
erasche/jbrowse
tests/selenium_tests/volvox_biodb_121_test.py
3
1208
import os import unittest import re from volvox_biodb_test import AbstractVolvoxBiodbTest class VolvoxBiodbTest121 ( AbstractVolvoxBiodbTest, unittest.TestCase ): data_dir = 'tests/data/volvox_formatted_1_2_1/' def setUp( self ): # skip calling VolvoxBiodbTest's setUp, cause we are not # actually running any formatting super( AbstractVolvoxBiodbTest, self ).setUp() def test_volvox( self ): # select "ctgA from the dropdown self.select_refseq( 'ctgA' ) # check a good browser title assert "ctgA" in self.browser.title, "browser title is actually %s" % self.browser.title # do a test where we search for a certain gene using the search box self.search_f15() self.assert_no_js_errors() # test scrolling, make sure we get no js errors self.scroll() # test dragging in and displaying the wiggle track self.wiggle() # test sequence track display self.sequence() def baseURL( self ): if not self.base_url: self.base_url = re.sub('[^/]+$','compat_121.html',super( AbstractVolvoxBiodbTest, self ).baseURL() ) return self.base_url
lgpl-2.1
quinot/ansible
lib/ansible/modules/remote_management/oneview/oneview_enclosure_facts.py
84
6416
#!/usr/bin/python # Copyright: (c) 2016-2017, Hewlett Packard Enterprise Development LP # 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: oneview_enclosure_facts short_description: Retrieve facts about one or more Enclosures description: - Retrieve facts about one or more of the Enclosures from OneView. version_added: "2.5" requirements: - hpOneView >= 2.0.1 author: - Felipe Bulsoni (@fgbulsoni) - Thiago Miotto (@tmiotto) - Adriane Cardozo (@adriane-cardozo) options: name: description: - Enclosure name. options: description: - "List with options to gather additional facts about an Enclosure and related resources. Options allowed: C(script), C(environmentalConfiguration), and C(utilization). For the option C(utilization), you can provide specific parameters." extends_documentation_fragment: - oneview - oneview.factsparams ''' EXAMPLES = ''' - name: Gather facts about all Enclosures oneview_enclosure_facts: hostname: 172.16.101.48 username: administrator password: my_password api_version: 500 no_log: true delegate_to: localhost - debug: var=enclosures - name: Gather paginated, filtered and sorted facts about Enclosures oneview_enclosure_facts: params: start: 0 count: 3 sort: name:descending filter: status=OK hostname: 172.16.101.48 username: administrator password: my_password api_version: 500 no_log: true delegate_to: localhost - debug: var=enclosures - name: Gather facts about an Enclosure by name oneview_enclosure_facts: name: Enclosure-Name hostname: 172.16.101.48 username: administrator password: my_password api_version: 500 no_log: true delegate_to: localhost - debug: var=enclosures - name: Gather facts about an Enclosure by name with options oneview_enclosure_facts: name: Test-Enclosure options: - script # optional - environmentalConfiguration # optional - utilization # optional hostname: 172.16.101.48 username: administrator password: my_password api_version: 500 no_log: true delegate_to: localhost - debug: var=enclosures - debug: var=enclosure_script - debug: var=enclosure_environmental_configuration - debug: var=enclosure_utilization - name: "Gather facts about an Enclosure with temperature data at a resolution of one sample per day, between two specified dates" oneview_enclosure_facts: name: Test-Enclosure options: - utilization: # optional fields: AmbientTemperature filter: - startDate=2016-07-01T14:29:42.000Z - endDate=2017-07-01T03:29:42.000Z view: day refresh: false hostname: 172.16.101.48 username: administrator password: my_password api_version: 500 no_log: true delegate_to: localhost - debug: var=enclosures - debug: var=enclosure_utilization ''' RETURN = ''' enclosures: description: Has all the OneView facts about the Enclosures. returned: Always, but can be null. type: dict enclosure_script: description: Has all the OneView facts about the script of an Enclosure. returned: When requested, but can be null. type: string enclosure_environmental_configuration: description: Has all the OneView facts about the environmental configuration of an Enclosure. returned: When requested, but can be null. type: dict enclosure_utilization: description: Has all the OneView facts about the utilization of an Enclosure. returned: When requested, but can be null. type: dict ''' from ansible.module_utils.oneview import OneViewModuleBase class EnclosureFactsModule(OneViewModuleBase): argument_spec = dict(name=dict(type='str'), options=dict(type='list'), params=dict(type='dict')) def __init__(self): super(EnclosureFactsModule, self).__init__(additional_arg_spec=self.argument_spec) def execute_module(self): ansible_facts = {} if self.module.params['name']: enclosures = self._get_by_name(self.module.params['name']) if self.options and enclosures: ansible_facts = self._gather_optional_facts(self.options, enclosures[0]) else: enclosures = self.oneview_client.enclosures.get_all(**self.facts_params) ansible_facts['enclosures'] = enclosures return dict(changed=False, ansible_facts=ansible_facts) def _gather_optional_facts(self, options, enclosure): enclosure_client = self.oneview_client.enclosures ansible_facts = {} if options.get('script'): ansible_facts['enclosure_script'] = enclosure_client.get_script(enclosure['uri']) if options.get('environmentalConfiguration'): env_config = enclosure_client.get_environmental_configuration(enclosure['uri']) ansible_facts['enclosure_environmental_configuration'] = env_config if options.get('utilization'): ansible_facts['enclosure_utilization'] = self._get_utilization(enclosure, options['utilization']) return ansible_facts def _get_utilization(self, enclosure, params): fields = view = refresh = filter = '' if isinstance(params, dict): fields = params.get('fields') view = params.get('view') refresh = params.get('refresh') filter = params.get('filter') return self.oneview_client.enclosures.get_utilization(enclosure['uri'], fields=fields, filter=filter, refresh=refresh, view=view) def _get_by_name(self, name): return self.oneview_client.enclosures.get_by('name', name) def main(): EnclosureFactsModule().run() if __name__ == '__main__': main()
gpl-3.0
ryfeus/lambda-packs
Tensorflow_OpenCV_Nightly/source/tensorflow/contrib/keras/api/keras/datasets/__init__.py
133
1271
# 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. # ============================================================================== """Keras built-in datasets.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.keras.api.keras.datasets import boston_housing from tensorflow.contrib.keras.api.keras.datasets import cifar10 from tensorflow.contrib.keras.api.keras.datasets import cifar100 from tensorflow.contrib.keras.api.keras.datasets import imdb from tensorflow.contrib.keras.api.keras.datasets import mnist from tensorflow.contrib.keras.api.keras.datasets import reuters del absolute_import del division del print_function
mit
runetvilum/skolevej
ogr2osm/langleyroad.py
2
5104
''' A translation function for Township of Langley Roads_shp.shp roads data. The shapefiles are availble under the PDDL as "Roads" from the Township of Langley at http://www.tol.ca/ServicesContact/OpenData/OpenDataCatalogue.aspx The following fields are dropped from the source shapefile: Field Definition Reason ALTROADNAM Alternate name? Always blank ALTSTNMID Alternate name ID? Always blank FROMLEFTPR From left property number Belongs on different ways FROMLEFTTH From left theoretical Not mappable FROMRIGHTP From right property number Belongs on different ways FROMRIGHTH From right theoretical Not mappable OBJECTID Internal feature number Automatically generated OWNER Owner of road Does not add to classification beyond ROADTYPE PROJECTNUM Project number Always blank ROADCLASS Road class # Text version of ROADTYPE SHAPE_LEN Length of feature Automatically generated STNAMEID Unique ID for street name. Not mappable TOLEFTPROP To left property number Belongs on different ways TOLEFTTHEO To left theoretical Not mappable TORIGHTPRO To left property number Belongs on different ways TORIGHTTHE To left theoretical Not mappable YEARADDED Year added to GIS database Not mappable The following fields are used: Field Used for Reason ROADNAME name=ROADNAME Name of the road ROADTYPE highway=* Type of the road STREETID tol:streetid Unique ID for the road segment Internal mappings: OWNER=Provincial <==> ROADTYPE=Highway Ramp|Ministry of Transportation OWNER=Regional ==> ROADTYPE=Major Road Network OSM Mappings Source value OSM value Shortcomings ROADTYPE=Arterial highway=secondary ROADTYPE=Collector highway=tertiary ROADTYPE=Local highway=residential May need to be changed to highway=unclassified for some roads ROADTYPE=Lane highway=service Source data does not indicate if service=alley ROADTYPE=Gravel highway=residential surface=gravel ROADTYPE=Ministry of Transportation highway=primary|motorway Huristics used to differentiate between highways. Double-check these ROADTYPE=Major Road Network highway=secondary Does not identify Highway 1A as primary ROADTYPE=Highway Ramp highway=motorway_link ''' def translateName(rawname): ''' A general purpose name expander. ''' suffixlookup = { 'Ave':'Avenue', 'Rd':'Road', 'St':'Street', 'Pl':'Place', 'Cres':'Crescent', 'Blvd':'Boulevard', 'Dr':'Drive', 'Lane':'Lane', 'Crt':'Court', 'Gr':'Grove', 'Cl':'Close', 'Rwy':'Railway', 'Div':'Diversion', 'Hwy':'Highway', 'Hwy':'Highway', 'Conn': 'Connector', 'E':'East', 'S':'South', 'N':'North', 'W':'West'} newName = '' for partName in rawname.split(): newName = newName + ' ' + suffixlookup.get(partName,partName) return newName.strip() def filterTags(attrs): if not attrs: return tags = {} if 'ROADNAME' in attrs: translated = translateName(attrs['ROADNAME'].title()) if translated != '(Lane)' and translated != '(Ramp)': tags['name'] = translated if 'STREETID' in attrs: tags['tol:streetid'] = attrs['STREETID'].strip() if 'ROADTYPE' in attrs: if attrs['ROADTYPE'].strip() == 'Major Road Network': tags['highway'] = 'secondary' elif attrs['ROADTYPE'].strip() == 'Arterial': tags['highway'] = 'secondary' elif attrs['ROADTYPE'].strip() == 'Collector': tags['highway'] = 'tertiary' elif attrs['ROADTYPE'].strip() == 'Local': tags['highway'] = 'residential' elif attrs['ROADTYPE'].strip() == 'Lane': tags['highway'] = 'service' elif attrs['ROADTYPE'].strip() == 'Gravel': tags['highway'] = 'residential' tags['surface'] = 'gravel' elif attrs['ROADTYPE'].strip() == 'Ministry of Transportation': if translated and (translated == '#1 Highway' or translated == 'Golden Ears Bridge'): tags['highway'] = 'motorway' else: tags['highway'] = 'primary' elif attrs['ROADTYPE'].strip() == 'Highway Ramp': tags['highway'] = 'motorway_link' else: tags['highway'] = 'road' tags['tol:roadtype'] = attrs['ROADTYPE'].strip() tags['source'] = 'Township of Langley GIS Data' return tags
gpl-3.0
jicruz/heroku-bot
lib/pip/utils/__init__.py
323
27187
from __future__ import absolute_import from collections import deque import contextlib import errno import io import locale # we have a submodule named 'logging' which would shadow this if we used the # regular name: import logging as std_logging import re import os import posixpath import shutil import stat import subprocess import sys import tarfile import zipfile from pip.exceptions import InstallationError from pip.compat import console_to_str, expanduser, stdlib_pkgs from pip.locations import ( site_packages, user_site, running_under_virtualenv, virtualenv_no_global, write_delete_marker_file, ) from pip._vendor import pkg_resources from pip._vendor.six.moves import input from pip._vendor.six import PY2 from pip._vendor.retrying import retry if PY2: from io import BytesIO as StringIO else: from io import StringIO __all__ = ['rmtree', 'display_path', 'backup_dir', 'ask', 'splitext', 'format_size', 'is_installable_dir', 'is_svn_page', 'file_contents', 'split_leading_dir', 'has_leading_dir', 'normalize_path', 'renames', 'get_terminal_size', 'get_prog', 'unzip_file', 'untar_file', 'unpack_file', 'call_subprocess', 'captured_stdout', 'ensure_dir', 'ARCHIVE_EXTENSIONS', 'SUPPORTED_EXTENSIONS', 'get_installed_version'] logger = std_logging.getLogger(__name__) BZ2_EXTENSIONS = ('.tar.bz2', '.tbz') XZ_EXTENSIONS = ('.tar.xz', '.txz', '.tlz', '.tar.lz', '.tar.lzma') ZIP_EXTENSIONS = ('.zip', '.whl') TAR_EXTENSIONS = ('.tar.gz', '.tgz', '.tar') ARCHIVE_EXTENSIONS = ( ZIP_EXTENSIONS + BZ2_EXTENSIONS + TAR_EXTENSIONS + XZ_EXTENSIONS) SUPPORTED_EXTENSIONS = ZIP_EXTENSIONS + TAR_EXTENSIONS try: import bz2 # noqa SUPPORTED_EXTENSIONS += BZ2_EXTENSIONS except ImportError: logger.debug('bz2 module is not available') try: # Only for Python 3.3+ import lzma # noqa SUPPORTED_EXTENSIONS += XZ_EXTENSIONS except ImportError: logger.debug('lzma module is not available') def import_or_raise(pkg_or_module_string, ExceptionType, *args, **kwargs): try: return __import__(pkg_or_module_string) except ImportError: raise ExceptionType(*args, **kwargs) def ensure_dir(path): """os.path.makedirs without EEXIST.""" try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: raise def get_prog(): try: if os.path.basename(sys.argv[0]) in ('__main__.py', '-c'): return "%s -m pip" % sys.executable except (AttributeError, TypeError, IndexError): pass return 'pip' # Retry every half second for up to 3 seconds @retry(stop_max_delay=3000, wait_fixed=500) def rmtree(dir, ignore_errors=False): shutil.rmtree(dir, ignore_errors=ignore_errors, onerror=rmtree_errorhandler) def rmtree_errorhandler(func, path, exc_info): """On Windows, the files in .svn are read-only, so when rmtree() tries to remove them, an exception is thrown. We catch that here, remove the read-only attribute, and hopefully continue without problems.""" # if file type currently read only if os.stat(path).st_mode & stat.S_IREAD: # convert to read/write os.chmod(path, stat.S_IWRITE) # use the original function to repeat the operation func(path) return else: raise def display_path(path): """Gives the display value for a given path, making it relative to cwd if possible.""" path = os.path.normcase(os.path.abspath(path)) if sys.version_info[0] == 2: path = path.decode(sys.getfilesystemencoding(), 'replace') path = path.encode(sys.getdefaultencoding(), 'replace') if path.startswith(os.getcwd() + os.path.sep): path = '.' + path[len(os.getcwd()):] return path def backup_dir(dir, ext='.bak'): """Figure out the name of a directory to back up the given dir to (adding .bak, .bak2, etc)""" n = 1 extension = ext while os.path.exists(dir + extension): n += 1 extension = ext + str(n) return dir + extension def ask_path_exists(message, options): for action in os.environ.get('PIP_EXISTS_ACTION', '').split(): if action in options: return action return ask(message, options) def ask(message, options): """Ask the message interactively, with the given possible responses""" while 1: if os.environ.get('PIP_NO_INPUT'): raise Exception( 'No input was expected ($PIP_NO_INPUT set); question: %s' % message ) response = input(message) response = response.strip().lower() if response not in options: print( 'Your response (%r) was not one of the expected responses: ' '%s' % (response, ', '.join(options)) ) else: return response def format_size(bytes): if bytes > 1000 * 1000: return '%.1fMB' % (bytes / 1000.0 / 1000) elif bytes > 10 * 1000: return '%ikB' % (bytes / 1000) elif bytes > 1000: return '%.1fkB' % (bytes / 1000.0) else: return '%ibytes' % bytes def is_installable_dir(path): """Return True if `path` is a directory containing a setup.py file.""" if not os.path.isdir(path): return False setup_py = os.path.join(path, 'setup.py') if os.path.isfile(setup_py): return True return False def is_svn_page(html): """ Returns true if the page appears to be the index page of an svn repository """ return (re.search(r'<title>[^<]*Revision \d+:', html) and re.search(r'Powered by (?:<a[^>]*?>)?Subversion', html, re.I)) def file_contents(filename): with open(filename, 'rb') as fp: return fp.read().decode('utf-8') def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE): """Yield pieces of data from a file-like object until EOF.""" while True: chunk = file.read(size) if not chunk: break yield chunk def split_leading_dir(path): path = path.lstrip('/').lstrip('\\') if '/' in path and (('\\' in path and path.find('/') < path.find('\\')) or '\\' not in path): return path.split('/', 1) elif '\\' in path: return path.split('\\', 1) else: return path, '' def has_leading_dir(paths): """Returns true if all the paths have the same leading path name (i.e., everything is in one subdirectory in an archive)""" common_prefix = None for path in paths: prefix, rest = split_leading_dir(path) if not prefix: return False elif common_prefix is None: common_prefix = prefix elif prefix != common_prefix: return False return True def normalize_path(path, resolve_symlinks=True): """ Convert a path to its canonical, case-normalized, absolute version. """ path = expanduser(path) if resolve_symlinks: path = os.path.realpath(path) else: path = os.path.abspath(path) return os.path.normcase(path) def splitext(path): """Like os.path.splitext, but take off .tar too""" base, ext = posixpath.splitext(path) if base.lower().endswith('.tar'): ext = base[-4:] + ext base = base[:-4] return base, ext def renames(old, new): """Like os.renames(), but handles renaming across devices.""" # Implementation borrowed from os.renames(). head, tail = os.path.split(new) if head and tail and not os.path.exists(head): os.makedirs(head) shutil.move(old, new) head, tail = os.path.split(old) if head and tail: try: os.removedirs(head) except OSError: pass def is_local(path): """ Return True if path is within sys.prefix, if we're running in a virtualenv. If we're not in a virtualenv, all paths are considered "local." """ if not running_under_virtualenv(): return True return normalize_path(path).startswith(normalize_path(sys.prefix)) def dist_is_local(dist): """ Return True if given Distribution object is installed locally (i.e. within current virtualenv). Always True if we're not in a virtualenv. """ return is_local(dist_location(dist)) def dist_in_usersite(dist): """ Return True if given Distribution is installed in user site. """ norm_path = normalize_path(dist_location(dist)) return norm_path.startswith(normalize_path(user_site)) def dist_in_site_packages(dist): """ Return True if given Distribution is installed in distutils.sysconfig.get_python_lib(). """ return normalize_path( dist_location(dist) ).startswith(normalize_path(site_packages)) def dist_is_editable(dist): """Is distribution an editable install?""" for path_item in sys.path: egg_link = os.path.join(path_item, dist.project_name + '.egg-link') if os.path.isfile(egg_link): return True return False def get_installed_distributions(local_only=True, skip=stdlib_pkgs, include_editables=True, editables_only=False, user_only=False): """ Return a list of installed Distribution objects. If ``local_only`` is True (default), only return installations local to the current virtualenv, if in a virtualenv. ``skip`` argument is an iterable of lower-case project names to ignore; defaults to stdlib_pkgs If ``editables`` is False, don't report editables. If ``editables_only`` is True , only report editables. If ``user_only`` is True , only report installations in the user site directory. """ if local_only: local_test = dist_is_local else: def local_test(d): return True if include_editables: def editable_test(d): return True else: def editable_test(d): return not dist_is_editable(d) if editables_only: def editables_only_test(d): return dist_is_editable(d) else: def editables_only_test(d): return True if user_only: user_test = dist_in_usersite else: def user_test(d): return True return [d for d in pkg_resources.working_set if local_test(d) and d.key not in skip and editable_test(d) and editables_only_test(d) and user_test(d) ] def egg_link_path(dist): """ Return the path for the .egg-link file if it exists, otherwise, None. There's 3 scenarios: 1) not in a virtualenv try to find in site.USER_SITE, then site_packages 2) in a no-global virtualenv try to find in site_packages 3) in a yes-global virtualenv try to find in site_packages, then site.USER_SITE (don't look in global location) For #1 and #3, there could be odd cases, where there's an egg-link in 2 locations. This method will just return the first one found. """ sites = [] if running_under_virtualenv(): if virtualenv_no_global(): sites.append(site_packages) else: sites.append(site_packages) if user_site: sites.append(user_site) else: if user_site: sites.append(user_site) sites.append(site_packages) for site in sites: egglink = os.path.join(site, dist.project_name) + '.egg-link' if os.path.isfile(egglink): return egglink def dist_location(dist): """ Get the site-packages location of this distribution. Generally this is dist.location, except in the case of develop-installed packages, where dist.location is the source code location, and we want to know where the egg-link file is. """ egg_link = egg_link_path(dist) if egg_link: return egg_link return dist.location def get_terminal_size(): """Returns a tuple (x, y) representing the width(x) and the height(x) in characters of the terminal window.""" def ioctl_GWINSZ(fd): try: import fcntl import termios import struct cr = struct.unpack( 'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234') ) except: return None if cr == (0, 0): return None return cr cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) if not cr: try: fd = os.open(os.ctermid(), os.O_RDONLY) cr = ioctl_GWINSZ(fd) os.close(fd) except: pass if not cr: cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80)) return int(cr[1]), int(cr[0]) def current_umask(): """Get the current umask which involves having to set it temporarily.""" mask = os.umask(0) os.umask(mask) return mask def unzip_file(filename, location, flatten=True): """ Unzip the file (with path `filename`) to the destination `location`. All files are written based on system defaults and umask (i.e. permissions are not preserved), except that regular file members with any execute permissions (user, group, or world) have "chmod +x" applied after being written. Note that for windows, any execute changes using os.chmod are no-ops per the python docs. """ ensure_dir(location) zipfp = open(filename, 'rb') try: zip = zipfile.ZipFile(zipfp, allowZip64=True) leading = has_leading_dir(zip.namelist()) and flatten for info in zip.infolist(): name = info.filename data = zip.read(name) fn = name if leading: fn = split_leading_dir(name)[1] fn = os.path.join(location, fn) dir = os.path.dirname(fn) if fn.endswith('/') or fn.endswith('\\'): # A directory ensure_dir(fn) else: ensure_dir(dir) fp = open(fn, 'wb') try: fp.write(data) finally: fp.close() mode = info.external_attr >> 16 # if mode and regular file and any execute permissions for # user/group/world? if mode and stat.S_ISREG(mode) and mode & 0o111: # make dest file have execute for user/group/world # (chmod +x) no-op on windows per python docs os.chmod(fn, (0o777 - current_umask() | 0o111)) finally: zipfp.close() def untar_file(filename, location): """ Untar the file (with path `filename`) to the destination `location`. All files are written based on system defaults and umask (i.e. permissions are not preserved), except that regular file members with any execute permissions (user, group, or world) have "chmod +x" applied after being written. Note that for windows, any execute changes using os.chmod are no-ops per the python docs. """ ensure_dir(location) if filename.lower().endswith('.gz') or filename.lower().endswith('.tgz'): mode = 'r:gz' elif filename.lower().endswith(BZ2_EXTENSIONS): mode = 'r:bz2' elif filename.lower().endswith(XZ_EXTENSIONS): mode = 'r:xz' elif filename.lower().endswith('.tar'): mode = 'r' else: logger.warning( 'Cannot determine compression type for file %s', filename, ) mode = 'r:*' tar = tarfile.open(filename, mode) try: # note: python<=2.5 doesn't seem to know about pax headers, filter them leading = has_leading_dir([ member.name for member in tar.getmembers() if member.name != 'pax_global_header' ]) for member in tar.getmembers(): fn = member.name if fn == 'pax_global_header': continue if leading: fn = split_leading_dir(fn)[1] path = os.path.join(location, fn) if member.isdir(): ensure_dir(path) elif member.issym(): try: tar._extract_member(member, path) except Exception as exc: # Some corrupt tar files seem to produce this # (specifically bad symlinks) logger.warning( 'In the tar file %s the member %s is invalid: %s', filename, member.name, exc, ) continue else: try: fp = tar.extractfile(member) except (KeyError, AttributeError) as exc: # Some corrupt tar files seem to produce this # (specifically bad symlinks) logger.warning( 'In the tar file %s the member %s is invalid: %s', filename, member.name, exc, ) continue ensure_dir(os.path.dirname(path)) with open(path, 'wb') as destfp: shutil.copyfileobj(fp, destfp) fp.close() # Update the timestamp (useful for cython compiled files) tar.utime(member, path) # member have any execute permissions for user/group/world? if member.mode & 0o111: # make dest file have execute for user/group/world # no-op on windows per python docs os.chmod(path, (0o777 - current_umask() | 0o111)) finally: tar.close() def unpack_file(filename, location, content_type, link): filename = os.path.realpath(filename) if (content_type == 'application/zip' or filename.lower().endswith(ZIP_EXTENSIONS) or zipfile.is_zipfile(filename)): unzip_file( filename, location, flatten=not filename.endswith('.whl') ) elif (content_type == 'application/x-gzip' or tarfile.is_tarfile(filename) or filename.lower().endswith( TAR_EXTENSIONS + BZ2_EXTENSIONS + XZ_EXTENSIONS)): untar_file(filename, location) elif (content_type and content_type.startswith('text/html') and is_svn_page(file_contents(filename))): # We don't really care about this from pip.vcs.subversion import Subversion Subversion('svn+' + link.url).unpack(location) else: # FIXME: handle? # FIXME: magic signatures? logger.critical( 'Cannot unpack file %s (downloaded from %s, content-type: %s); ' 'cannot detect archive format', filename, location, content_type, ) raise InstallationError( 'Cannot determine archive format of %s' % location ) def call_subprocess(cmd, show_stdout=True, cwd=None, on_returncode='raise', command_desc=None, extra_environ=None, spinner=None): # This function's handling of subprocess output is confusing and I # previously broke it terribly, so as penance I will write a long comment # explaining things. # # The obvious thing that affects output is the show_stdout= # kwarg. show_stdout=True means, let the subprocess write directly to our # stdout. Even though it is nominally the default, it is almost never used # inside pip (and should not be used in new code without a very good # reason); as of 2016-02-22 it is only used in a few places inside the VCS # wrapper code. Ideally we should get rid of it entirely, because it # creates a lot of complexity here for a rarely used feature. # # Most places in pip set show_stdout=False. What this means is: # - We connect the child stdout to a pipe, which we read. # - By default, we hide the output but show a spinner -- unless the # subprocess exits with an error, in which case we show the output. # - If the --verbose option was passed (= loglevel is DEBUG), then we show # the output unconditionally. (But in this case we don't want to show # the output a second time if it turns out that there was an error.) # # stderr is always merged with stdout (even if show_stdout=True). if show_stdout: stdout = None else: stdout = subprocess.PIPE if command_desc is None: cmd_parts = [] for part in cmd: if ' ' in part or '\n' in part or '"' in part or "'" in part: part = '"%s"' % part.replace('"', '\\"') cmd_parts.append(part) command_desc = ' '.join(cmd_parts) logger.debug("Running command %s", command_desc) env = os.environ.copy() if extra_environ: env.update(extra_environ) try: proc = subprocess.Popen( cmd, stderr=subprocess.STDOUT, stdin=None, stdout=stdout, cwd=cwd, env=env) except Exception as exc: logger.critical( "Error %s while executing command %s", exc, command_desc, ) raise if stdout is not None: all_output = [] while True: line = console_to_str(proc.stdout.readline()) if not line: break line = line.rstrip() all_output.append(line + '\n') if logger.getEffectiveLevel() <= std_logging.DEBUG: # Show the line immediately logger.debug(line) else: # Update the spinner if spinner is not None: spinner.spin() proc.wait() if spinner is not None: if proc.returncode: spinner.finish("error") else: spinner.finish("done") if proc.returncode: if on_returncode == 'raise': if (logger.getEffectiveLevel() > std_logging.DEBUG and not show_stdout): logger.info( 'Complete output from command %s:', command_desc, ) logger.info( ''.join(all_output) + '\n----------------------------------------' ) raise InstallationError( 'Command "%s" failed with error code %s in %s' % (command_desc, proc.returncode, cwd)) elif on_returncode == 'warn': logger.warning( 'Command "%s" had error code %s in %s', command_desc, proc.returncode, cwd, ) elif on_returncode == 'ignore': pass else: raise ValueError('Invalid value: on_returncode=%s' % repr(on_returncode)) if not show_stdout: return ''.join(all_output) def read_text_file(filename): """Return the contents of *filename*. Try to decode the file contents with utf-8, the preferred system encoding (e.g., cp1252 on some Windows machines), and latin1, in that order. Decoding a byte string with latin1 will never raise an error. In the worst case, the returned string will contain some garbage characters. """ with open(filename, 'rb') as fp: data = fp.read() encodings = ['utf-8', locale.getpreferredencoding(False), 'latin1'] for enc in encodings: try: data = data.decode(enc) except UnicodeDecodeError: continue break assert type(data) != bytes # Latin1 should have worked. return data def _make_build_dir(build_dir): os.makedirs(build_dir) write_delete_marker_file(build_dir) class FakeFile(object): """Wrap a list of lines in an object with readline() to make ConfigParser happy.""" def __init__(self, lines): self._gen = (l for l in lines) def readline(self): try: try: return next(self._gen) except NameError: return self._gen.next() except StopIteration: return '' def __iter__(self): return self._gen class StreamWrapper(StringIO): @classmethod def from_stream(cls, orig_stream): cls.orig_stream = orig_stream return cls() # compileall.compile_dir() needs stdout.encoding to print to stdout @property def encoding(self): return self.orig_stream.encoding @contextlib.contextmanager def captured_output(stream_name): """Return a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO. Taken from Lib/support/__init__.py in the CPython repo. """ orig_stdout = getattr(sys, stream_name) setattr(sys, stream_name, StreamWrapper.from_stream(orig_stdout)) try: yield getattr(sys, stream_name) finally: setattr(sys, stream_name, orig_stdout) def captured_stdout(): """Capture the output of sys.stdout: with captured_stdout() as stdout: print('hello') self.assertEqual(stdout.getvalue(), 'hello\n') Taken from Lib/support/__init__.py in the CPython repo. """ return captured_output('stdout') class cached_property(object): """A property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the attribute resets the property. Source: https://github.com/bottlepy/bottle/blob/0.11.5/bottle.py#L175 """ def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: # We're being accessed from the class itself, not from an object return self value = obj.__dict__[self.func.__name__] = self.func(obj) return value def get_installed_version(dist_name, lookup_dirs=None): """Get the installed version of dist_name avoiding pkg_resources cache""" # Create a requirement that we'll look for inside of setuptools. req = pkg_resources.Requirement.parse(dist_name) # We want to avoid having this cached, so we need to construct a new # working set each time. if lookup_dirs is None: working_set = pkg_resources.WorkingSet() else: working_set = pkg_resources.WorkingSet(lookup_dirs) # Get the installed distribution from our working set dist = working_set.find(req) # Check to see if we got an installed distribution or not, if we did # we want to return it's version. return dist.version if dist else None def consume(iterator): """Consume an iterable at C speed.""" deque(iterator, maxlen=0)
gpl-3.0
dvliman/jaikuengine
.google_appengine/lib/django-1.5/django/contrib/admin/validation.py
100
20755
from django.core.exceptions import ImproperlyConfigured from django.db import models from django.db.models.fields import FieldDoesNotExist from django.forms.models import (BaseModelForm, BaseModelFormSet, fields_for_model, _get_foreign_key) from django.contrib.admin import ListFilter, FieldListFilter from django.contrib.admin.util import get_fields_from_path, NotRelationField from django.contrib.admin.options import (flatten_fieldsets, BaseModelAdmin, ModelAdmin, HORIZONTAL, VERTICAL) __all__ = ['validate'] def validate(cls, model): """ Does basic ModelAdmin option validation. Calls custom validation classmethod in the end if it is provided in cls. The signature of the custom validation classmethod should be: def validate(cls, model). """ # Before we can introspect models, they need to be fully loaded so that # inter-relations are set up correctly. We force that here. models.get_apps() opts = model._meta validate_base(cls, model) # list_display if hasattr(cls, 'list_display'): check_isseq(cls, 'list_display', cls.list_display) for idx, field in enumerate(cls.list_display): if not callable(field): if not hasattr(cls, field): if not hasattr(model, field): try: opts.get_field(field) except models.FieldDoesNotExist: raise ImproperlyConfigured("%s.list_display[%d], %r is not a callable or an attribute of %r or found in the model %r." % (cls.__name__, idx, field, cls.__name__, model._meta.object_name)) else: # getattr(model, field) could be an X_RelatedObjectsDescriptor f = fetch_attr(cls, model, opts, "list_display[%d]" % idx, field) if isinstance(f, models.ManyToManyField): raise ImproperlyConfigured("'%s.list_display[%d]', '%s' is a ManyToManyField which is not supported." % (cls.__name__, idx, field)) # list_display_links if hasattr(cls, 'list_display_links'): check_isseq(cls, 'list_display_links', cls.list_display_links) for idx, field in enumerate(cls.list_display_links): if field not in cls.list_display: raise ImproperlyConfigured("'%s.list_display_links[%d]' " "refers to '%s' which is not defined in 'list_display'." % (cls.__name__, idx, field)) # list_filter if hasattr(cls, 'list_filter'): check_isseq(cls, 'list_filter', cls.list_filter) for idx, item in enumerate(cls.list_filter): # There are three options for specifying a filter: # 1: 'field' - a basic field filter, possibly w/ relationships (eg, 'field__rel') # 2: ('field', SomeFieldListFilter) - a field-based list filter class # 3: SomeListFilter - a non-field list filter class if callable(item) and not isinstance(item, models.Field): # If item is option 3, it should be a ListFilter... if not issubclass(item, ListFilter): raise ImproperlyConfigured("'%s.list_filter[%d]' is '%s'" " which is not a descendant of ListFilter." % (cls.__name__, idx, item.__name__)) # ... but not a FieldListFilter. if issubclass(item, FieldListFilter): raise ImproperlyConfigured("'%s.list_filter[%d]' is '%s'" " which is of type FieldListFilter but is not" " associated with a field name." % (cls.__name__, idx, item.__name__)) else: if isinstance(item, (tuple, list)): # item is option #2 field, list_filter_class = item if not issubclass(list_filter_class, FieldListFilter): raise ImproperlyConfigured("'%s.list_filter[%d][1]'" " is '%s' which is not of type FieldListFilter." % (cls.__name__, idx, list_filter_class.__name__)) else: # item is option #1 field = item # Validate the field string try: get_fields_from_path(model, field) except (NotRelationField, FieldDoesNotExist): raise ImproperlyConfigured("'%s.list_filter[%d]' refers to '%s'" " which does not refer to a Field." % (cls.__name__, idx, field)) # list_per_page = 100 if hasattr(cls, 'list_per_page') and not isinstance(cls.list_per_page, int): raise ImproperlyConfigured("'%s.list_per_page' should be a integer." % cls.__name__) # list_max_show_all if hasattr(cls, 'list_max_show_all') and not isinstance(cls.list_max_show_all, int): raise ImproperlyConfigured("'%s.list_max_show_all' should be an integer." % cls.__name__) # list_editable if hasattr(cls, 'list_editable') and cls.list_editable: check_isseq(cls, 'list_editable', cls.list_editable) for idx, field_name in enumerate(cls.list_editable): try: field = opts.get_field_by_name(field_name)[0] except models.FieldDoesNotExist: raise ImproperlyConfigured("'%s.list_editable[%d]' refers to a " "field, '%s', not defined on %s.%s." % (cls.__name__, idx, field_name, model._meta.app_label, model.__name__)) if field_name not in cls.list_display: raise ImproperlyConfigured("'%s.list_editable[%d]' refers to " "'%s' which is not defined in 'list_display'." % (cls.__name__, idx, field_name)) if field_name in cls.list_display_links: raise ImproperlyConfigured("'%s' cannot be in both '%s.list_editable'" " and '%s.list_display_links'" % (field_name, cls.__name__, cls.__name__)) if not cls.list_display_links and cls.list_display[0] in cls.list_editable: raise ImproperlyConfigured("'%s.list_editable[%d]' refers to" " the first field in list_display, '%s', which can't be" " used unless list_display_links is set." % (cls.__name__, idx, cls.list_display[0])) if not field.editable: raise ImproperlyConfigured("'%s.list_editable[%d]' refers to a " "field, '%s', which isn't editable through the admin." % (cls.__name__, idx, field_name)) # search_fields = () if hasattr(cls, 'search_fields'): check_isseq(cls, 'search_fields', cls.search_fields) # date_hierarchy = None if cls.date_hierarchy: f = get_field(cls, model, opts, 'date_hierarchy', cls.date_hierarchy) if not isinstance(f, (models.DateField, models.DateTimeField)): raise ImproperlyConfigured("'%s.date_hierarchy is " "neither an instance of DateField nor DateTimeField." % cls.__name__) # ordering = None if cls.ordering: check_isseq(cls, 'ordering', cls.ordering) for idx, field in enumerate(cls.ordering): if field == '?' and len(cls.ordering) != 1: raise ImproperlyConfigured("'%s.ordering' has the random " "ordering marker '?', but contains other fields as " "well. Please either remove '?' or the other fields." % cls.__name__) if field == '?': continue if field.startswith('-'): field = field[1:] # Skip ordering in the format field1__field2 (FIXME: checking # this format would be nice, but it's a little fiddly). if '__' in field: continue get_field(cls, model, opts, 'ordering[%d]' % idx, field) if hasattr(cls, "readonly_fields"): check_readonly_fields(cls, model, opts) # list_select_related = False # save_as = False # save_on_top = False for attr in ('list_select_related', 'save_as', 'save_on_top'): if not isinstance(getattr(cls, attr), bool): raise ImproperlyConfigured("'%s.%s' should be a boolean." % (cls.__name__, attr)) # inlines = [] if hasattr(cls, 'inlines'): check_isseq(cls, 'inlines', cls.inlines) for idx, inline in enumerate(cls.inlines): if not issubclass(inline, BaseModelAdmin): raise ImproperlyConfigured("'%s.inlines[%d]' does not inherit " "from BaseModelAdmin." % (cls.__name__, idx)) if not inline.model: raise ImproperlyConfigured("'model' is a required attribute " "of '%s.inlines[%d]'." % (cls.__name__, idx)) if not issubclass(inline.model, models.Model): raise ImproperlyConfigured("'%s.inlines[%d].model' does not " "inherit from models.Model." % (cls.__name__, idx)) validate_base(inline, inline.model) validate_inline(inline, cls, model) def validate_inline(cls, parent, parent_model): # model is already verified to exist and be a Model if cls.fk_name: # default value is None f = get_field(cls, cls.model, cls.model._meta, 'fk_name', cls.fk_name) if not isinstance(f, models.ForeignKey): raise ImproperlyConfigured("'%s.fk_name is not an instance of " "models.ForeignKey." % cls.__name__) fk = _get_foreign_key(parent_model, cls.model, fk_name=cls.fk_name, can_fail=True) # extra = 3 if not isinstance(cls.extra, int): raise ImproperlyConfigured("'%s.extra' should be a integer." % cls.__name__) # max_num = None max_num = getattr(cls, 'max_num', None) if max_num is not None and not isinstance(max_num, int): raise ImproperlyConfigured("'%s.max_num' should be an integer or None (default)." % cls.__name__) # formset if hasattr(cls, 'formset') and not issubclass(cls.formset, BaseModelFormSet): raise ImproperlyConfigured("'%s.formset' does not inherit from " "BaseModelFormSet." % cls.__name__) # exclude if hasattr(cls, 'exclude') and cls.exclude: if fk and fk.name in cls.exclude: raise ImproperlyConfigured("%s cannot exclude the field " "'%s' - this is the foreign key to the parent model " "%s.%s." % (cls.__name__, fk.name, parent_model._meta.app_label, parent_model.__name__)) if hasattr(cls, "readonly_fields"): check_readonly_fields(cls, cls.model, cls.model._meta) def validate_fields_spec(cls, model, opts, flds, label): """ Validate the fields specification in `flds` from a ModelAdmin subclass `cls` for the `model` model. `opts` is `model`'s Meta inner class. Use `label` for reporting problems to the user. The fields specification can be a ``fields`` option or a ``fields`` sub-option from a ``fieldsets`` option component. """ for fields in flds: # The entry in fields might be a tuple. If it is a standalone # field, make it into a tuple to make processing easier. if type(fields) != tuple: fields = (fields,) for field in fields: if field in cls.readonly_fields: # Stuff can be put in fields that isn't actually a # model field if it's in readonly_fields, # readonly_fields will handle the validation of such # things. continue check_formfield(cls, model, opts, label, field) try: f = opts.get_field(field) except models.FieldDoesNotExist: # If we can't find a field on the model that matches, it could be an # extra field on the form; nothing to check so move on to the next field. continue if isinstance(f, models.ManyToManyField) and not f.rel.through._meta.auto_created: raise ImproperlyConfigured("'%s.%s' " "can't include the ManyToManyField field '%s' because " "'%s' manually specifies a 'through' model." % ( cls.__name__, label, field, field)) def validate_base(cls, model): opts = model._meta # raw_id_fields if hasattr(cls, 'raw_id_fields'): check_isseq(cls, 'raw_id_fields', cls.raw_id_fields) for idx, field in enumerate(cls.raw_id_fields): f = get_field(cls, model, opts, 'raw_id_fields', field) if not isinstance(f, (models.ForeignKey, models.ManyToManyField)): raise ImproperlyConfigured("'%s.raw_id_fields[%d]', '%s' must " "be either a ForeignKey or ManyToManyField." % (cls.__name__, idx, field)) # fields if cls.fields: # default value is None check_isseq(cls, 'fields', cls.fields) validate_fields_spec(cls, model, opts, cls.fields, 'fields') if cls.fieldsets: raise ImproperlyConfigured('Both fieldsets and fields are specified in %s.' % cls.__name__) if len(cls.fields) > len(set(cls.fields)): raise ImproperlyConfigured('There are duplicate field(s) in %s.fields' % cls.__name__) # fieldsets if cls.fieldsets: # default value is None check_isseq(cls, 'fieldsets', cls.fieldsets) for idx, fieldset in enumerate(cls.fieldsets): check_isseq(cls, 'fieldsets[%d]' % idx, fieldset) if len(fieldset) != 2: raise ImproperlyConfigured("'%s.fieldsets[%d]' does not " "have exactly two elements." % (cls.__name__, idx)) check_isdict(cls, 'fieldsets[%d][1]' % idx, fieldset[1]) if 'fields' not in fieldset[1]: raise ImproperlyConfigured("'fields' key is required in " "%s.fieldsets[%d][1] field options dict." % (cls.__name__, idx)) validate_fields_spec(cls, model, opts, fieldset[1]['fields'], "fieldsets[%d][1]['fields']" % idx) flattened_fieldsets = flatten_fieldsets(cls.fieldsets) if len(flattened_fieldsets) > len(set(flattened_fieldsets)): raise ImproperlyConfigured('There are duplicate field(s) in %s.fieldsets' % cls.__name__) # exclude if cls.exclude: # default value is None check_isseq(cls, 'exclude', cls.exclude) for field in cls.exclude: check_formfield(cls, model, opts, 'exclude', field) try: f = opts.get_field(field) except models.FieldDoesNotExist: # If we can't find a field on the model that matches, # it could be an extra field on the form. continue if len(cls.exclude) > len(set(cls.exclude)): raise ImproperlyConfigured('There are duplicate field(s) in %s.exclude' % cls.__name__) # form if hasattr(cls, 'form') and not issubclass(cls.form, BaseModelForm): raise ImproperlyConfigured("%s.form does not inherit from " "BaseModelForm." % cls.__name__) # filter_vertical if hasattr(cls, 'filter_vertical'): check_isseq(cls, 'filter_vertical', cls.filter_vertical) for idx, field in enumerate(cls.filter_vertical): f = get_field(cls, model, opts, 'filter_vertical', field) if not isinstance(f, models.ManyToManyField): raise ImproperlyConfigured("'%s.filter_vertical[%d]' must be " "a ManyToManyField." % (cls.__name__, idx)) # filter_horizontal if hasattr(cls, 'filter_horizontal'): check_isseq(cls, 'filter_horizontal', cls.filter_horizontal) for idx, field in enumerate(cls.filter_horizontal): f = get_field(cls, model, opts, 'filter_horizontal', field) if not isinstance(f, models.ManyToManyField): raise ImproperlyConfigured("'%s.filter_horizontal[%d]' must be " "a ManyToManyField." % (cls.__name__, idx)) # radio_fields if hasattr(cls, 'radio_fields'): check_isdict(cls, 'radio_fields', cls.radio_fields) for field, val in cls.radio_fields.items(): f = get_field(cls, model, opts, 'radio_fields', field) if not (isinstance(f, models.ForeignKey) or f.choices): raise ImproperlyConfigured("'%s.radio_fields['%s']' " "is neither an instance of ForeignKey nor does " "have choices set." % (cls.__name__, field)) if not val in (HORIZONTAL, VERTICAL): raise ImproperlyConfigured("'%s.radio_fields['%s']' " "is neither admin.HORIZONTAL nor admin.VERTICAL." % (cls.__name__, field)) # prepopulated_fields if hasattr(cls, 'prepopulated_fields'): check_isdict(cls, 'prepopulated_fields', cls.prepopulated_fields) for field, val in cls.prepopulated_fields.items(): f = get_field(cls, model, opts, 'prepopulated_fields', field) if isinstance(f, (models.DateTimeField, models.ForeignKey, models.ManyToManyField)): raise ImproperlyConfigured("'%s.prepopulated_fields['%s']' " "is either a DateTimeField, ForeignKey or " "ManyToManyField. This isn't allowed." % (cls.__name__, field)) check_isseq(cls, "prepopulated_fields['%s']" % field, val) for idx, f in enumerate(val): get_field(cls, model, opts, "prepopulated_fields['%s'][%d]" % (field, idx), f) def check_isseq(cls, label, obj): if not isinstance(obj, (list, tuple)): raise ImproperlyConfigured("'%s.%s' must be a list or tuple." % (cls.__name__, label)) def check_isdict(cls, label, obj): if not isinstance(obj, dict): raise ImproperlyConfigured("'%s.%s' must be a dictionary." % (cls.__name__, label)) def get_field(cls, model, opts, label, field): try: return opts.get_field(field) except models.FieldDoesNotExist: raise ImproperlyConfigured("'%s.%s' refers to field '%s' that is missing from model '%s.%s'." % (cls.__name__, label, field, model._meta.app_label, model.__name__)) def check_formfield(cls, model, opts, label, field): if getattr(cls.form, 'base_fields', None): try: cls.form.base_fields[field] except KeyError: raise ImproperlyConfigured("'%s.%s' refers to field '%s' that " "is missing from the form." % (cls.__name__, label, field)) else: get_form_is_overridden = hasattr(cls, 'get_form') and cls.get_form != ModelAdmin.get_form if not get_form_is_overridden: fields = fields_for_model(model) try: fields[field] except KeyError: raise ImproperlyConfigured("'%s.%s' refers to field '%s' that " "is missing from the form." % (cls.__name__, label, field)) def fetch_attr(cls, model, opts, label, field): try: return opts.get_field(field) except models.FieldDoesNotExist: pass try: return getattr(model, field) except AttributeError: raise ImproperlyConfigured("'%s.%s' refers to '%s' that is neither a field, method or property of model '%s.%s'." % (cls.__name__, label, field, model._meta.app_label, model.__name__)) def check_readonly_fields(cls, model, opts): check_isseq(cls, "readonly_fields", cls.readonly_fields) for idx, field in enumerate(cls.readonly_fields): if not callable(field): if not hasattr(cls, field): if not hasattr(model, field): try: opts.get_field(field) except models.FieldDoesNotExist: raise ImproperlyConfigured("%s.readonly_fields[%d], %r is not a callable or an attribute of %r or found in the model %r." % (cls.__name__, idx, field, cls.__name__, model._meta.object_name))
apache-2.0
mrroach/CentralServer
csrv/model/cards/corp/__init__.py
1
1920
from card01054 import Card01054 from card01055 import Card01055 from card01056 import Card01056 from card01057 import Card01057 from card01058 import Card01058 from card01059 import Card01059 from card01060 import Card01060 from card01061 import Card01061 from card01062 import Card01062 from card01063 import Card01063 from card01064 import Card01064 from card01065 import Card01065 from card01066 import Card01066 from card01067 import Card01067 from card01068 import Card01068 from card01069 import Card01069 from card01070 import Card01070 from card01071 import Card01071 from card01072 import Card01072 from card01073 import Card01073 from card01074 import Card01074 from card01075 import Card01075 from card01076 import Card01076 from card01077 import Card01077 from card01078 import Card01078 from card01079 import Card01079 from card01080 import Card01080 from card01081 import Card01081 from card01082 import Card01082 from card01083 import Card01083 from card01084 import Card01084 from card01085 import Card01085 from card01086 import Card01086 from card01087 import Card01087 from card01088 import Card01088 from card01089 import Card01089 from card01090 import Card01090 from card01091 import Card01091 from card01092 import Card01092 from card01093 import Card01093 from card01094 import Card01094 from card01095 import Card01095 from card01096 import Card01096 from card01097 import Card01097 from card01098 import Card01098 from card01099 import Card01099 from card01100 import Card01100 from card01101 import Card01101 from card01102 import Card01102 from card01103 import Card01103 from card01104 import Card01104 from card01105 import Card01105 from card01106 import Card01106 from card01107 import Card01107 from card01108 import Card01108 from card01109 import Card01109 from card01110 import Card01110 from card01111 import Card01111 from card01112 import Card01112 from card01113 import Card01113
apache-2.0
CallaJun/hackprince
indico/PIL/OleFileIO.py
7
89128
#!/usr/bin/env python ## OleFileIO_PL: ## Module to read Microsoft OLE2 files (also called Structured Storage or ## Microsoft Compound Document File Format), such as Microsoft Office ## documents, Image Composer and FlashPix files, Outlook messages, ... ## This version is compatible with Python 2.6+ and 3.x ## version 0.30 2014-02-04 Philippe Lagadec - http://www.decalage.info ## Project website: http://www.decalage.info/python/olefileio ## Improved version of the OleFileIO module from PIL library v1.1.6 ## See: http://www.pythonware.com/products/pil/index.htm ## The Python Imaging Library (PIL) is ## Copyright (c) 1997-2005 by Secret Labs AB ## Copyright (c) 1995-2005 by Fredrik Lundh ## OleFileIO_PL changes are Copyright (c) 2005-2014 by Philippe Lagadec ## See source code and LICENSE.txt for information on usage and redistribution. ## WARNING: THIS IS (STILL) WORK IN PROGRESS. # Starting with OleFileIO_PL v0.30, only Python 2.6+ and 3.x is supported # This import enables print() as a function rather than a keyword # (main requirement to be compatible with Python 3.x) # The comment on the line below should be printed on Python 2.5 or older: from __future__ import print_function # This version of OleFileIO_PL requires Python 2.6+ or 3.x. __author__ = "Philippe Lagadec, Fredrik Lundh (Secret Labs AB)" __date__ = "2014-02-04" __version__ = '0.30' #--- LICENSE ------------------------------------------------------------------ # OleFileIO_PL is an improved version of the OleFileIO module from the # Python Imaging Library (PIL). # OleFileIO_PL changes are Copyright (c) 2005-2014 by Philippe Lagadec # # The Python Imaging Library (PIL) is # Copyright (c) 1997-2005 by Secret Labs AB # Copyright (c) 1995-2005 by Fredrik Lundh # # By obtaining, using, and/or copying this software and/or its associated # documentation, you agree that you have read, understood, and will comply with # the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and its # associated documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appears in all copies, and that both # that copyright notice and this permission notice appear in supporting # documentation, and that the name of Secret Labs AB or the author(s) not be used # in advertising or publicity pertaining to distribution of the software # without specific, written prior permission. # # SECRET LABS AB AND THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS # SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. # IN NO EVENT SHALL SECRET LABS AB OR THE AUTHORS BE LIABLE FOR ANY SPECIAL, # 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. #----------------------------------------------------------------------------- # CHANGELOG: (only OleFileIO_PL changes compared to PIL 1.1.6) # 2005-05-11 v0.10 PL: - a few fixes for Python 2.4 compatibility # (all changes flagged with [PL]) # 2006-02-22 v0.11 PL: - a few fixes for some Office 2003 documents which raise # exceptions in _OleStream.__init__() # 2006-06-09 v0.12 PL: - fixes for files above 6.8MB (DIFAT in loadfat) # - added some constants # - added header values checks # - added some docstrings # - getsect: bugfix in case sectors >512 bytes # - getsect: added conformity checks # - DEBUG_MODE constant to activate debug display # 2007-09-04 v0.13 PL: - improved/translated (lots of) comments # - updated license # - converted tabs to 4 spaces # 2007-11-19 v0.14 PL: - added OleFileIO._raise_defect() to adapt sensitivity # - improved _unicode() to use Python 2.x unicode support # - fixed bug in _OleDirectoryEntry # 2007-11-25 v0.15 PL: - added safety checks to detect FAT loops # - fixed _OleStream which didn't check stream size # - added/improved many docstrings and comments # - moved helper functions _unicode and _clsid out of # OleFileIO class # - improved OleFileIO._find() to add Unix path syntax # - OleFileIO._find() is now case-insensitive # - added get_type() and get_rootentry_name() # - rewritten loaddirectory and _OleDirectoryEntry # 2007-11-27 v0.16 PL: - added _OleDirectoryEntry.kids_dict # - added detection of duplicate filenames in storages # - added detection of duplicate references to streams # - added get_size() and exists() to _OleDirectoryEntry # - added isOleFile to check header before parsing # - added __all__ list to control public keywords in pydoc # 2007-12-04 v0.17 PL: - added _load_direntry to fix a bug in loaddirectory # - improved _unicode(), added workarounds for Python <2.3 # - added set_debug_mode and -d option to set debug mode # - fixed bugs in OleFileIO.open and _OleDirectoryEntry # - added safety check in main for large or binary # properties # - allow size>0 for storages for some implementations # 2007-12-05 v0.18 PL: - fixed several bugs in handling of FAT, MiniFAT and # streams # - added option '-c' in main to check all streams # 2009-12-10 v0.19 PL: - bugfix for 32 bit arrays on 64 bits platforms # (thanks to Ben G. and Martijn for reporting the bug) # 2009-12-11 v0.20 PL: - bugfix in OleFileIO.open when filename is not plain str # 2010-01-22 v0.21 PL: - added support for big-endian CPUs such as PowerPC Macs # 2012-02-16 v0.22 PL: - fixed bug in getproperties, patch by chuckleberryfinn # (https://bitbucket.org/decalage/olefileio_pl/issue/7) # - added close method to OleFileIO (fixed issue #2) # 2012-07-25 v0.23 PL: - added support for file-like objects (patch by mete0r_kr) # 2013-05-05 v0.24 PL: - getproperties: added conversion from filetime to python # datetime # - main: displays properties with date format # - new class OleMetadata to parse standard properties # - added get_metadata method # 2013-05-07 v0.24 PL: - a few improvements in OleMetadata # 2013-05-24 v0.25 PL: - getproperties: option to not convert some timestamps # - OleMetaData: total_edit_time is now a number of seconds, # not a timestamp # - getproperties: added support for VT_BOOL, VT_INT, V_UINT # - getproperties: filter out null chars from strings # - getproperties: raise non-fatal defects instead of # exceptions when properties cannot be parsed properly # 2013-05-27 PL: - getproperties: improved exception handling # - _raise_defect: added option to set exception type # - all non-fatal issues are now recorded, and displayed # when run as a script # 2013-07-11 v0.26 PL: - added methods to get modification and creation times # of a directory entry or a storage/stream # - fixed parsing of direntry timestamps # 2013-07-24 PL: - new options in listdir to list storages and/or streams # 2014-02-04 v0.30 PL: - upgraded code to support Python 3.x by Martin Panter # - several fixes for Python 2.6 (xrange, MAGIC) # - reused i32 from Pillow's _binary #----------------------------------------------------------------------------- # TODO (for version 1.0): # + isOleFile should accept file-like objects like open # + fix how all the methods handle unicode str and/or bytes as arguments # + add path attrib to _OleDirEntry, set it once and for all in init or # append_kids (then listdir/_list can be simplified) # - TESTS with Linux, MacOSX, Python 1.5.2, various files, PIL, ... # - add underscore to each private method, to avoid their display in # pydoc/epydoc documentation - Remove it for classes to be documented # - replace all raised exceptions with _raise_defect (at least in OleFileIO) # - merge code from _OleStream and OleFileIO.getsect to read sectors # (maybe add a class for FAT and MiniFAT ?) # - add method to check all streams (follow sectors chains without storing all # stream in memory, and report anomalies) # - use _OleDirectoryEntry.kids_dict to improve _find and _list ? # - fix Unicode names handling (find some way to stay compatible with Py1.5.2) # => if possible avoid converting names to Latin-1 # - review DIFAT code: fix handling of DIFSECT blocks in FAT (not stop) # - rewrite OleFileIO.getproperties # - improve docstrings to show more sample uses # - see also original notes and FIXME below # - remove all obsolete FIXMEs # - OleMetadata: fix version attrib according to # http://msdn.microsoft.com/en-us/library/dd945671%28v=office.12%29.aspx # IDEAS: # - in OleFileIO._open and _OleStream, use size=None instead of 0x7FFFFFFF for # streams with unknown size # - use arrays of int instead of long integers for FAT/MiniFAT, to improve # performance and reduce memory usage ? (possible issue with values >2^31) # - provide tests with unittest (may need write support to create samples) # - move all debug code (and maybe dump methods) to a separate module, with # a class which inherits OleFileIO ? # - fix docstrings to follow epydoc format # - add support for 4K sectors ? # - add support for big endian byte order ? # - create a simple OLE explorer with wxPython # FUTURE EVOLUTIONS to add write support: # 1) add ability to write a stream back on disk from BytesIO (same size, no # change in FAT/MiniFAT). # 2) rename a stream/storage if it doesn't change the RB tree # 3) use rbtree module to update the red-black tree + any rename # 4) remove a stream/storage: free sectors in FAT/MiniFAT # 5) allocate new sectors in FAT/MiniFAT # 6) create new storage/stream #----------------------------------------------------------------------------- # # THIS IS WORK IN PROGRESS # # The Python Imaging Library # $Id$ # # stuff to deal with OLE2 Structured Storage files. this module is # used by PIL to read Image Composer and FlashPix files, but can also # be used to read other files of this type. # # History: # 1997-01-20 fl Created # 1997-01-22 fl Fixed 64-bit portability quirk # 2003-09-09 fl Fixed typo in OleFileIO.loadfat (noted by Daniel Haertle) # 2004-02-29 fl Changed long hex constants to signed integers # # Notes: # FIXME: sort out sign problem (eliminate long hex constants) # FIXME: change filename to use "a/b/c" instead of ["a", "b", "c"] # FIXME: provide a glob mechanism function (using fnmatchcase) # # Literature: # # "FlashPix Format Specification, Appendix A", Kodak and Microsoft, # September 1996. # # Quotes: # # "If this document and functionality of the Software conflict, # the actual functionality of the Software represents the correct # functionality" -- Microsoft, in the OLE format specification # # Copyright (c) Secret Labs AB 1997. # Copyright (c) Fredrik Lundh 1997. # # See the README file for information on usage and redistribution. # #------------------------------------------------------------------------------ import io import sys import struct, array, os.path, datetime #[PL] Define explicitly the public API to avoid private objects in pydoc: __all__ = ['OleFileIO', 'isOleFile', 'MAGIC'] # For Python 3.x, need to redefine long as int: if str is not bytes: long = int # Need to make sure we use xrange both on Python 2 and 3.x: try: # on Python 2 we need xrange: iterrange = xrange except: # no xrange, for Python 3 it was renamed as range: iterrange = range #[PL] workaround to fix an issue with array item size on 64 bits systems: if array.array('L').itemsize == 4: # on 32 bits platforms, long integers in an array are 32 bits: UINT32 = 'L' elif array.array('I').itemsize == 4: # on 64 bits platforms, integers in an array are 32 bits: UINT32 = 'I' else: raise ValueError('Need to fix a bug with 32 bit arrays, please contact author...') #[PL] These workarounds were inspired from the Path module # (see http://www.jorendorff.com/articles/python/path/) #TODO: test with old Python versions # Pre-2.3 workaround for basestring. try: basestring except NameError: try: # is Unicode supported (Python >2.0 or >1.6 ?) basestring = (str, unicode) except NameError: basestring = str #[PL] Experimental setting: if True, OLE filenames will be kept in Unicode # if False (default PIL behaviour), all filenames are converted to Latin-1. KEEP_UNICODE_NAMES = False #[PL] DEBUG display mode: False by default, use set_debug_mode() or "-d" on # command line to change it. DEBUG_MODE = False def debug_print(msg): print(msg) def debug_pass(msg): pass debug = debug_pass def set_debug_mode(debug_mode): """ Set debug mode on or off, to control display of debugging messages. mode: True or False """ global DEBUG_MODE, debug DEBUG_MODE = debug_mode if debug_mode: debug = debug_print else: debug = debug_pass MAGIC = b'\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1' #[PL]: added constants for Sector IDs (from AAF specifications) MAXREGSECT = 0xFFFFFFFA; # maximum SECT DIFSECT = 0xFFFFFFFC; # (-4) denotes a DIFAT sector in a FAT FATSECT = 0xFFFFFFFD; # (-3) denotes a FAT sector in a FAT ENDOFCHAIN = 0xFFFFFFFE; # (-2) end of a virtual stream chain FREESECT = 0xFFFFFFFF; # (-1) unallocated sector #[PL]: added constants for Directory Entry IDs (from AAF specifications) MAXREGSID = 0xFFFFFFFA; # maximum directory entry ID NOSTREAM = 0xFFFFFFFF; # (-1) unallocated directory entry #[PL] object types in storage (from AAF specifications) STGTY_EMPTY = 0 # empty directory entry (according to OpenOffice.org doc) STGTY_STORAGE = 1 # element is a storage object STGTY_STREAM = 2 # element is a stream object STGTY_LOCKBYTES = 3 # element is an ILockBytes object STGTY_PROPERTY = 4 # element is an IPropertyStorage object STGTY_ROOT = 5 # element is a root storage # # -------------------------------------------------------------------- # property types VT_EMPTY=0; VT_NULL=1; VT_I2=2; VT_I4=3; VT_R4=4; VT_R8=5; VT_CY=6; VT_DATE=7; VT_BSTR=8; VT_DISPATCH=9; VT_ERROR=10; VT_BOOL=11; VT_VARIANT=12; VT_UNKNOWN=13; VT_DECIMAL=14; VT_I1=16; VT_UI1=17; VT_UI2=18; VT_UI4=19; VT_I8=20; VT_UI8=21; VT_INT=22; VT_UINT=23; VT_VOID=24; VT_HRESULT=25; VT_PTR=26; VT_SAFEARRAY=27; VT_CARRAY=28; VT_USERDEFINED=29; VT_LPSTR=30; VT_LPWSTR=31; VT_FILETIME=64; VT_BLOB=65; VT_STREAM=66; VT_STORAGE=67; VT_STREAMED_OBJECT=68; VT_STORED_OBJECT=69; VT_BLOB_OBJECT=70; VT_CF=71; VT_CLSID=72; VT_VECTOR=0x1000; # map property id to name (for debugging purposes) VT = {} for keyword, var in list(vars().items()): if keyword[:3] == "VT_": VT[var] = keyword # # -------------------------------------------------------------------- # Some common document types (root.clsid fields) WORD_CLSID = "00020900-0000-0000-C000-000000000046" #TODO: check Excel, PPT, ... #[PL]: Defect levels to classify parsing errors - see OleFileIO._raise_defect() DEFECT_UNSURE = 10 # a case which looks weird, but not sure it's a defect DEFECT_POTENTIAL = 20 # a potential defect DEFECT_INCORRECT = 30 # an error according to specifications, but parsing # can go on DEFECT_FATAL = 40 # an error which cannot be ignored, parsing is # impossible #[PL] add useful constants to __all__: for key in list(vars().keys()): if key.startswith('STGTY_') or key.startswith('DEFECT_'): __all__.append(key) #--- FUNCTIONS ---------------------------------------------------------------- def isOleFile (filename): """ Test if file is an OLE container (according to its header). :param filename: file name or path (str, unicode) :returns: True if OLE, False otherwise. """ f = open(filename, 'rb') header = f.read(len(MAGIC)) if header == MAGIC: return True else: return False if bytes is str: # version for Python 2.x def i8(c): return ord(c) else: # version for Python 3.x def i8(c): return c if c.__class__ is int else c[0] #TODO: replace i16 and i32 with more readable struct.unpack equivalent? def i16(c, o = 0): """ Converts a 2-bytes (16 bits) string to an integer. :param c: string containing bytes to convert :param o: offset of bytes to convert in string """ return i8(c[o]) | (i8(c[o+1])<<8) def i32(c, o = 0): """ Converts a 4-bytes (32 bits) string to an integer. :param c: string containing bytes to convert :param o: offset of bytes to convert in string """ ## return int(ord(c[o])+(ord(c[o+1])<<8)+(ord(c[o+2])<<16)+(ord(c[o+3])<<24)) ## # [PL]: added int() because "<<" gives long int since Python 2.4 # copied from Pillow's _binary: return i8(c[o]) | (i8(c[o+1])<<8) | (i8(c[o+2])<<16) | (i8(c[o+3])<<24) def _clsid(clsid): """ Converts a CLSID to a human-readable string. :param clsid: string of length 16. """ assert len(clsid) == 16 # if clsid is only made of null bytes, return an empty string: # (PL: why not simply return the string with zeroes?) if not clsid.strip(b"\0"): return "" return (("%08X-%04X-%04X-%02X%02X-" + "%02X" * 6) % ((i32(clsid, 0), i16(clsid, 4), i16(clsid, 6)) + tuple(map(i8, clsid[8:16])))) # UNICODE support: # (necessary to handle storages/streams names which use Unicode) def _unicode(s, errors='replace'): """ Map unicode string to Latin 1. (Python with Unicode support) :param s: UTF-16LE unicode string to convert to Latin-1 :param errors: 'replace', 'ignore' or 'strict'. """ #TODO: test if it OleFileIO works with Unicode strings, instead of # converting to Latin-1. try: # First the string is converted to plain Unicode: # (assuming it is encoded as UTF-16 little-endian) u = s.decode('UTF-16LE', errors) if bytes is not str or KEEP_UNICODE_NAMES: return u else: # Second the unicode string is converted to Latin-1 return u.encode('latin_1', errors) except: # there was an error during Unicode to Latin-1 conversion: raise IOError('incorrect Unicode name') def filetime2datetime(filetime): """ convert FILETIME (64 bits int) to Python datetime.datetime """ # TODO: manage exception when microseconds is too large # inspired from http://code.activestate.com/recipes/511425-filetime-to-datetime/ _FILETIME_null_date = datetime.datetime(1601, 1, 1, 0, 0, 0) #debug('timedelta days=%d' % (filetime//(10*1000000*3600*24))) return _FILETIME_null_date + datetime.timedelta(microseconds=filetime//10) #=== CLASSES ================================================================== class OleMetadata: """ class to parse and store metadata from standard properties of OLE files. Available attributes: codepage, title, subject, author, keywords, comments, template, last_saved_by, revision_number, total_edit_time, last_printed, create_time, last_saved_time, num_pages, num_words, num_chars, thumbnail, creating_application, security, codepage_doc, category, presentation_target, bytes, lines, paragraphs, slides, notes, hidden_slides, mm_clips, scale_crop, heading_pairs, titles_of_parts, manager, company, links_dirty, chars_with_spaces, unused, shared_doc, link_base, hlinks, hlinks_changed, version, dig_sig, content_type, content_status, language, doc_version Note: an attribute is set to None when not present in the properties of the OLE file. References for SummaryInformation stream: - http://msdn.microsoft.com/en-us/library/dd942545.aspx - http://msdn.microsoft.com/en-us/library/dd925819%28v=office.12%29.aspx - http://msdn.microsoft.com/en-us/library/windows/desktop/aa380376%28v=vs.85%29.aspx - http://msdn.microsoft.com/en-us/library/aa372045.aspx - http://sedna-soft.de/summary-information-stream/ - http://poi.apache.org/apidocs/org/apache/poi/hpsf/SummaryInformation.html References for DocumentSummaryInformation stream: - http://msdn.microsoft.com/en-us/library/dd945671%28v=office.12%29.aspx - http://msdn.microsoft.com/en-us/library/windows/desktop/aa380374%28v=vs.85%29.aspx - http://poi.apache.org/apidocs/org/apache/poi/hpsf/DocumentSummaryInformation.html new in version 0.25 """ # attribute names for SummaryInformation stream properties: # (ordered by property id, starting at 1) SUMMARY_ATTRIBS = ['codepage', 'title', 'subject', 'author', 'keywords', 'comments', 'template', 'last_saved_by', 'revision_number', 'total_edit_time', 'last_printed', 'create_time', 'last_saved_time', 'num_pages', 'num_words', 'num_chars', 'thumbnail', 'creating_application', 'security'] # attribute names for DocumentSummaryInformation stream properties: # (ordered by property id, starting at 1) DOCSUM_ATTRIBS = ['codepage_doc', 'category', 'presentation_target', 'bytes', 'lines', 'paragraphs', 'slides', 'notes', 'hidden_slides', 'mm_clips', 'scale_crop', 'heading_pairs', 'titles_of_parts', 'manager', 'company', 'links_dirty', 'chars_with_spaces', 'unused', 'shared_doc', 'link_base', 'hlinks', 'hlinks_changed', 'version', 'dig_sig', 'content_type', 'content_status', 'language', 'doc_version'] def __init__(self): """ Constructor for OleMetadata All attributes are set to None by default """ # properties from SummaryInformation stream self.codepage = None self.title = None self.subject = None self.author = None self.keywords = None self.comments = None self.template = None self.last_saved_by = None self.revision_number = None self.total_edit_time = None self.last_printed = None self.create_time = None self.last_saved_time = None self.num_pages = None self.num_words = None self.num_chars = None self.thumbnail = None self.creating_application = None self.security = None # properties from DocumentSummaryInformation stream self.codepage_doc = None self.category = None self.presentation_target = None self.bytes = None self.lines = None self.paragraphs = None self.slides = None self.notes = None self.hidden_slides = None self.mm_clips = None self.scale_crop = None self.heading_pairs = None self.titles_of_parts = None self.manager = None self.company = None self.links_dirty = None self.chars_with_spaces = None self.unused = None self.shared_doc = None self.link_base = None self.hlinks = None self.hlinks_changed = None self.version = None self.dig_sig = None self.content_type = None self.content_status = None self.language = None self.doc_version = None def parse_properties(self, olefile): """ Parse standard properties of an OLE file, from the streams "\x05SummaryInformation" and "\x05DocumentSummaryInformation", if present. Properties are converted to strings, integers or python datetime objects. If a property is not present, its value is set to None. """ # first set all attributes to None: for attrib in (self.SUMMARY_ATTRIBS + self.DOCSUM_ATTRIBS): setattr(self, attrib, None) if olefile.exists("\x05SummaryInformation"): # get properties from the stream: # (converting timestamps to python datetime, except total_edit_time, # which is property #10) props = olefile.getproperties("\x05SummaryInformation", convert_time=True, no_conversion=[10]) # store them into this object's attributes: for i in range(len(self.SUMMARY_ATTRIBS)): # ids for standards properties start at 0x01, until 0x13 value = props.get(i+1, None) setattr(self, self.SUMMARY_ATTRIBS[i], value) if olefile.exists("\x05DocumentSummaryInformation"): # get properties from the stream: props = olefile.getproperties("\x05DocumentSummaryInformation", convert_time=True) # store them into this object's attributes: for i in range(len(self.DOCSUM_ATTRIBS)): # ids for standards properties start at 0x01, until 0x13 value = props.get(i+1, None) setattr(self, self.DOCSUM_ATTRIBS[i], value) def dump(self): """ Dump all metadata, for debugging purposes. """ print('Properties from SummaryInformation stream:') for prop in self.SUMMARY_ATTRIBS: value = getattr(self, prop) print('- %s: %s' % (prop, repr(value))) print('Properties from DocumentSummaryInformation stream:') for prop in self.DOCSUM_ATTRIBS: value = getattr(self, prop) print('- %s: %s' % (prop, repr(value))) #--- _OleStream --------------------------------------------------------------- class _OleStream(io.BytesIO): """ OLE2 Stream Returns a read-only file object which can be used to read the contents of a OLE stream (instance of the BytesIO class). To open a stream, use the openstream method in the OleFile class. This function can be used with either ordinary streams, or ministreams, depending on the offset, sectorsize, and fat table arguments. Attributes: - size: actual size of data stream, after it was opened. """ # FIXME: should store the list of sects obtained by following # the fat chain, and load new sectors on demand instead of # loading it all in one go. def __init__(self, fp, sect, size, offset, sectorsize, fat, filesize): """ Constructor for _OleStream class. :param fp : file object, the OLE container or the MiniFAT stream :param sect : sector index of first sector in the stream :param size : total size of the stream :param offset : offset in bytes for the first FAT or MiniFAT sector :param sectorsize: size of one sector :param fat : array/list of sector indexes (FAT or MiniFAT) :param filesize : size of OLE file (for debugging) :returns : a BytesIO instance containing the OLE stream """ debug('_OleStream.__init__:') debug(' sect=%d (%X), size=%d, offset=%d, sectorsize=%d, len(fat)=%d, fp=%s' %(sect,sect,size,offset,sectorsize,len(fat), repr(fp))) #[PL] To detect malformed documents with FAT loops, we compute the # expected number of sectors in the stream: unknown_size = False if size==0x7FFFFFFF: # this is the case when called from OleFileIO._open(), and stream # size is not known in advance (for example when reading the # Directory stream). Then we can only guess maximum size: size = len(fat)*sectorsize # and we keep a record that size was unknown: unknown_size = True debug(' stream with UNKNOWN SIZE') nb_sectors = (size + (sectorsize-1)) // sectorsize debug('nb_sectors = %d' % nb_sectors) # This number should (at least) be less than the total number of # sectors in the given FAT: if nb_sectors > len(fat): raise IOError('malformed OLE document, stream too large') # optimization(?): data is first a list of strings, and join() is called # at the end to concatenate all in one string. # (this may not be really useful with recent Python versions) data = [] # if size is zero, then first sector index should be ENDOFCHAIN: if size == 0 and sect != ENDOFCHAIN: debug('size == 0 and sect != ENDOFCHAIN:') raise IOError('incorrect OLE sector index for empty stream') #[PL] A fixed-length for loop is used instead of an undefined while # loop to avoid DoS attacks: for i in range(nb_sectors): # Sector index may be ENDOFCHAIN, but only if size was unknown if sect == ENDOFCHAIN: if unknown_size: break else: # else this means that the stream is smaller than declared: debug('sect=ENDOFCHAIN before expected size') raise IOError('incomplete OLE stream') # sector index should be within FAT: if sect<0 or sect>=len(fat): debug('sect=%d (%X) / len(fat)=%d' % (sect, sect, len(fat))) debug('i=%d / nb_sectors=%d' %(i, nb_sectors)) ## tmp_data = b"".join(data) ## f = open('test_debug.bin', 'wb') ## f.write(tmp_data) ## f.close() ## debug('data read so far: %d bytes' % len(tmp_data)) raise IOError('incorrect OLE FAT, sector index out of range') #TODO: merge this code with OleFileIO.getsect() ? #TODO: check if this works with 4K sectors: try: fp.seek(offset + sectorsize * sect) except: debug('sect=%d, seek=%d, filesize=%d' % (sect, offset+sectorsize*sect, filesize)) raise IOError('OLE sector index out of range') sector_data = fp.read(sectorsize) # [PL] check if there was enough data: # Note: if sector is the last of the file, sometimes it is not a # complete sector (of 512 or 4K), so we may read less than # sectorsize. if len(sector_data)!=sectorsize and sect!=(len(fat)-1): debug('sect=%d / len(fat)=%d, seek=%d / filesize=%d, len read=%d' % (sect, len(fat), offset+sectorsize*sect, filesize, len(sector_data))) debug('seek+len(read)=%d' % (offset+sectorsize*sect+len(sector_data))) raise IOError('incomplete OLE sector') data.append(sector_data) # jump to next sector in the FAT: try: sect = fat[sect] except IndexError: # [PL] if pointer is out of the FAT an exception is raised raise IOError('incorrect OLE FAT, sector index out of range') #[PL] Last sector should be a "end of chain" marker: if sect != ENDOFCHAIN: raise IOError('incorrect last sector index in OLE stream') data = b"".join(data) # Data is truncated to the actual stream size: if len(data) >= size: data = data[:size] # actual stream size is stored for future use: self.size = size elif unknown_size: # actual stream size was not known, now we know the size of read # data: self.size = len(data) else: # read data is less than expected: debug('len(data)=%d, size=%d' % (len(data), size)) raise IOError('OLE stream size is less than declared') # when all data is read in memory, BytesIO constructor is called io.BytesIO.__init__(self, data) # Then the _OleStream object can be used as a read-only file object. #--- _OleDirectoryEntry ------------------------------------------------------- class _OleDirectoryEntry: """ OLE2 Directory Entry """ #[PL] parsing code moved from OleFileIO.loaddirectory # struct to parse directory entries: # <: little-endian byte order, standard sizes # (note: this should guarantee that Q returns a 64 bits int) # 64s: string containing entry name in unicode (max 31 chars) + null char # H: uint16, number of bytes used in name buffer, including null = (len+1)*2 # B: uint8, dir entry type (between 0 and 5) # B: uint8, color: 0=black, 1=red # I: uint32, index of left child node in the red-black tree, NOSTREAM if none # I: uint32, index of right child node in the red-black tree, NOSTREAM if none # I: uint32, index of child root node if it is a storage, else NOSTREAM # 16s: CLSID, unique identifier (only used if it is a storage) # I: uint32, user flags # Q (was 8s): uint64, creation timestamp or zero # Q (was 8s): uint64, modification timestamp or zero # I: uint32, SID of first sector if stream or ministream, SID of 1st sector # of stream containing ministreams if root entry, 0 otherwise # I: uint32, total stream size in bytes if stream (low 32 bits), 0 otherwise # I: uint32, total stream size in bytes if stream (high 32 bits), 0 otherwise STRUCT_DIRENTRY = '<64sHBBIII16sIQQIII' # size of a directory entry: 128 bytes DIRENTRY_SIZE = 128 assert struct.calcsize(STRUCT_DIRENTRY) == DIRENTRY_SIZE def __init__(self, entry, sid, olefile): """ Constructor for an _OleDirectoryEntry object. Parses a 128-bytes entry from the OLE Directory stream. :param entry : string (must be 128 bytes long) :param sid : index of this directory entry in the OLE file directory :param olefile: OleFileIO containing this directory entry """ self.sid = sid # ref to olefile is stored for future use self.olefile = olefile # kids is a list of children entries, if this entry is a storage: # (list of _OleDirectoryEntry objects) self.kids = [] # kids_dict is a dictionary of children entries, indexed by their # name in lowercase: used to quickly find an entry, and to detect # duplicates self.kids_dict = {} # flag used to detect if the entry is referenced more than once in # directory: self.used = False # decode DirEntry ( name, namelength, self.entry_type, self.color, self.sid_left, self.sid_right, self.sid_child, clsid, self.dwUserFlags, self.createTime, self.modifyTime, self.isectStart, sizeLow, sizeHigh ) = struct.unpack(_OleDirectoryEntry.STRUCT_DIRENTRY, entry) if self.entry_type not in [STGTY_ROOT, STGTY_STORAGE, STGTY_STREAM, STGTY_EMPTY]: olefile._raise_defect(DEFECT_INCORRECT, 'unhandled OLE storage type') # only first directory entry can (and should) be root: if self.entry_type == STGTY_ROOT and sid != 0: olefile._raise_defect(DEFECT_INCORRECT, 'duplicate OLE root entry') if sid == 0 and self.entry_type != STGTY_ROOT: olefile._raise_defect(DEFECT_INCORRECT, 'incorrect OLE root entry') #debug (struct.unpack(fmt_entry, entry[:len_entry])) # name should be at most 31 unicode characters + null character, # so 64 bytes in total (31*2 + 2): if namelength>64: olefile._raise_defect(DEFECT_INCORRECT, 'incorrect DirEntry name length') # if exception not raised, namelength is set to the maximum value: namelength = 64 # only characters without ending null char are kept: name = name[:(namelength-2)] # name is converted from unicode to Latin-1: self.name = _unicode(name) debug('DirEntry SID=%d: %s' % (self.sid, repr(self.name))) debug(' - type: %d' % self.entry_type) debug(' - sect: %d' % self.isectStart) debug(' - SID left: %d, right: %d, child: %d' % (self.sid_left, self.sid_right, self.sid_child)) # sizeHigh is only used for 4K sectors, it should be zero for 512 bytes # sectors, BUT apparently some implementations set it as 0xFFFFFFFF, 1 # or some other value so it cannot be raised as a defect in general: if olefile.sectorsize == 512: if sizeHigh != 0 and sizeHigh != 0xFFFFFFFF: debug('sectorsize=%d, sizeLow=%d, sizeHigh=%d (%X)' % (olefile.sectorsize, sizeLow, sizeHigh, sizeHigh)) olefile._raise_defect(DEFECT_UNSURE, 'incorrect OLE stream size') self.size = sizeLow else: self.size = sizeLow + (long(sizeHigh)<<32) debug(' - size: %d (sizeLow=%d, sizeHigh=%d)' % (self.size, sizeLow, sizeHigh)) self.clsid = _clsid(clsid) # a storage should have a null size, BUT some implementations such as # Word 8 for Mac seem to allow non-null values => Potential defect: if self.entry_type == STGTY_STORAGE and self.size != 0: olefile._raise_defect(DEFECT_POTENTIAL, 'OLE storage with size>0') # check if stream is not already referenced elsewhere: if self.entry_type in (STGTY_ROOT, STGTY_STREAM) and self.size>0: if self.size < olefile.minisectorcutoff \ and self.entry_type==STGTY_STREAM: # only streams can be in MiniFAT # ministream object minifat = True else: minifat = False olefile._check_duplicate_stream(self.isectStart, minifat) def build_storage_tree(self): """ Read and build the red-black tree attached to this _OleDirectoryEntry object, if it is a storage. Note that this method builds a tree of all subentries, so it should only be called for the root object once. """ debug('build_storage_tree: SID=%d - %s - sid_child=%d' % (self.sid, repr(self.name), self.sid_child)) if self.sid_child != NOSTREAM: # if child SID is not NOSTREAM, then this entry is a storage. # Let's walk through the tree of children to fill the kids list: self.append_kids(self.sid_child) # Note from OpenOffice documentation: the safest way is to # recreate the tree because some implementations may store broken # red-black trees... # in the OLE file, entries are sorted on (length, name). # for convenience, we sort them on name instead: # (see rich comparison methods in this class) self.kids.sort() def append_kids(self, child_sid): """ Walk through red-black tree of children of this directory entry to add all of them to the kids list. (recursive method) child_sid : index of child directory entry to use, or None when called first time for the root. (only used during recursion) """ #[PL] this method was added to use simple recursion instead of a complex # algorithm. # if this is not a storage or a leaf of the tree, nothing to do: if child_sid == NOSTREAM: return # check if child SID is in the proper range: if child_sid<0 or child_sid>=len(self.olefile.direntries): self.olefile._raise_defect(DEFECT_FATAL, 'OLE DirEntry index out of range') # get child direntry: child = self.olefile._load_direntry(child_sid) #direntries[child_sid] debug('append_kids: child_sid=%d - %s - sid_left=%d, sid_right=%d, sid_child=%d' % (child.sid, repr(child.name), child.sid_left, child.sid_right, child.sid_child)) # the directory entries are organized as a red-black tree. # (cf. Wikipedia for details) # First walk through left side of the tree: self.append_kids(child.sid_left) # Check if its name is not already used (case-insensitive): name_lower = child.name.lower() if name_lower in self.kids_dict: self.olefile._raise_defect(DEFECT_INCORRECT, "Duplicate filename in OLE storage") # Then the child_sid _OleDirectoryEntry object is appended to the # kids list and dictionary: self.kids.append(child) self.kids_dict[name_lower] = child # Check if kid was not already referenced in a storage: if child.used: self.olefile._raise_defect(DEFECT_INCORRECT, 'OLE Entry referenced more than once') child.used = True # Finally walk through right side of the tree: self.append_kids(child.sid_right) # Afterwards build kid's own tree if it's also a storage: child.build_storage_tree() def __eq__(self, other): "Compare entries by name" return self.name == other.name def __lt__(self, other): "Compare entries by name" return self.name < other.name def __ne__(self, other): return not self.__eq__(other) def __le__(self, other): return self.__eq__(other) or self.__lt__(other) # Reflected __lt__() and __le__() will be used for __gt__() and __ge__() #TODO: replace by the same function as MS implementation ? # (order by name length first, then case-insensitive order) def dump(self, tab = 0): "Dump this entry, and all its subentries (for debug purposes only)" TYPES = ["(invalid)", "(storage)", "(stream)", "(lockbytes)", "(property)", "(root)"] print(" "*tab + repr(self.name), TYPES[self.entry_type], end=' ') if self.entry_type in (STGTY_STREAM, STGTY_ROOT): print(self.size, "bytes", end=' ') print() if self.entry_type in (STGTY_STORAGE, STGTY_ROOT) and self.clsid: print(" "*tab + "{%s}" % self.clsid) for kid in self.kids: kid.dump(tab + 2) def getmtime(self): """ Return modification time of a directory entry. :returns: None if modification time is null, a python datetime object otherwise (UTC timezone) new in version 0.26 """ if self.modifyTime == 0: return None return filetime2datetime(self.modifyTime) def getctime(self): """ Return creation time of a directory entry. :returns: None if modification time is null, a python datetime object otherwise (UTC timezone) new in version 0.26 """ if self.createTime == 0: return None return filetime2datetime(self.createTime) #--- OleFileIO ---------------------------------------------------------------- class OleFileIO: """ OLE container object This class encapsulates the interface to an OLE 2 structured storage file. Use the :py:meth:`~PIL.OleFileIO.OleFileIO.listdir` and :py:meth:`~PIL.OleFileIO.OleFileIO.openstream` methods to access the contents of this file. Object names are given as a list of strings, one for each subentry level. The root entry should be omitted. For example, the following code extracts all image streams from a Microsoft Image Composer file:: ole = OleFileIO("fan.mic") for entry in ole.listdir(): if entry[1:2] == "Image": fin = ole.openstream(entry) fout = open(entry[0:1], "wb") while True: s = fin.read(8192) if not s: break fout.write(s) You can use the viewer application provided with the Python Imaging Library to view the resulting files (which happens to be standard TIFF files). """ def __init__(self, filename = None, raise_defects=DEFECT_FATAL): """ Constructor for OleFileIO class. :param filename: file to open. :param raise_defects: minimal level for defects to be raised as exceptions. (use DEFECT_FATAL for a typical application, DEFECT_INCORRECT for a security-oriented application, see source code for details) """ # minimal level for defects to be raised as exceptions: self._raise_defects_level = raise_defects # list of defects/issues not raised as exceptions: # tuples of (exception type, message) self.parsing_issues = [] if filename: self.open(filename) def _raise_defect(self, defect_level, message, exception_type=IOError): """ This method should be called for any defect found during file parsing. It may raise an IOError exception according to the minimal level chosen for the OleFileIO object. :param defect_level: defect level, possible values are: DEFECT_UNSURE : a case which looks weird, but not sure it's a defect DEFECT_POTENTIAL : a potential defect DEFECT_INCORRECT : an error according to specifications, but parsing can go on DEFECT_FATAL : an error which cannot be ignored, parsing is impossible :param message: string describing the defect, used with raised exception. :param exception_type: exception class to be raised, IOError by default """ # added by [PL] if defect_level >= self._raise_defects_level: raise exception_type(message) else: # just record the issue, no exception raised: self.parsing_issues.append((exception_type, message)) def open(self, filename): """ Open an OLE2 file. Reads the header, FAT and directory. :param filename: string-like or file-like object """ #[PL] check if filename is a string-like or file-like object: # (it is better to check for a read() method) if hasattr(filename, 'read'): # file-like object self.fp = filename else: # string-like object: filename of file on disk #TODO: if larger than 1024 bytes, this could be the actual data => BytesIO self.fp = open(filename, "rb") # old code fails if filename is not a plain string: #if isinstance(filename, (bytes, basestring)): # self.fp = open(filename, "rb") #else: # self.fp = filename # obtain the filesize by using seek and tell, which should work on most # file-like objects: #TODO: do it above, using getsize with filename when possible? #TODO: fix code to fail with clear exception when filesize cannot be obtained self.fp.seek(0, os.SEEK_END) try: filesize = self.fp.tell() finally: self.fp.seek(0) self._filesize = filesize # lists of streams in FAT and MiniFAT, to detect duplicate references # (list of indexes of first sectors of each stream) self._used_streams_fat = [] self._used_streams_minifat = [] header = self.fp.read(512) if len(header) != 512 or header[:8] != MAGIC: self._raise_defect(DEFECT_FATAL, "not an OLE2 structured storage file") # [PL] header structure according to AAF specifications: ##Header ##struct StructuredStorageHeader { // [offset from start (bytes), length (bytes)] ##BYTE _abSig[8]; // [00H,08] {0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, ## // 0x1a, 0xe1} for current version ##CLSID _clsid; // [08H,16] reserved must be zero (WriteClassStg/ ## // GetClassFile uses root directory class id) ##USHORT _uMinorVersion; // [18H,02] minor version of the format: 33 is ## // written by reference implementation ##USHORT _uDllVersion; // [1AH,02] major version of the dll/format: 3 for ## // 512-byte sectors, 4 for 4 KB sectors ##USHORT _uByteOrder; // [1CH,02] 0xFFFE: indicates Intel byte-ordering ##USHORT _uSectorShift; // [1EH,02] size of sectors in power-of-two; ## // typically 9 indicating 512-byte sectors ##USHORT _uMiniSectorShift; // [20H,02] size of mini-sectors in power-of-two; ## // typically 6 indicating 64-byte mini-sectors ##USHORT _usReserved; // [22H,02] reserved, must be zero ##ULONG _ulReserved1; // [24H,04] reserved, must be zero ##FSINDEX _csectDir; // [28H,04] must be zero for 512-byte sectors, ## // number of SECTs in directory chain for 4 KB ## // sectors ##FSINDEX _csectFat; // [2CH,04] number of SECTs in the FAT chain ##SECT _sectDirStart; // [30H,04] first SECT in the directory chain ##DFSIGNATURE _signature; // [34H,04] signature used for transactions; must ## // be zero. The reference implementation ## // does not support transactions ##ULONG _ulMiniSectorCutoff; // [38H,04] maximum size for a mini stream; ## // typically 4096 bytes ##SECT _sectMiniFatStart; // [3CH,04] first SECT in the MiniFAT chain ##FSINDEX _csectMiniFat; // [40H,04] number of SECTs in the MiniFAT chain ##SECT _sectDifStart; // [44H,04] first SECT in the DIFAT chain ##FSINDEX _csectDif; // [48H,04] number of SECTs in the DIFAT chain ##SECT _sectFat[109]; // [4CH,436] the SECTs of first 109 FAT sectors ##}; # [PL] header decoding: # '<' indicates little-endian byte ordering for Intel (cf. struct module help) fmt_header = '<8s16sHHHHHHLLLLLLLLLL' header_size = struct.calcsize(fmt_header) debug( "fmt_header size = %d, +FAT = %d" % (header_size, header_size + 109*4) ) header1 = header[:header_size] ( self.Sig, self.clsid, self.MinorVersion, self.DllVersion, self.ByteOrder, self.SectorShift, self.MiniSectorShift, self.Reserved, self.Reserved1, self.csectDir, self.csectFat, self.sectDirStart, self.signature, self.MiniSectorCutoff, self.MiniFatStart, self.csectMiniFat, self.sectDifStart, self.csectDif ) = struct.unpack(fmt_header, header1) debug( struct.unpack(fmt_header, header1)) if self.Sig != MAGIC: # OLE signature should always be present self._raise_defect(DEFECT_FATAL, "incorrect OLE signature") if self.clsid != bytearray(16): # according to AAF specs, CLSID should always be zero self._raise_defect(DEFECT_INCORRECT, "incorrect CLSID in OLE header") debug( "MinorVersion = %d" % self.MinorVersion ) debug( "DllVersion = %d" % self.DllVersion ) if self.DllVersion not in [3, 4]: # version 3: usual format, 512 bytes per sector # version 4: large format, 4K per sector self._raise_defect(DEFECT_INCORRECT, "incorrect DllVersion in OLE header") debug( "ByteOrder = %X" % self.ByteOrder ) if self.ByteOrder != 0xFFFE: # For now only common little-endian documents are handled correctly self._raise_defect(DEFECT_FATAL, "incorrect ByteOrder in OLE header") # TODO: add big-endian support for documents created on Mac ? self.SectorSize = 2**self.SectorShift debug( "SectorSize = %d" % self.SectorSize ) if self.SectorSize not in [512, 4096]: self._raise_defect(DEFECT_INCORRECT, "incorrect SectorSize in OLE header") if (self.DllVersion==3 and self.SectorSize!=512) \ or (self.DllVersion==4 and self.SectorSize!=4096): self._raise_defect(DEFECT_INCORRECT, "SectorSize does not match DllVersion in OLE header") self.MiniSectorSize = 2**self.MiniSectorShift debug( "MiniSectorSize = %d" % self.MiniSectorSize ) if self.MiniSectorSize not in [64]: self._raise_defect(DEFECT_INCORRECT, "incorrect MiniSectorSize in OLE header") if self.Reserved != 0 or self.Reserved1 != 0: self._raise_defect(DEFECT_INCORRECT, "incorrect OLE header (non-null reserved bytes)") debug( "csectDir = %d" % self.csectDir ) if self.SectorSize==512 and self.csectDir!=0: self._raise_defect(DEFECT_INCORRECT, "incorrect csectDir in OLE header") debug( "csectFat = %d" % self.csectFat ) debug( "sectDirStart = %X" % self.sectDirStart ) debug( "signature = %d" % self.signature ) # Signature should be zero, BUT some implementations do not follow this # rule => only a potential defect: if self.signature != 0: self._raise_defect(DEFECT_POTENTIAL, "incorrect OLE header (signature>0)") debug( "MiniSectorCutoff = %d" % self.MiniSectorCutoff ) debug( "MiniFatStart = %X" % self.MiniFatStart ) debug( "csectMiniFat = %d" % self.csectMiniFat ) debug( "sectDifStart = %X" % self.sectDifStart ) debug( "csectDif = %d" % self.csectDif ) # calculate the number of sectors in the file # (-1 because header doesn't count) self.nb_sect = ( (filesize + self.SectorSize-1) // self.SectorSize) - 1 debug( "Number of sectors in the file: %d" % self.nb_sect ) # file clsid (probably never used, so we don't store it) #clsid = _clsid(header[8:24]) self.sectorsize = self.SectorSize #1 << i16(header, 30) self.minisectorsize = self.MiniSectorSize #1 << i16(header, 32) self.minisectorcutoff = self.MiniSectorCutoff # i32(header, 56) # check known streams for duplicate references (these are always in FAT, # never in MiniFAT): self._check_duplicate_stream(self.sectDirStart) # check MiniFAT only if it is not empty: if self.csectMiniFat: self._check_duplicate_stream(self.MiniFatStart) # check DIFAT only if it is not empty: if self.csectDif: self._check_duplicate_stream(self.sectDifStart) # Load file allocation tables self.loadfat(header) # Load direcory. This sets both the direntries list (ordered by sid) # and the root (ordered by hierarchy) members. self.loaddirectory(self.sectDirStart)#i32(header, 48)) self.ministream = None self.minifatsect = self.MiniFatStart #i32(header, 60) def close(self): """ close the OLE file, to release the file object """ self.fp.close() def _check_duplicate_stream(self, first_sect, minifat=False): """ Checks if a stream has not been already referenced elsewhere. This method should only be called once for each known stream, and only if stream size is not null. :param first_sect: index of first sector of the stream in FAT :param minifat: if True, stream is located in the MiniFAT, else in the FAT """ if minifat: debug('_check_duplicate_stream: sect=%d in MiniFAT' % first_sect) used_streams = self._used_streams_minifat else: debug('_check_duplicate_stream: sect=%d in FAT' % first_sect) # some values can be safely ignored (not a real stream): if first_sect in (DIFSECT,FATSECT,ENDOFCHAIN,FREESECT): return used_streams = self._used_streams_fat #TODO: would it be more efficient using a dict or hash values, instead # of a list of long ? if first_sect in used_streams: self._raise_defect(DEFECT_INCORRECT, 'Stream referenced twice') else: used_streams.append(first_sect) def dumpfat(self, fat, firstindex=0): "Displays a part of FAT in human-readable form for debugging purpose" # [PL] added only for debug if not DEBUG_MODE: return # dictionary to convert special FAT values in human-readable strings VPL=8 # valeurs par ligne (8+1 * 8+1 = 81) fatnames = { FREESECT: "..free..", ENDOFCHAIN: "[ END. ]", FATSECT: "FATSECT ", DIFSECT: "DIFSECT " } nbsect = len(fat) nlines = (nbsect+VPL-1)//VPL print("index", end=" ") for i in range(VPL): print("%8X" % i, end=" ") print() for l in range(nlines): index = l*VPL print("%8X:" % (firstindex+index), end=" ") for i in range(index, index+VPL): if i>=nbsect: break sect = fat[i] if sect in fatnames: nom = fatnames[sect] else: if sect == i+1: nom = " --->" else: nom = "%8X" % sect print(nom, end=" ") print() def dumpsect(self, sector, firstindex=0): "Displays a sector in a human-readable form, for debugging purpose." if not DEBUG_MODE: return VPL=8 # number of values per line (8+1 * 8+1 = 81) tab = array.array(UINT32, sector) nbsect = len(tab) nlines = (nbsect+VPL-1)//VPL print("index", end=" ") for i in range(VPL): print("%8X" % i, end=" ") print() for l in range(nlines): index = l*VPL print("%8X:" % (firstindex+index), end=" ") for i in range(index, index+VPL): if i>=nbsect: break sect = tab[i] nom = "%8X" % sect print(nom, end=" ") print() def sect2array(self, sect): """ convert a sector to an array of 32 bits unsigned integers, swapping bytes on big endian CPUs such as PowerPC (old Macs) """ a = array.array(UINT32, sect) # if CPU is big endian, swap bytes: if sys.byteorder == 'big': a.byteswap() return a def loadfat_sect(self, sect): """ Adds the indexes of the given sector to the FAT :param sect: string containing the first FAT sector, or array of long integers :returns: index of last FAT sector. """ # a FAT sector is an array of ulong integers. if isinstance(sect, array.array): # if sect is already an array it is directly used fat1 = sect else: # if it's a raw sector, it is parsed in an array fat1 = self.sect2array(sect) self.dumpsect(sect) # The FAT is a sector chain starting at the first index of itself. for isect in fat1: #print("isect = %X" % isect) if isect == ENDOFCHAIN or isect == FREESECT: # the end of the sector chain has been reached break # read the FAT sector s = self.getsect(isect) # parse it as an array of 32 bits integers, and add it to the # global FAT array nextfat = self.sect2array(s) self.fat = self.fat + nextfat return isect def loadfat(self, header): """ Load the FAT table. """ # The header contains a sector numbers # for the first 109 FAT sectors. Additional sectors are # described by DIF blocks sect = header[76:512] debug( "len(sect)=%d, so %d integers" % (len(sect), len(sect)//4) ) #fat = [] # [PL] FAT is an array of 32 bits unsigned ints, it's more effective # to use an array than a list in Python. # It's initialized as empty first: self.fat = array.array(UINT32) self.loadfat_sect(sect) #self.dumpfat(self.fat) ## for i in range(0, len(sect), 4): ## ix = i32(sect, i) ## #[PL] if ix == -2 or ix == -1: # ix == 0xFFFFFFFE or ix == 0xFFFFFFFF: ## if ix == 0xFFFFFFFE or ix == 0xFFFFFFFF: ## break ## s = self.getsect(ix) ## #fat = fat + [i32(s, i) for i in range(0, len(s), 4)] ## fat = fat + array.array(UINT32, s) if self.csectDif != 0: # [PL] There's a DIFAT because file is larger than 6.8MB # some checks just in case: if self.csectFat <= 109: # there must be at least 109 blocks in header and the rest in # DIFAT, so number of sectors must be >109. self._raise_defect(DEFECT_INCORRECT, 'incorrect DIFAT, not enough sectors') if self.sectDifStart >= self.nb_sect: # initial DIFAT block index must be valid self._raise_defect(DEFECT_FATAL, 'incorrect DIFAT, first index out of range') debug( "DIFAT analysis..." ) # We compute the necessary number of DIFAT sectors : # (each DIFAT sector = 127 pointers + 1 towards next DIFAT sector) nb_difat = (self.csectFat-109 + 126)//127 debug( "nb_difat = %d" % nb_difat ) if self.csectDif != nb_difat: raise IOError('incorrect DIFAT') isect_difat = self.sectDifStart for i in iterrange(nb_difat): debug( "DIFAT block %d, sector %X" % (i, isect_difat) ) #TODO: check if corresponding FAT SID = DIFSECT sector_difat = self.getsect(isect_difat) difat = self.sect2array(sector_difat) self.dumpsect(sector_difat) self.loadfat_sect(difat[:127]) # last DIFAT pointer is next DIFAT sector: isect_difat = difat[127] debug( "next DIFAT sector: %X" % isect_difat ) # checks: if isect_difat not in [ENDOFCHAIN, FREESECT]: # last DIFAT pointer value must be ENDOFCHAIN or FREESECT raise IOError('incorrect end of DIFAT') ## if len(self.fat) != self.csectFat: ## # FAT should contain csectFat blocks ## print("FAT length: %d instead of %d" % (len(self.fat), self.csectFat)) ## raise IOError('incorrect DIFAT') # since FAT is read from fixed-size sectors, it may contain more values # than the actual number of sectors in the file. # Keep only the relevant sector indexes: if len(self.fat) > self.nb_sect: debug('len(fat)=%d, shrunk to nb_sect=%d' % (len(self.fat), self.nb_sect)) self.fat = self.fat[:self.nb_sect] debug('\nFAT:') self.dumpfat(self.fat) def loadminifat(self): """ Load the MiniFAT table. """ # MiniFAT is stored in a standard sub-stream, pointed to by a header # field. # NOTE: there are two sizes to take into account for this stream: # 1) Stream size is calculated according to the number of sectors # declared in the OLE header. This allocated stream may be more than # needed to store the actual sector indexes. # (self.csectMiniFat is the number of sectors of size self.SectorSize) stream_size = self.csectMiniFat * self.SectorSize # 2) Actually used size is calculated by dividing the MiniStream size # (given by root entry size) by the size of mini sectors, *4 for # 32 bits indexes: nb_minisectors = (self.root.size + self.MiniSectorSize-1) // self.MiniSectorSize used_size = nb_minisectors * 4 debug('loadminifat(): minifatsect=%d, nb FAT sectors=%d, used_size=%d, stream_size=%d, nb MiniSectors=%d' % (self.minifatsect, self.csectMiniFat, used_size, stream_size, nb_minisectors)) if used_size > stream_size: # This is not really a problem, but may indicate a wrong implementation: self._raise_defect(DEFECT_INCORRECT, 'OLE MiniStream is larger than MiniFAT') # In any case, first read stream_size: s = self._open(self.minifatsect, stream_size, force_FAT=True).read() #[PL] Old code replaced by an array: #self.minifat = [i32(s, i) for i in range(0, len(s), 4)] self.minifat = self.sect2array(s) # Then shrink the array to used size, to avoid indexes out of MiniStream: debug('MiniFAT shrunk from %d to %d sectors' % (len(self.minifat), nb_minisectors)) self.minifat = self.minifat[:nb_minisectors] debug('loadminifat(): len=%d' % len(self.minifat)) debug('\nMiniFAT:') self.dumpfat(self.minifat) def getsect(self, sect): """ Read given sector from file on disk. :param sect: sector index :returns: a string containing the sector data. """ # [PL] this original code was wrong when sectors are 4KB instead of # 512 bytes: #self.fp.seek(512 + self.sectorsize * sect) #[PL]: added safety checks: #print("getsect(%X)" % sect) try: self.fp.seek(self.sectorsize * (sect+1)) except: debug('getsect(): sect=%X, seek=%d, filesize=%d' % (sect, self.sectorsize*(sect+1), self._filesize)) self._raise_defect(DEFECT_FATAL, 'OLE sector index out of range') sector = self.fp.read(self.sectorsize) if len(sector) != self.sectorsize: debug('getsect(): sect=%X, read=%d, sectorsize=%d' % (sect, len(sector), self.sectorsize)) self._raise_defect(DEFECT_FATAL, 'incomplete OLE sector') return sector def loaddirectory(self, sect): """ Load the directory. :param sect: sector index of directory stream. """ # The directory is stored in a standard # substream, independent of its size. # open directory stream as a read-only file: # (stream size is not known in advance) self.directory_fp = self._open(sect) #[PL] to detect malformed documents and avoid DoS attacks, the maximum # number of directory entries can be calculated: max_entries = self.directory_fp.size // 128 debug('loaddirectory: size=%d, max_entries=%d' % (self.directory_fp.size, max_entries)) # Create list of directory entries #self.direntries = [] # We start with a list of "None" object self.direntries = [None] * max_entries ## for sid in iterrange(max_entries): ## entry = fp.read(128) ## if not entry: ## break ## self.direntries.append(_OleDirectoryEntry(entry, sid, self)) # load root entry: self._load_direntry(0) # Root entry is the first entry: self.root = self.direntries[0] # read and build all storage trees, starting from the root: self.root.build_storage_tree() def _load_direntry (self, sid): """ Load a directory entry from the directory. This method should only be called once for each storage/stream when loading the directory. :param sid: index of storage/stream in the directory. :returns: a _OleDirectoryEntry object :exception IOError: if the entry has always been referenced. """ # check if SID is OK: if sid<0 or sid>=len(self.direntries): self._raise_defect(DEFECT_FATAL, "OLE directory index out of range") # check if entry was already referenced: if self.direntries[sid] is not None: self._raise_defect(DEFECT_INCORRECT, "double reference for OLE stream/storage") # if exception not raised, return the object return self.direntries[sid] self.directory_fp.seek(sid * 128) entry = self.directory_fp.read(128) self.direntries[sid] = _OleDirectoryEntry(entry, sid, self) return self.direntries[sid] def dumpdirectory(self): """ Dump directory (for debugging only) """ self.root.dump() def _open(self, start, size = 0x7FFFFFFF, force_FAT=False): """ Open a stream, either in FAT or MiniFAT according to its size. (openstream helper) :param start: index of first sector :param size: size of stream (or nothing if size is unknown) :param force_FAT: if False (default), stream will be opened in FAT or MiniFAT according to size. If True, it will always be opened in FAT. """ debug('OleFileIO.open(): sect=%d, size=%d, force_FAT=%s' % (start, size, str(force_FAT))) # stream size is compared to the MiniSectorCutoff threshold: if size < self.minisectorcutoff and not force_FAT: # ministream object if not self.ministream: # load MiniFAT if it wasn't already done: self.loadminifat() # The first sector index of the miniFAT stream is stored in the # root directory entry: size_ministream = self.root.size debug('Opening MiniStream: sect=%d, size=%d' % (self.root.isectStart, size_ministream)) self.ministream = self._open(self.root.isectStart, size_ministream, force_FAT=True) return _OleStream(self.ministream, start, size, 0, self.minisectorsize, self.minifat, self.ministream.size) else: # standard stream return _OleStream(self.fp, start, size, 512, self.sectorsize, self.fat, self._filesize) def _list(self, files, prefix, node, streams=True, storages=False): """ (listdir helper) :param files: list of files to fill in :param prefix: current location in storage tree (list of names) :param node: current node (_OleDirectoryEntry object) :param streams: bool, include streams if True (True by default) - new in v0.26 :param storages: bool, include storages if True (False by default) - new in v0.26 (note: the root storage is never included) """ prefix = prefix + [node.name] for entry in node.kids: if entry.kids: # this is a storage if storages: # add it to the list files.append(prefix[1:] + [entry.name]) # check its kids self._list(files, prefix, entry, streams, storages) else: # this is a stream if streams: # add it to the list files.append(prefix[1:] + [entry.name]) def listdir(self, streams=True, storages=False): """ Return a list of streams stored in this file :param streams: bool, include streams if True (True by default) - new in v0.26 :param storages: bool, include storages if True (False by default) - new in v0.26 (note: the root storage is never included) """ files = [] self._list(files, [], self.root, streams, storages) return files def _find(self, filename): """ Returns directory entry of given filename. (openstream helper) Note: this method is case-insensitive. :param filename: path of stream in storage tree (except root entry), either: - a string using Unix path syntax, for example: 'storage_1/storage_1.2/stream' - a list of storage filenames, path to the desired stream/storage. Example: ['storage_1', 'storage_1.2', 'stream'] :returns: sid of requested filename raise IOError if file not found """ # if filename is a string instead of a list, split it on slashes to # convert to a list: if isinstance(filename, basestring): filename = filename.split('/') # walk across storage tree, following given path: node = self.root for name in filename: for kid in node.kids: if kid.name.lower() == name.lower(): break else: raise IOError("file not found") node = kid return node.sid def openstream(self, filename): """ Open a stream as a read-only file object (BytesIO). :param filename: path of stream in storage tree (except root entry), either: - a string using Unix path syntax, for example: 'storage_1/storage_1.2/stream' - a list of storage filenames, path to the desired stream/storage. Example: ['storage_1', 'storage_1.2', 'stream'] :returns: file object (read-only) :exception IOError: if filename not found, or if this is not a stream. """ sid = self._find(filename) entry = self.direntries[sid] if entry.entry_type != STGTY_STREAM: raise IOError("this file is not a stream") return self._open(entry.isectStart, entry.size) def get_type(self, filename): """ Test if given filename exists as a stream or a storage in the OLE container, and return its type. :param filename: path of stream in storage tree. (see openstream for syntax) :returns: False if object does not exist, its entry type (>0) otherwise: - STGTY_STREAM: a stream - STGTY_STORAGE: a storage - STGTY_ROOT: the root entry """ try: sid = self._find(filename) entry = self.direntries[sid] return entry.entry_type except: return False def getmtime(self, filename): """ Return modification time of a stream/storage. :param filename: path of stream/storage in storage tree. (see openstream for syntax) :returns: None if modification time is null, a python datetime object otherwise (UTC timezone) new in version 0.26 """ sid = self._find(filename) entry = self.direntries[sid] return entry.getmtime() def getctime(self, filename): """ Return creation time of a stream/storage. :param filename: path of stream/storage in storage tree. (see openstream for syntax) :returns: None if creation time is null, a python datetime object otherwise (UTC timezone) new in version 0.26 """ sid = self._find(filename) entry = self.direntries[sid] return entry.getctime() def exists(self, filename): """ Test if given filename exists as a stream or a storage in the OLE container. :param filename: path of stream in storage tree. (see openstream for syntax) :returns: True if object exist, else False. """ try: self._find(filename) return True except: return False def get_size(self, filename): """ Return size of a stream in the OLE container, in bytes. :param filename: path of stream in storage tree (see openstream for syntax) :returns: size in bytes (long integer) :exception IOError: if file not found :exception TypeError: if this is not a stream """ sid = self._find(filename) entry = self.direntries[sid] if entry.entry_type != STGTY_STREAM: #TODO: Should it return zero instead of raising an exception ? raise TypeError('object is not an OLE stream') return entry.size def get_rootentry_name(self): """ Return root entry name. Should usually be 'Root Entry' or 'R' in most implementations. """ return self.root.name def getproperties(self, filename, convert_time=False, no_conversion=None): """ Return properties described in substream. :param filename: path of stream in storage tree (see openstream for syntax) :param convert_time: bool, if True timestamps will be converted to Python datetime :param no_conversion: None or list of int, timestamps not to be converted (for example total editing time is not a real timestamp) :returns: a dictionary of values indexed by id (integer) """ # make sure no_conversion is a list, just to simplify code below: if no_conversion == None: no_conversion = [] # stream path as a string to report exceptions: streampath = filename if not isinstance(streampath, str): streampath = '/'.join(streampath) fp = self.openstream(filename) data = {} try: # header s = fp.read(28) #clsid = _clsid(s[8:24]) # format id s = fp.read(20) #fmtid = _clsid(s[:16]) fp.seek(i32(s, 16)) # get section s = b"****" + fp.read(i32(fp.read(4))-4) # number of properties: num_props = i32(s, 4) except BaseException as exc: # catch exception while parsing property header, and only raise # a DEFECT_INCORRECT then return an empty dict, because this is not # a fatal error when parsing the whole file msg = 'Error while parsing properties header in stream %s: %s' % ( repr(streampath), exc) self._raise_defect(DEFECT_INCORRECT, msg, type(exc)) return data for i in range(num_props): try: id = 0 # just in case of an exception id = i32(s, 8+i*8) offset = i32(s, 12+i*8) type = i32(s, offset) debug ('property id=%d: type=%d offset=%X' % (id, type, offset)) # test for common types first (should perhaps use # a dictionary instead?) if type == VT_I2: # 16-bit signed integer value = i16(s, offset+4) if value >= 32768: value = value - 65536 elif type == VT_UI2: # 2-byte unsigned integer value = i16(s, offset+4) elif type in (VT_I4, VT_INT, VT_ERROR): # VT_I4: 32-bit signed integer # VT_ERROR: HRESULT, similar to 32-bit signed integer, # see http://msdn.microsoft.com/en-us/library/cc230330.aspx value = i32(s, offset+4) elif type in (VT_UI4, VT_UINT): # 4-byte unsigned integer value = i32(s, offset+4) # FIXME elif type in (VT_BSTR, VT_LPSTR): # CodePageString, see http://msdn.microsoft.com/en-us/library/dd942354.aspx # size is a 32 bits integer, including the null terminator, and # possibly trailing or embedded null chars #TODO: if codepage is unicode, the string should be converted as such count = i32(s, offset+4) value = s[offset+8:offset+8+count-1] # remove all null chars: value = value.replace(b'\x00', b'') elif type == VT_BLOB: # binary large object (BLOB) # see http://msdn.microsoft.com/en-us/library/dd942282.aspx count = i32(s, offset+4) value = s[offset+8:offset+8+count] elif type == VT_LPWSTR: # UnicodeString # see http://msdn.microsoft.com/en-us/library/dd942313.aspx # "the string should NOT contain embedded or additional trailing # null characters." count = i32(s, offset+4) value = _unicode(s[offset+8:offset+8+count*2]) elif type == VT_FILETIME: value = long(i32(s, offset+4)) + (long(i32(s, offset+8))<<32) # FILETIME is a 64-bit int: "number of 100ns periods # since Jan 1,1601". if convert_time and id not in no_conversion: debug('Converting property #%d to python datetime, value=%d=%fs' %(id, value, float(value)/10000000)) # convert FILETIME to Python datetime.datetime # inspired from http://code.activestate.com/recipes/511425-filetime-to-datetime/ _FILETIME_null_date = datetime.datetime(1601, 1, 1, 0, 0, 0) debug('timedelta days=%d' % (value//(10*1000000*3600*24))) value = _FILETIME_null_date + datetime.timedelta(microseconds=value//10) else: # legacy code kept for backward compatibility: returns a # number of seconds since Jan 1,1601 value = value // 10000000 # seconds elif type == VT_UI1: # 1-byte unsigned integer value = i8(s[offset+4]) elif type == VT_CLSID: value = _clsid(s[offset+4:offset+20]) elif type == VT_CF: # PropertyIdentifier or ClipboardData?? # see http://msdn.microsoft.com/en-us/library/dd941945.aspx count = i32(s, offset+4) value = s[offset+8:offset+8+count] elif type == VT_BOOL: # VARIANT_BOOL, 16 bits bool, 0x0000=Fals, 0xFFFF=True # see http://msdn.microsoft.com/en-us/library/cc237864.aspx value = bool(i16(s, offset+4)) else: value = None # everything else yields "None" debug ('property id=%d: type=%d not implemented in parser yet' % (id, type)) # missing: VT_EMPTY, VT_NULL, VT_R4, VT_R8, VT_CY, VT_DATE, # VT_DECIMAL, VT_I1, VT_I8, VT_UI8, # see http://msdn.microsoft.com/en-us/library/dd942033.aspx # FIXME: add support for VT_VECTOR # VT_VECTOR is a 32 uint giving the number of items, followed by # the items in sequence. The VT_VECTOR value is combined with the # type of items, e.g. VT_VECTOR|VT_BSTR # see http://msdn.microsoft.com/en-us/library/dd942011.aspx #print("%08x" % id, repr(value), end=" ") #print("(%s)" % VT[i32(s, offset) & 0xFFF]) data[id] = value except BaseException as exc: # catch exception while parsing each property, and only raise # a DEFECT_INCORRECT, because parsing can go on msg = 'Error while parsing property id %d in stream %s: %s' % ( id, repr(streampath), exc) self._raise_defect(DEFECT_INCORRECT, msg, type(exc)) return data def get_metadata(self): """ Parse standard properties streams, return an OleMetadata object containing all the available metadata. (also stored in the metadata attribute of the OleFileIO object) new in version 0.25 """ self.metadata = OleMetadata() self.metadata.parse_properties(self) return self.metadata # # -------------------------------------------------------------------- # This script can be used to dump the directory of any OLE2 structured # storage file. if __name__ == "__main__": # [PL] display quick usage info if launched from command-line if len(sys.argv) <= 1: print(__doc__) print(""" Launched from command line, this script parses OLE files and prints info. Usage: OleFileIO_PL.py [-d] [-c] <file> [file2 ...] Options: -d : debug mode (display a lot of debug information, for developers only) -c : check all streams (for debugging purposes) """) sys.exit() check_streams = False for filename in sys.argv[1:]: #try: # OPTIONS: if filename == '-d': # option to switch debug mode on: set_debug_mode(True) continue if filename == '-c': # option to switch check streams mode on: check_streams = True continue ole = OleFileIO(filename)#, raise_defects=DEFECT_INCORRECT) print("-" * 68) print(filename) print("-" * 68) ole.dumpdirectory() for streamname in ole.listdir(): if streamname[-1][0] == "\005": print(streamname, ": properties") props = ole.getproperties(streamname, convert_time=True) props = sorted(props.items()) for k, v in props: #[PL]: avoid to display too large or binary values: if isinstance(v, (basestring, bytes)): if len(v) > 50: v = v[:50] if isinstance(v, bytes): # quick and dirty binary check: for c in (1,2,3,4,5,6,7,11,12,14,15,16,17,18,19,20, 21,22,23,24,25,26,27,28,29,30,31): if c in bytearray(v): v = '(binary data)' break print(" ", k, v) if check_streams: # Read all streams to check if there are errors: print('\nChecking streams...') for streamname in ole.listdir(): # print name using repr() to convert binary chars to \xNN: print('-', repr('/'.join(streamname)),'-', end=' ') st_type = ole.get_type(streamname) if st_type == STGTY_STREAM: print('size %d' % ole.get_size(streamname)) # just try to read stream in memory: ole.openstream(streamname) else: print('NOT a stream : type=%d' % st_type) print() ## for streamname in ole.listdir(): ## # print name using repr() to convert binary chars to \xNN: ## print('-', repr('/'.join(streamname)),'-', end=' ') ## print(ole.getmtime(streamname)) ## print() print('Modification/Creation times of all directory entries:') for entry in ole.direntries: if entry is not None: print('- %s: mtime=%s ctime=%s' % (entry.name, entry.getmtime(), entry.getctime())) print() # parse and display metadata: meta = ole.get_metadata() meta.dump() print() #[PL] Test a few new methods: root = ole.get_rootentry_name() print('Root entry name: "%s"' % root) if ole.exists('worddocument'): print("This is a Word document.") print("type of stream 'WordDocument':", ole.get_type('worddocument')) print("size :", ole.get_size('worddocument')) if ole.exists('macros/vba'): print("This document may contain VBA macros.") # print parsing issues: print('\nNon-fatal issues raised during parsing:') if ole.parsing_issues: for exctype, msg in ole.parsing_issues: print('- %s: %s' % (exctype.__name__, msg)) else: print('None') ## except IOError as v: ## print("***", "cannot read", file, "-", v)
lgpl-3.0
cbeloni/pychronesapp
backend/venv/lib/python2.7/site-packages/babel/messages/extract.py
151
22695
# -*- coding: utf-8 -*- """ babel.messages.extract ~~~~~~~~~~~~~~~~~~~~~~ Basic infrastructure for extracting localizable messages from source files. This module defines an extensible system for collecting localizable message strings from a variety of sources. A native extractor for Python source files is builtin, extractors for other sources can be added using very simple plugins. The main entry points into the extraction functionality are the functions `extract_from_dir` and `extract_from_file`. :copyright: (c) 2013 by the Babel Team. :license: BSD, see LICENSE for more details. """ import os import sys from tokenize import generate_tokens, COMMENT, NAME, OP, STRING from babel.util import parse_encoding, pathmatch, relpath from babel._compat import PY2, text_type from textwrap import dedent GROUP_NAME = 'babel.extractors' DEFAULT_KEYWORDS = { '_': None, 'gettext': None, 'ngettext': (1, 2), 'ugettext': None, 'ungettext': (1, 2), 'dgettext': (2,), 'dngettext': (2, 3), 'N_': None, 'pgettext': ((1, 'c'), 2) } DEFAULT_MAPPING = [('**.py', 'python')] empty_msgid_warning = ( '%s: warning: Empty msgid. It is reserved by GNU gettext: gettext("") ' 'returns the header entry with meta information, not the empty string.') def _strip_comment_tags(comments, tags): """Helper function for `extract` that strips comment tags from strings in a list of comment lines. This functions operates in-place. """ def _strip(line): for tag in tags: if line.startswith(tag): return line[len(tag):].strip() return line comments[:] = map(_strip, comments) def extract_from_dir(dirname=None, method_map=DEFAULT_MAPPING, options_map=None, keywords=DEFAULT_KEYWORDS, comment_tags=(), callback=None, strip_comment_tags=False): """Extract messages from any source files found in the given directory. This function generates tuples of the form ``(filename, lineno, message, comments, context)``. Which extraction method is used per file is determined by the `method_map` parameter, which maps extended glob patterns to extraction method names. For example, the following is the default mapping: >>> method_map = [ ... ('**.py', 'python') ... ] This basically says that files with the filename extension ".py" at any level inside the directory should be processed by the "python" extraction method. Files that don't match any of the mapping patterns are ignored. See the documentation of the `pathmatch` function for details on the pattern syntax. The following extended mapping would also use the "genshi" extraction method on any file in "templates" subdirectory: >>> method_map = [ ... ('**/templates/**.*', 'genshi'), ... ('**.py', 'python') ... ] The dictionary provided by the optional `options_map` parameter augments these mappings. It uses extended glob patterns as keys, and the values are dictionaries mapping options names to option values (both strings). The glob patterns of the `options_map` do not necessarily need to be the same as those used in the method mapping. For example, while all files in the ``templates`` folders in an application may be Genshi applications, the options for those files may differ based on extension: >>> options_map = { ... '**/templates/**.txt': { ... 'template_class': 'genshi.template:TextTemplate', ... 'encoding': 'latin-1' ... }, ... '**/templates/**.html': { ... 'include_attrs': '' ... } ... } :param dirname: the path to the directory to extract messages from. If not given the current working directory is used. :param method_map: a list of ``(pattern, method)`` tuples that maps of extraction method names to extended glob patterns :param options_map: a dictionary of additional options (optional) :param keywords: a dictionary mapping keywords (i.e. names of functions that should be recognized as translation functions) to tuples that specify which of their arguments contain localizable strings :param comment_tags: a list of tags of translator comments to search for and include in the results :param callback: a function that is called for every file that message are extracted from, just before the extraction itself is performed; the function is passed the filename, the name of the extraction method and and the options dictionary as positional arguments, in that order :param strip_comment_tags: a flag that if set to `True` causes all comment tags to be removed from the collected comments. :see: `pathmatch` """ if dirname is None: dirname = os.getcwd() if options_map is None: options_map = {} absname = os.path.abspath(dirname) for root, dirnames, filenames in os.walk(absname): for subdir in dirnames: if subdir.startswith('.') or subdir.startswith('_'): dirnames.remove(subdir) dirnames.sort() filenames.sort() for filename in filenames: filename = relpath( os.path.join(root, filename).replace(os.sep, '/'), dirname ) for pattern, method in method_map: if pathmatch(pattern, filename): filepath = os.path.join(absname, filename) options = {} for opattern, odict in options_map.items(): if pathmatch(opattern, filename): options = odict if callback: callback(filename, method, options) for lineno, message, comments, context in \ extract_from_file(method, filepath, keywords=keywords, comment_tags=comment_tags, options=options, strip_comment_tags= strip_comment_tags): yield filename, lineno, message, comments, context break def extract_from_file(method, filename, keywords=DEFAULT_KEYWORDS, comment_tags=(), options=None, strip_comment_tags=False): """Extract messages from a specific file. This function returns a list of tuples of the form ``(lineno, funcname, message)``. :param filename: the path to the file to extract messages from :param method: a string specifying the extraction method (.e.g. "python") :param keywords: a dictionary mapping keywords (i.e. names of functions that should be recognized as translation functions) to tuples that specify which of their arguments contain localizable strings :param comment_tags: a list of translator tags to search for and include in the results :param strip_comment_tags: a flag that if set to `True` causes all comment tags to be removed from the collected comments. :param options: a dictionary of additional options (optional) """ fileobj = open(filename, 'rb') try: return list(extract(method, fileobj, keywords, comment_tags, options, strip_comment_tags)) finally: fileobj.close() def extract(method, fileobj, keywords=DEFAULT_KEYWORDS, comment_tags=(), options=None, strip_comment_tags=False): """Extract messages from the given file-like object using the specified extraction method. This function returns tuples of the form ``(lineno, message, comments)``. The implementation dispatches the actual extraction to plugins, based on the value of the ``method`` parameter. >>> source = '''# foo module ... def run(argv): ... print _('Hello, world!') ... ''' >>> from StringIO import StringIO >>> for message in extract('python', StringIO(source)): ... print message (3, u'Hello, world!', [], None) :param method: a string specifying the extraction method (.e.g. "python"); if this is a simple name, the extraction function will be looked up by entry point; if it is an explicit reference to a function (of the form ``package.module:funcname`` or ``package.module.funcname``), the corresponding function will be imported and used :param fileobj: the file-like object the messages should be extracted from :param keywords: a dictionary mapping keywords (i.e. names of functions that should be recognized as translation functions) to tuples that specify which of their arguments contain localizable strings :param comment_tags: a list of translator tags to search for and include in the results :param options: a dictionary of additional options (optional) :param strip_comment_tags: a flag that if set to `True` causes all comment tags to be removed from the collected comments. :raise ValueError: if the extraction method is not registered """ func = None if ':' in method or '.' in method: if ':' not in method: lastdot = method.rfind('.') module, attrname = method[:lastdot], method[lastdot + 1:] else: module, attrname = method.split(':', 1) func = getattr(__import__(module, {}, {}, [attrname]), attrname) else: try: from pkg_resources import working_set except ImportError: pass else: for entry_point in working_set.iter_entry_points(GROUP_NAME, method): func = entry_point.load(require=True) break if func is None: # if pkg_resources is not available or no usable egg-info was found # (see #230), we resort to looking up the builtin extractors # directly builtin = { 'ignore': extract_nothing, 'python': extract_python, 'javascript': extract_javascript } func = builtin.get(method) if func is None: raise ValueError('Unknown extraction method %r' % method) results = func(fileobj, keywords.keys(), comment_tags, options=options or {}) for lineno, funcname, messages, comments in results: if funcname: spec = keywords[funcname] or (1,) else: spec = (1,) if not isinstance(messages, (list, tuple)): messages = [messages] if not messages: continue # Validate the messages against the keyword's specification context = None msgs = [] invalid = False # last_index is 1 based like the keyword spec last_index = len(messages) for index in spec: if isinstance(index, tuple): context = messages[index[0] - 1] continue if last_index < index: # Not enough arguments invalid = True break message = messages[index - 1] if message is None: invalid = True break msgs.append(message) if invalid: continue # keyword spec indexes are 1 based, therefore '-1' if isinstance(spec[0], tuple): # context-aware *gettext method first_msg_index = spec[1] - 1 else: first_msg_index = spec[0] - 1 if not messages[first_msg_index]: # An empty string msgid isn't valid, emit a warning where = '%s:%i' % (hasattr(fileobj, 'name') and \ fileobj.name or '(unknown)', lineno) sys.stderr.write((empty_msgid_warning % where) + '\n') continue messages = tuple(msgs) if len(messages) == 1: messages = messages[0] if strip_comment_tags: _strip_comment_tags(comments, comment_tags) yield lineno, messages, comments, context def extract_nothing(fileobj, keywords, comment_tags, options): """Pseudo extractor that does not actually extract anything, but simply returns an empty list. """ return [] def extract_python(fileobj, keywords, comment_tags, options): """Extract messages from Python source code. It returns an iterator yielding tuples in the following form ``(lineno, funcname, message, comments)``. :param fileobj: the seekable, file-like object the messages should be extracted from :param keywords: a list of keywords (i.e. function names) that should be recognized as translation functions :param comment_tags: a list of translator tags to search for and include in the results :param options: a dictionary of additional options (optional) :rtype: ``iterator`` """ funcname = lineno = message_lineno = None call_stack = -1 buf = [] messages = [] translator_comments = [] in_def = in_translator_comments = False comment_tag = None encoding = parse_encoding(fileobj) or options.get('encoding', 'iso-8859-1') if PY2: next_line = fileobj.readline else: next_line = lambda: fileobj.readline().decode(encoding) tokens = generate_tokens(next_line) for tok, value, (lineno, _), _, _ in tokens: if call_stack == -1 and tok == NAME and value in ('def', 'class'): in_def = True elif tok == OP and value == '(': if in_def: # Avoid false positives for declarations such as: # def gettext(arg='message'): in_def = False continue if funcname: message_lineno = lineno call_stack += 1 elif in_def and tok == OP and value == ':': # End of a class definition without parens in_def = False continue elif call_stack == -1 and tok == COMMENT: # Strip the comment token from the line if PY2: value = value.decode(encoding) value = value[1:].strip() if in_translator_comments and \ translator_comments[-1][0] == lineno - 1: # We're already inside a translator comment, continue appending translator_comments.append((lineno, value)) continue # If execution reaches this point, let's see if comment line # starts with one of the comment tags for comment_tag in comment_tags: if value.startswith(comment_tag): in_translator_comments = True translator_comments.append((lineno, value)) break elif funcname and call_stack == 0: if tok == OP and value == ')': if buf: messages.append(''.join(buf)) del buf[:] else: messages.append(None) if len(messages) > 1: messages = tuple(messages) else: messages = messages[0] # Comments don't apply unless they immediately preceed the # message if translator_comments and \ translator_comments[-1][0] < message_lineno - 1: translator_comments = [] yield (message_lineno, funcname, messages, [comment[1] for comment in translator_comments]) funcname = lineno = message_lineno = None call_stack = -1 messages = [] translator_comments = [] in_translator_comments = False elif tok == STRING: # Unwrap quotes in a safe manner, maintaining the string's # encoding # https://sourceforge.net/tracker/?func=detail&atid=355470& # aid=617979&group_id=5470 value = eval('# coding=%s\n%s' % (str(encoding), value), {'__builtins__':{}}, {}) if PY2 and not isinstance(value, text_type): value = value.decode(encoding) buf.append(value) elif tok == OP and value == ',': if buf: messages.append(''.join(buf)) del buf[:] else: messages.append(None) if translator_comments: # We have translator comments, and since we're on a # comma(,) user is allowed to break into a new line # Let's increase the last comment's lineno in order # for the comment to still be a valid one old_lineno, old_comment = translator_comments.pop() translator_comments.append((old_lineno+1, old_comment)) elif call_stack > 0 and tok == OP and value == ')': call_stack -= 1 elif funcname and call_stack == -1: funcname = None elif tok == NAME and value in keywords: funcname = value def extract_javascript(fileobj, keywords, comment_tags, options): """Extract messages from JavaScript source code. :param fileobj: the seekable, file-like object the messages should be extracted from :param keywords: a list of keywords (i.e. function names) that should be recognized as translation functions :param comment_tags: a list of translator tags to search for and include in the results :param options: a dictionary of additional options (optional) """ from babel.messages.jslexer import tokenize, unquote_string funcname = message_lineno = None messages = [] last_argument = None translator_comments = [] concatenate_next = False encoding = options.get('encoding', 'utf-8') last_token = None call_stack = -1 for token in tokenize(fileobj.read().decode(encoding)): if token.type == 'operator' and token.value == '(': if funcname: message_lineno = token.lineno call_stack += 1 elif call_stack == -1 and token.type == 'linecomment': value = token.value[2:].strip() if translator_comments and \ translator_comments[-1][0] == token.lineno - 1: translator_comments.append((token.lineno, value)) continue for comment_tag in comment_tags: if value.startswith(comment_tag): translator_comments.append((token.lineno, value.strip())) break elif token.type == 'multilinecomment': # only one multi-line comment may preceed a translation translator_comments = [] value = token.value[2:-2].strip() for comment_tag in comment_tags: if value.startswith(comment_tag): lines = value.splitlines() if lines: lines[0] = lines[0].strip() lines[1:] = dedent('\n'.join(lines[1:])).splitlines() for offset, line in enumerate(lines): translator_comments.append((token.lineno + offset, line)) break elif funcname and call_stack == 0: if token.type == 'operator' and token.value == ')': if last_argument is not None: messages.append(last_argument) if len(messages) > 1: messages = tuple(messages) elif messages: messages = messages[0] else: messages = None # Comments don't apply unless they immediately precede the # message if translator_comments and \ translator_comments[-1][0] < message_lineno - 1: translator_comments = [] if messages is not None: yield (message_lineno, funcname, messages, [comment[1] for comment in translator_comments]) funcname = message_lineno = last_argument = None concatenate_next = False translator_comments = [] messages = [] call_stack = -1 elif token.type == 'string': new_value = unquote_string(token.value) if concatenate_next: last_argument = (last_argument or '') + new_value concatenate_next = False else: last_argument = new_value elif token.type == 'operator': if token.value == ',': if last_argument is not None: messages.append(last_argument) last_argument = None else: messages.append(None) concatenate_next = False elif token.value == '+': concatenate_next = True elif call_stack > 0 and token.type == 'operator' \ and token.value == ')': call_stack -= 1 elif funcname and call_stack == -1: funcname = None elif call_stack == -1 and token.type == 'name' and \ token.value in keywords and \ (last_token is None or last_token.type != 'name' or last_token.value != 'function'): funcname = token.value last_token = token
mit
JVillella/tensorflow
tensorflow/contrib/timeseries/python/timeseries/state_space_models/varma.py
25
8860
# 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. # ============================================================================== r"""Multivariate autoregressive model (vector autoregression). Implements the following model (num_blocks = max(ar_order, ma_order + 1)): y(t, 1) = \sum_{i=1}^{ar_order} ar_coefs[i] * y(t - 1, i) y(t, i) = y(t - 1, i - 1) + ma_coefs[i - 1] * e(t) for 1 < i < num_blocks y(t, num_blocks) = y(t - 1, num_blocks - 1) + e(t) Where e(t) are Gaussian with zero mean and learned covariance. Each element of ar_coefs and ma_coefs is a [num_features x num_features] matrix. Each y(t, i) is a vector of length num_features. Indices in the above equations are one-based. Initial conditions y(0, i) come from prior state (which may either be learned or left as a constant with high prior covariance). If ar_order > ma_order, the observation model is: y(t, 1) + observation_noise(t) If ma_order >= ar_order, it is (to observe the moving average component): y(t, 1) + y(t, num_blocks) + observation_noise(t) Where observation_noise(t) are Gaussian with zero mean and learned covariance. This implementation uses a formulation which puts all of the autoregressive coefficients in the transition equation for the observed component, which enables learning using truncated backpropagation. Noise is not applied directly to the observed component (with the exception of standard observation noise), which further aids learning of the autoregressive coefficients when VARMA is in an ensemble with other models (in which case having an observation noise term is usually unavoidable). """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.timeseries.python.timeseries import math_utils from tensorflow.contrib.timeseries.python.timeseries.state_space_models import state_space_model from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import linalg_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import variable_scope class VARMA(state_space_model.StateSpaceModel): """A VARMA model implementation as a special case of the state space model.""" def __init__(self, autoregressive_order, moving_average_order, configuration=state_space_model.StateSpaceModelConfiguration()): """Construct a VARMA model. The size of the latent state for this model is: num_features * max(autoregressive_order, moving_average_order + 1) Square matrices of this size are constructed and multiplied. Args: autoregressive_order: The maximum autoregressive lag. moving_average_order: The maximum moving average lag, after which transient deviations are expected to return to their long-term mean. configuration: A StateSpaceModelConfiguration object. """ self.ar_order = autoregressive_order self.ma_order = moving_average_order self.state_num_blocks = max(autoregressive_order, moving_average_order + 1) super(VARMA, self).__init__(configuration=configuration) self.state_dimension = self.state_num_blocks * self.num_features def _define_parameters(self, observation_transition_tradeoff_log=None): with variable_scope.variable_scope(self._variable_scope): # TODO(allenl): Evaluate parameter transformations for AR/MA coefficients # which improve interpretability/stability. self.ar_coefs = variable_scope.get_variable( name="ar_coefs", shape=[self.num_features, self.num_features, self.ar_order], dtype=self.dtype, initializer=init_ops.zeros_initializer()) self.ma_coefs = variable_scope.get_variable( name="ma_coefs", initializer=array_ops.tile( linalg_ops.eye(self.num_features, dtype=self.dtype)[None, :, :], [self.ma_order, 1, 1]), dtype=self.dtype) super(VARMA, self)._define_parameters( observation_transition_tradeoff_log=observation_transition_tradeoff_log) def get_state_transition(self): """Construct state transition matrix from VARMA parameters. Returns: the state transition matrix. It has shape [self.state_dimendion, self.state_dimension]. """ # Pad any unused AR blocks with zeros. The extra state is necessary if # ma_order >= ar_order. ar_coefs_padded = array_ops.reshape( array_ops.pad(self.ar_coefs, [[0, 0], [0, 0], [0, self.state_num_blocks - self.ar_order]]), [self.num_features, self.state_dimension]) shift_matrix = array_ops.pad( linalg_ops.eye( (self.state_num_blocks - 1) * self.num_features, dtype=self.dtype), [[0, 0], [0, self.num_features]]) return array_ops.concat([ar_coefs_padded, shift_matrix], axis=0) def get_noise_transform(self): """Construct state noise transform matrix from VARMA parameters. Returns: the state noise transform matrix. It has shape [self.state_dimendion, self.num_features]. """ # Noise is broadcast, through the moving average coefficients, to # un-observed parts of the latent state. ma_coefs_padded = array_ops.reshape( array_ops.pad(self.ma_coefs, [[self.state_num_blocks - 1 - self.ma_order, 0], [0, 0], [0, 0]]), [(self.state_num_blocks - 1) * self.num_features, self.num_features], name="noise_transform") # Deterministically apply noise to the oldest component. return array_ops.concat( [ma_coefs_padded, linalg_ops.eye(self.num_features, dtype=self.dtype)], axis=0) def get_observation_model(self, times): """Construct observation model matrix from VARMA parameters. Args: times: A [batch size] vector indicating the times observation models are requested for. Unused. Returns: the observation model matrix. It has shape [self.num_features, self.state_dimension]. """ del times # StateSpaceModel will broadcast along the batch dimension if self.ar_order > self.ma_order or self.state_num_blocks < 2: return array_ops.pad( linalg_ops.eye(self.num_features, dtype=self.dtype), [[0, 0], [0, self.num_features * (self.state_num_blocks - 1)]], name="observation_model") else: # Add a second observed component which "catches" the accumulated moving # average errors as they reach the end of the state. If ar_order > # ma_order, this is unnecessary, since accumulated errors cycle naturally. return array_ops.concat( [ array_ops.pad( linalg_ops.eye(self.num_features, dtype=self.dtype), [[0, 0], [0, self.num_features * (self.state_num_blocks - 2)]]), linalg_ops.eye(self.num_features, dtype=self.dtype) ], axis=1, name="observation_model") def get_state_transition_noise_covariance( self, minimum_initial_variance=1e-5): # Most state space models use only an explicit observation noise term to # model deviations from expectations, and so a low initial transition noise # parameter is helpful there. Since deviations from expectations are also # modeled as transition noise in VARMA, we set its initial value based on a # slight over-estimate empirical observation noise. if self._input_statistics is not None: feature_variance = self._input_statistics.series_start_moments.variance initial_transition_noise_scale = math_ops.log( math_ops.maximum( math_ops.reduce_mean(feature_variance), minimum_initial_variance)) else: initial_transition_noise_scale = 0. state_noise_transform = ops.convert_to_tensor( self.get_noise_transform(), dtype=self.dtype) state_noise_dimension = state_noise_transform.get_shape()[1].value return math_utils.variable_covariance_matrix( state_noise_dimension, "state_transition_noise", dtype=self.dtype, initial_overall_scale_log=initial_transition_noise_scale)
apache-2.0
grantsewell/nzbToMedia
libs/guessit/containers.py
6
28866
#!/usr/bin/env python # -*- coding: utf-8 -*- # # GuessIt - A library for guessing information from filenames # Copyright (c) 2013 Nicolas Wack <wackou@gmail.com> # Copyright (c) 2013 Rémi Alvergnat <toilal.dev@gmail.com> # # GuessIt is free software; you can redistribute it and/or modify it under # the terms of the Lesser GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # GuessIt 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 # Lesser GNU General Public License for more details. # # You should have received a copy of the Lesser GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from __future__ import absolute_import, division, print_function, unicode_literals from .patterns import compile_pattern, sep from . import base_text_type from .guess import Guess import types def _get_span(prop, match): """Retrieves span for a match""" if not prop.global_span and match.re.groups: start = None end = None for i in range(1, match.re.groups + 1): span = match.span(i) if start is None or span[0] < start: start = span[0] if end is None or span[1] > end: end = span[1] return start, end else: return match.span() start = span[0] end = span[1] def _trim_span(span, value, blanks = sep): start, end = span for i in range(0, len(value)): if value[i] in blanks: start += 1 else: break for i in reversed(range(0, len(value))): if value[i] in blanks: end -= 1 else: break if end <= start: return -1, -1 return start, end def _get_groups(compiled_re): """ Retrieves groups from re :return: list of group names """ if compiled_re.groups: indexgroup = {} for k, i in compiled_re.groupindex.items(): indexgroup[i] = k ret = [] for i in range(1, compiled_re.groups + 1): ret.append(indexgroup.get(i, i)) return ret else: return [None] class NoValidator(object): def validate(self, prop, string, node, match, entry_start, entry_end): return True class LeftValidator(object): """Make sure our match is starting by separator, or by another entry""" def validate(self, prop, string, node, match, entry_start, entry_end): span = _get_span(prop, match) span = _trim_span(span, string[span[0]:span[1]]) start, end = span sep_start = start <= 0 or string[start - 1] in sep start_by_other = start in entry_end if not sep_start and not start_by_other: return False return True class RightValidator(object): """Make sure our match is ended by separator, or by another entry""" def validate(self, prop, string, node, match, entry_start, entry_end): span = _get_span(prop, match) span = _trim_span(span, string[span[0]:span[1]]) start, end = span sep_end = end >= len(string) or string[end] in sep end_by_other = end in entry_start if not sep_end and not end_by_other: return False return True class ChainedValidator(object): def __init__(self, *validators): self._validators = validators def validate(self, prop, string, node, match, entry_start, entry_end): for validator in self._validators: if not validator.validate(prop, string, node, match, entry_start, entry_end): return False return True class SameKeyValidator(object): def __init__(self, validator_function): self.validator_function = validator_function def validate(self, prop, string, node, match, entry_start, entry_end): for key in prop.keys: for same_value_leaf in node.root.leaves_containing(key): ret = self.validator_function(same_value_leaf, key, prop, string, node, match, entry_start, entry_end) if ret is not None: return ret return True class OnlyOneValidator(SameKeyValidator): def __init__(self): super(OnlyOneValidator, self).__init__(lambda same_value_leaf, key, prop, string, node, match, entry_start, entry_end: False) class DefaultValidator(object): """Make sure our match is surrounded by separators, or by another entry""" def validate(self, prop, string, node, match, entry_start, entry_end): span = _get_span(prop, match) span = _trim_span(span, string[span[0]:span[1]]) start, end = span sep_start = start <= 0 or string[start - 1] in sep sep_end = end >= len(string) or string[end] in sep start_by_other = start in entry_end end_by_other = end in entry_start if (sep_start or start_by_other) and (sep_end or end_by_other): return True return False class FunctionValidator(object): def __init__(self, function): self.function = function def validate(self, prop, string, node, match, entry_start, entry_end): return self.function(prop, string, node, match, entry_start, entry_end) class FormatterValidator(object): def __init__(self, group_name=None, formatted_validator=None): self.group_name = group_name self.formatted_validator = formatted_validator def validate(self, prop, string, node, match, entry_start, entry_end): if self.group_name: formatted = prop.format(match.group(self.group_name), self.group_name) else: formatted = prop.format(match.group()) if self.formatted_validator: return self.formatted_validator(formatted) else: return formatted def _get_positions(prop, string, node, match, entry_start, entry_end): span = match.span() start = span[0] end = span[1] at_start = True at_end = True while start > 0: start -= 1 if string[start] not in sep: at_start = False break while end < len(string) - 1: end += 1 if string[end] not in sep: at_end = False break return at_start, at_end class WeakValidator(DefaultValidator): """Make sure our match is surrounded by separators and is the first or last element in the string""" def validate(self, prop, string, node, match, entry_start, entry_end): if super(WeakValidator, self).validate(prop, string, node, match, entry_start, entry_end): at_start, at_end = _get_positions(prop, string, node, match, entry_start, entry_end) return at_start or at_end return False class NeighborValidator(DefaultValidator): """Make sure the node is next another one""" def validate(self, prop, string, node, match, entry_start, entry_end): at_start, at_end = _get_positions(prop, string, node, match, entry_start, entry_end) if at_start: previous_leaf = node.root.previous_leaf(node) if previous_leaf is not None: return True if at_end: next_leaf = node.root.next_leaf(node) if next_leaf is not None: return True return False class LeavesValidator(DefaultValidator): def __init__(self, lambdas=None, previous_lambdas=None, next_lambdas=None, both_side=False, default_=True): self.previous_lambdas = previous_lambdas if previous_lambdas is not None else [] self.next_lambdas = next_lambdas if next_lambdas is not None else [] if lambdas: self.previous_lambdas.extend(lambdas) self.next_lambdas.extend(lambdas) self.both_side = both_side self.default_ = default_ """Make sure our match is surrounded by separators and validates defined lambdas""" def validate(self, prop, string, node, match, entry_start, entry_end): if self.default_: super_ret = super(LeavesValidator, self).validate(prop, string, node, match, entry_start, entry_end) else: super_ret = True if not super_ret: return False previous_ = self._validate_previous(prop, string, node, match, entry_start, entry_end) next_ = self._validate_next(prop, string, node, match, entry_start, entry_end) if previous_ is None and next_ is None: return super_ret if self.both_side: return previous_ and next_ else: return previous_ or next_ def _validate_previous(self, prop, string, node, match, entry_start, entry_end): if self.previous_lambdas: for leaf in node.root.previous_leaves(node): for lambda_ in self.previous_lambdas: ret = self._check_rule(lambda_, leaf) if ret is not None: return ret return False def _validate_next(self, prop, string, node, match, entry_start, entry_end): if self.next_lambdas: for leaf in node.root.next_leaves(node): for lambda_ in self.next_lambdas: ret = self._check_rule(lambda_, leaf) if ret is not None: return ret return False def _check_rule(self, lambda_, previous_leaf): return lambda_(previous_leaf) class _Property: """Represents a property configuration.""" def __init__(self, keys=None, pattern=None, canonical_form=None, canonical_from_pattern=True, confidence=1.0, enhance=True, global_span=False, validator=DefaultValidator(), formatter=None, disabler=None, confidence_lambda=None): """ :param keys: Keys of the property (format, screenSize, ...) :type keys: string :param canonical_form: Unique value of the property (DVD, 720p, ...) :type canonical_form: string :param pattern: Regexp pattern :type pattern: string :param confidence: confidence :type confidence: float :param enhance: enhance the pattern :type enhance: boolean :param global_span: if True, the whole match span will used to create the Guess. Else, the span from the capturing groups will be used. :type global_span: boolean :param validator: Validator to use :type validator: :class:`DefaultValidator` :param formatter: Formater to use :type formatter: function """ if isinstance(keys, list): self.keys = keys elif isinstance(keys, base_text_type): self.keys = [keys] else: self.keys = [] self.canonical_form = canonical_form if pattern is not None: self.pattern = pattern else: self.pattern = canonical_form if self.canonical_form is None and canonical_from_pattern: self.canonical_form = self.pattern self.compiled = compile_pattern(self.pattern, enhance=enhance) for group_name in _get_groups(self.compiled): if isinstance(group_name, base_text_type) and not group_name in self.keys: self.keys.append(group_name) if not self.keys: raise ValueError("No property key is defined") self.confidence = confidence self.confidence_lambda = confidence_lambda self.global_span = global_span self.validator = validator self.formatter = formatter self.disabler = disabler def disabled(self, options): if self.disabler: return self.disabler(options) return False def format(self, value, group_name=None): """Retrieves the final value from re group match value""" formatter = None if isinstance(self.formatter, dict): formatter = self.formatter.get(group_name) if formatter is None and group_name is not None: formatter = self.formatter.get(None) else: formatter = self.formatter if isinstance(formatter, types.FunctionType): return formatter(value) elif formatter is not None: return formatter.format(value) return value def __repr__(self): return "%s: %s" % (self.keys, self.canonical_form if self.canonical_form else self.pattern) class PropertiesContainer(object): def __init__(self, **kwargs): self._properties = [] self.default_property_kwargs = kwargs def unregister_property(self, name, *canonical_forms): """Unregister a property canonical forms If canonical_forms are specified, only those values will be unregistered :param name: Property name to unregister :type name: string :param canonical_forms: Values to unregister :type canonical_forms: varargs of string """ _properties = [prop for prop in self._properties if prop.name == name and (not canonical_forms or prop.canonical_form in canonical_forms)] def register_property(self, name, *patterns, **property_params): """Register property with defined canonical form and patterns. :param name: name of the property (format, screenSize, ...) :type name: string :param patterns: regular expression patterns to register for the property canonical_form :type patterns: varargs of string """ properties = [] for pattern in patterns: params = dict(self.default_property_kwargs) params.update(property_params) if isinstance(pattern, dict): params.update(pattern) prop = _Property(name, **params) else: prop = _Property(name, pattern, **params) self._properties.append(prop) properties.append(prop) return properties def register_canonical_properties(self, name, *canonical_forms, **property_params): """Register properties from their canonical forms. :param name: name of the property (releaseGroup, ...) :type name: string :param canonical_forms: values of the property ('ESiR', 'WAF', 'SEPTiC', ...) :type canonical_forms: varargs of strings """ properties = [] for canonical_form in canonical_forms: params = dict(property_params) params['canonical_form'] = canonical_form properties.extend(self.register_property(name, canonical_form, **property_params)) return properties def unregister_all_properties(self): """Unregister all defined properties""" self._properties.clear() def find_properties(self, string, node, options, name=None, validate=True, re_match=False, sort=True, multiple=False): """Find all distinct properties for given string If no capturing group is defined in the property, value will be grabbed from the entire match. If one ore more unnamed capturing group is defined in the property, first capturing group will be used. If named capturing group are defined in the property, they will be returned as property key. If validate, found properties will be validated by their defined validator If re_match, re.match will be used instead of re.search. if sort, found properties will be sorted from longer match to shorter match. If multiple is False and multiple values are found for the same property, the more confident one will be returned. If multiple is False and multiple values are found for the same property and the same confidence, the longer will be returned. :param string: input string :type string: string :param node: current node of the matching tree :type node: :class:`guessit.matchtree.MatchTree` :param name: name of property to find :type name: string :param re_match: use re.match instead of re.search :type re_match: bool :param multiple: Allows multiple property values to be returned :type multiple: bool :return: found properties :rtype: list of tuples (:class:`_Property`, match, list of tuples (property_name, tuple(value_start, value_end))) :see: `_Property` :see: `register_property` :see: `register_canonical_properties` """ entry_start = {} entry_end = {} entries = [] duplicate_matches = {} ret = [] if not string.strip(): return ret # search all properties for prop in self.get_properties(name): if not prop.disabled(options): valid_match = None if re_match: match = prop.compiled.match(string) if match: entries.append((prop, match)) else: matches = list(prop.compiled.finditer(string)) duplicate_matches[prop] = matches for match in matches: entries.append((prop, match)) for prop, match in entries: # compute confidence if prop.confidence_lambda: computed_confidence = prop.confidence_lambda(match) if computed_confidence is not None: prop.confidence = computed_confidence if validate: # compute entries start and ends for prop, match in entries: start, end = _get_span(prop, match) if start not in entry_start: entry_start[start] = [prop] else: entry_start[start].append(prop) if end not in entry_end: entry_end[end] = [prop] else: entry_end[end].append(prop) # remove invalid values while True: invalid_entries = [] for entry in entries: prop, match = entry if not prop.validator.validate(prop, string, node, match, entry_start, entry_end): invalid_entries.append(entry) if not invalid_entries: break for entry in invalid_entries: prop, match = entry entries.remove(entry) prop_duplicate_matches = duplicate_matches.get(prop) if prop_duplicate_matches: prop_duplicate_matches.remove(match) invalid_span = _get_span(prop, match) start = invalid_span[0] end = invalid_span[1] entry_start[start].remove(prop) if not entry_start.get(start): del entry_start[start] entry_end[end].remove(prop) if not entry_end.get(end): del entry_end[end] for prop, prop_duplicate_matches in duplicate_matches.items(): # Keeping the last valid match. # Needed for the.100.109.hdtv-lol.mp4 for duplicate_match in prop_duplicate_matches[:-1]: entries.remove((prop, duplicate_match)) if multiple: ret = entries else: # keep only best match if multiple values where found entries_dict = {} for entry in entries: for key in prop.keys: if key not in entries_dict: entries_dict[key] = [] entries_dict[key].append(entry) for key_entries in entries_dict.values(): if multiple: for entry in key_entries: ret.append(entry) else: best_ret = {} best_prop, best_match = None, None if len(key_entries) == 1: best_prop, best_match = key_entries[0] else: for prop, match in key_entries: start, end = _get_span(prop, match) if not best_prop or \ best_prop.confidence < best_prop.confidence or \ best_prop.confidence == best_prop.confidence and \ best_match.span()[1] - best_match.span()[0] < match.span()[1] - match.span()[0]: best_prop, best_match = prop, match best_ret[best_prop] = best_match for prop, match in best_ret.items(): ret.append((prop, match)) if sort: def _sorting(x): _, x_match = x x_start, x_end = x_match.span() return x_start - x_end ret.sort(key=_sorting) return ret def as_guess(self, found_properties, input=None, filter_=None, sep_replacement=None, multiple=False, *args, **kwargs): if filter_ is None: filter_ = lambda property, *args, **kwargs: True guesses = [] if multiple else None for prop, match in found_properties: first_key = None for key in prop.keys: # First property key will be used as base for effective name if isinstance(key, base_text_type): if first_key is None: first_key = key break property_name = first_key if first_key else None span = _get_span(prop, match) guess = Guess(confidence=prop.confidence, input=input, span=span, prop=property_name) groups = _get_groups(match.re) for group_name in groups: name = group_name if isinstance(group_name, base_text_type) else property_name if property_name not in groups else None if name: value = self._effective_prop_value(prop, group_name, input, match.span(group_name) if group_name else match.span(), sep_replacement) if not value is None: is_string = isinstance(value, base_text_type) if not is_string or is_string and value: # Keep non empty strings and other defined objects if isinstance(value, dict): for k, v in value.items(): if k is None: k = name guess[k] = v else: if name in guess: if not isinstance(guess[name], list): guess[name] = [guess[name]] guess[name].append(value) else: guess[name] = value if group_name: guess.metadata(prop).span = match.span(group_name) if filter_(guess): if multiple: guesses.append(guess) else: return guess return guesses def _effective_prop_value(self, prop, group_name, input=None, span=None, sep_replacement=None): if prop.canonical_form: return prop.canonical_form if input is None: return None value = input if span is not None: value = value[span[0]:span[1]] value = input[span[0]:span[1]] if input else None if sep_replacement: for sep_char in sep: value = value.replace(sep_char, sep_replacement) if value: value = prop.format(value, group_name) return value def get_properties(self, name=None, canonical_form=None): """Retrieve properties :return: Properties :rtype: generator """ for prop in self._properties: if (name is None or name in prop.keys) and (canonical_form is None or prop.canonical_form == canonical_form): yield prop def get_supported_properties(self): supported_properties = {} for prop in self.get_properties(): for k in prop.keys: values = supported_properties.get(k) if not values: values = set() supported_properties[k] = values if prop.canonical_form: values.add(prop.canonical_form) return supported_properties class QualitiesContainer(): def __init__(self): self._qualities = {} def register_quality(self, name, canonical_form, rating): """Register a quality rating. :param name: Name of the property :type name: string :param canonical_form: Value of the property :type canonical_form: string :param rating: Estimated quality rating for the property :type rating: int """ property_qualities = self._qualities.get(name) if property_qualities is None: property_qualities = {} self._qualities[name] = property_qualities property_qualities[canonical_form] = rating def unregister_quality(self, name, *canonical_forms): """Unregister quality ratings for given property name. If canonical_forms are specified, only those values will be unregistered :param name: Name of the property :type name: string :param canonical_forms: Value of the property :type canonical_forms: string """ if not canonical_forms: if name in self._qualities: del self._qualities[name] else: property_qualities = self._qualities.get(name) if property_qualities is not None: for property_canonical_form in canonical_forms: if property_canonical_form in property_qualities: del property_qualities[property_canonical_form] if not property_qualities: del self._qualities[name] def clear_qualities(self,): """Unregister all defined quality ratings. """ self._qualities.clear() def rate_quality(self, guess, *props): """Rate the quality of guess. :param guess: Guess to rate :type guess: :class:`guessit.guess.Guess` :param props: Properties to include in the rating. if empty, rating will be performed for all guess properties. :type props: varargs of string :return: Quality of the guess. The higher, the better. :rtype: int """ rate = 0 if not props: props = guess.keys() for prop in props: prop_value = guess.get(prop) prop_qualities = self._qualities.get(prop) if prop_value is not None and prop_qualities is not None: rate += prop_qualities.get(prop_value, 0) return rate def best_quality_properties(self, props, *guesses): """Retrieve the best quality guess, based on given properties :param props: Properties to include in the rating :type props: list of strings :param guesses: Guesses to rate :type guesses: :class:`guessit.guess.Guess` :return: Best quality guess from all passed guesses :rtype: :class:`guessit.guess.Guess` """ best_guess = None best_rate = None for guess in guesses: rate = self.rate_quality(guess, *props) if best_rate is None or best_rate < rate: best_rate = rate best_guess = guess return best_guess def best_quality(self, *guesses): """Retrieve the best quality guess. :param guesses: Guesses to rate :type guesses: :class:`guessit.guess.Guess` :return: Best quality guess from all passed guesses :rtype: :class:`guessit.guess.Guess` """ best_guess = None best_rate = None for guess in guesses: rate = self.rate_quality(guess) if best_rate is None or best_rate < rate: best_rate = rate best_guess = guess return best_guess
gpl-3.0
embox/mybuild
tests/test_solver.py
2
8677
from __future__ import absolute_import, division, print_function from mybuild._compat import * import functools import unittest from mybuild.req import pgraph from mybuild.req.solver import (ComparableSolution, create_trunk, solve_trunk, solve, SolveError) class HandyPgraph(pgraph.Pgraph): def __init__(self): super(HandyPgraph, self).__init__() for node_type in type(self)._iter_all_node_types(): if not hasattr(self, node_type.__name__): setattr(self, node_type.__name__, functools.partial(self.new_node, node_type)) class Named(object): @classmethod def _new(cls, *args, **kwargs): kwargs.setdefault('cache_kwargs', True) return super(Named, cls)._new(*args, **kwargs) def __init__(self, *args, **kwargs): self._name = kwargs.pop('name', None) super(Named, self).__init__(*args, **kwargs) def __repr__(self): return self._name or super(Named, self).__repr__() @HandyPgraph.node_type class NamedAtom(Named, pgraph.Atom): pass class StarArgsToArg(object): """For compatibility with tests, to let them to pass operands in *args.""" @classmethod def _new(cls, *operands, **kwargs): return super(StarArgsToArg, cls)._new(operands, **kwargs) @HandyPgraph.node_type class Or(Named, StarArgsToArg, pgraph.Or): pass @HandyPgraph.node_type class And(Named, StarArgsToArg, pgraph.And): pass @HandyPgraph.node_type class AtMostOne(Named, StarArgsToArg, pgraph.AtMostOne): pass @HandyPgraph.node_type class AllEqual(Named, StarArgsToArg, pgraph.AllEqual): pass class SolverTestCaseBase(unittest.TestCase): def setUp(self): self.pgraph = HandyPgraph() def atoms(self, names): return [self.pgraph.NamedAtom(name=name) for name in names] class TrunkTestCase(SolverTestCaseBase): """Test cases which do not involve branching.""" def test_initial_const(self): g = self.pgraph A, = self.atoms('A') N = g.new_const(True, A) solution = solve(g, {}) self.assertIs(True, solution[A]) def test_implication_1(self): g = self.pgraph A, = self.atoms('A') N = g.Not(A) solution = solve(g, {N: True}) self.assertIs(True, solution[N]) self.assertIs(False, solution[A]) def test_implication_2(self): g = self.pgraph A,B,C = self.atoms('ABC') N = g.AtMostOne(A,B,C) solution = solve(g, {N: False}) self.assertIs(False, solution[A]) self.assertIs(False, solution[B]) self.assertIs(False, solution[C]) def test_implication_3(self): g = self.pgraph A,B,C = self.atoms('ABC') N = g.AtMostOne(A,B,C) solution = solve(g, {N: True, A: True}) self.assertIs(False, solution[B]) self.assertIs(False, solution[C]) def test_neglast_1(self): g = self.pgraph A,B,C,D = self.atoms('ABCD') # (A|B) & (C|D) & (B|~C) & ~B N = g.And(g.Or(A,B), g.Or(C,D), g.Or(B, g.Not(C)), g.Not(B)) solution = solve(g, {N: True}) self.assertIs(True, solution[N]) self.assertIs(True, solution[A]) self.assertIs(False, solution[B]) self.assertIs(False, solution[C]) self.assertIs(True, solution[D]) def test_neglast_2(self): g = self.pgraph A,B = self.atoms('AB') # (A=>B) & A N = g.And(g.Implies(A,B), A) solution = solve(g, {N: True}) self.assertIs(True, solution[N]) self.assertIs(True, solution[A]) self.assertIs(True, solution[B]) def test_neglast_3(self): g = self.pgraph A,B = self.atoms('AB') # (A=>B) & ~B N = g.And(g.Implies(A,B), g.Not(B)) solution = solve(g, {N: True}) self.assertIs(True, solution[N]) self.assertIs(False, solution[A]) self.assertIs(False, solution[B]) def test_neglast_4(self): g = self.pgraph A,B,C = self.atoms('ABC') N = g.AtMostOne(A,B,C) solution = solve(g, {N: True, A: False, B: False}) self.assertIs(True, solution[C]) def test_violation_1(self): g = self.pgraph A, = self.atoms('A') # A & ~A N = g.And(A, g.Not(A)) with self.assertRaises(SolveError): solve(g, {N: True}) def test_violation_2(self): g = self.pgraph A,B,C = self.atoms('ABC') N = g.AtMostOne(A,B,C) with self.assertRaises(SolveError): solve(g, {A: True, B: True}) class BranchTestCase(SolverTestCaseBase): def sneaky_pair_and(self, a, b, **kwargs): """(A | B) & (~A | B) & (A | ~B)""" g = self.pgraph # return g.And(g.Or(a, b), # g.Or(g.Not(a), b), # g.Or(a, g.Not(b)), **kwargs) # solved the same way as an expr above, but gives lesser logs return g.And(g.Or(a[True], b[True]), g.Or(a[False], b[True]), g.Or(a[True], b[False]), **kwargs) def sneaky_chain(self): g = self.pgraph A, B, C, D, E = self.atoms('ABCDE') # (E | Z) & (~E | Z) & (E | ~Z), where # Z = (D | Y) & (~D | Y) & (D | ~Y), where # Y = (C | X) & (~C | X) & (C | ~X), where # X = (A | B) & (~A | B) & (A | ~B) X = self.sneaky_pair_and(A, B, name='X') Y = self.sneaky_pair_and(C, X, name='Y') Z = self.sneaky_pair_and(D, Y, name='Z') P = self.sneaky_pair_and(E, Z) return P, (X, Y, Z), (A, B, C, D, E) def test_contradiction_1(self): g = self.pgraph A,B = self.atoms('AB') # (A|B) & (~A | A&~A) N = g.And(g.Or(A, B), g.Or(g.Not(A), g.And(A, g.Not(A)))) solution = solve(g, {N: True}) self.assertIs(False, solution[A]) self.assertIs(True, solution[B]) def test_contradiction_2(self): g = self.pgraph A,B = self.atoms('AB') nA,nB = map(g.Not, (A,B)) # (A + ~A&~B + ~B) & (B + B&~A) # solution = solve(g, {N: True}) solution = solve(g, { g.Or(A, g.And(nA, nB), nB): True, g.Or(B, g.And(nA, B)): True }) self.assertIs(True, solution[A]) self.assertIs(True, solution[B]) def test_15(self): g = self.pgraph A,B,C = self.atoms('ABC') # (A | A&~A) & (A=>B) & (B=>C) & (C=>A) A[True] >> B[True] >> C[True] >> A[True] N = g.Or(A, g.And(A, g.Not(A))) solution = solve(g, {N: True}) self.assertIs(True, solution[A]) self.assertIs(True, solution[B]) self.assertIs(True, solution[C]) def test_resolve_0(self): g = self.pgraph A, B = self.atoms('AB') x = g.And(B[False], A[False], g.Or(A[True], B[True])) y = B[True] x.equivalent(y) with self.assertRaises(SolveError): solve(g, {self.sneaky_pair_and(A, B): True}) def test_resolve_1(self): g = self.pgraph A, B = self.atoms('AB') solution = solve(g, {self.sneaky_pair_and(A, B): True}) self.assertIs(True, solution[A]) self.assertIs(True, solution[B]) def test_resolve_2(self): g = self.pgraph A, B, C = self.atoms('ABC') # (C | X) & (~C | X) & (C | ~X), where # X = (A | B) & (~A | B) & (A | ~B) X = self.sneaky_pair_and(A, B, name='X') P = self.sneaky_pair_and(C, X) solution = solve(g, {P: True}) self.assertIs(True, solution[A]) self.assertIs(True, solution[B]) self.assertIs(True, solution[C]) self.assertIs(True, solution[X]) def test_resolve_4(self): g = self.pgraph P, pair_ands, atoms = self.sneaky_chain() solution = solve(g, {P: True}) for node in (pair_ands + atoms): self.assertIs(True, solution[node], "{0} is not True".format(node)) def test_trunk_base(self): g = self.pgraph P, pair_ands, atoms = self.sneaky_chain() initial_trunk = create_trunk(g, {P: True}) solved_trunk = solve_trunk(g, {P: True}) self.assertEqual(ComparableSolution(initial_trunk), ComparableSolution(solved_trunk.base)) self.assertEqual(ComparableSolution(initial_trunk.base), ComparableSolution(solved_trunk.base))
bsd-2-clause
elijah513/scikit-learn
sklearn/decomposition/truncated_svd.py
199
7744
"""Truncated SVD for sparse matrices, aka latent semantic analysis (LSA). """ # Author: Lars Buitinck <L.J.Buitinck@uva.nl> # Olivier Grisel <olivier.grisel@ensta.org> # Michael Becker <mike@beckerfuffle.com> # License: 3-clause BSD. import numpy as np import scipy.sparse as sp try: from scipy.sparse.linalg import svds except ImportError: from ..utils.arpack import svds from ..base import BaseEstimator, TransformerMixin from ..utils import check_array, as_float_array, check_random_state from ..utils.extmath import randomized_svd, safe_sparse_dot, svd_flip from ..utils.sparsefuncs import mean_variance_axis __all__ = ["TruncatedSVD"] class TruncatedSVD(BaseEstimator, TransformerMixin): """Dimensionality reduction using truncated SVD (aka LSA). This transformer performs linear dimensionality reduction by means of truncated singular value decomposition (SVD). It is very similar to PCA, but operates on sample vectors directly, instead of on a covariance matrix. This means it can work with scipy.sparse matrices efficiently. In particular, truncated SVD works on term count/tf-idf matrices as returned by the vectorizers in sklearn.feature_extraction.text. In that context, it is known as latent semantic analysis (LSA). This estimator supports two algorithm: a fast randomized SVD solver, and a "naive" algorithm that uses ARPACK as an eigensolver on (X * X.T) or (X.T * X), whichever is more efficient. Read more in the :ref:`User Guide <LSA>`. Parameters ---------- n_components : int, default = 2 Desired dimensionality of output data. Must be strictly less than the number of features. The default value is useful for visualisation. For LSA, a value of 100 is recommended. algorithm : string, default = "randomized" SVD solver to use. Either "arpack" for the ARPACK wrapper in SciPy (scipy.sparse.linalg.svds), or "randomized" for the randomized algorithm due to Halko (2009). n_iter : int, optional Number of iterations for randomized SVD solver. Not used by ARPACK. random_state : int or RandomState, optional (Seed for) pseudo-random number generator. If not given, the numpy.random singleton is used. tol : float, optional Tolerance for ARPACK. 0 means machine precision. Ignored by randomized SVD solver. Attributes ---------- components_ : array, shape (n_components, n_features) explained_variance_ratio_ : array, [n_components] Percentage of variance explained by each of the selected components. explained_variance_ : array, [n_components] The variance of the training samples transformed by a projection to each component. Examples -------- >>> from sklearn.decomposition import TruncatedSVD >>> from sklearn.random_projection import sparse_random_matrix >>> X = sparse_random_matrix(100, 100, density=0.01, random_state=42) >>> svd = TruncatedSVD(n_components=5, random_state=42) >>> svd.fit(X) # doctest: +NORMALIZE_WHITESPACE TruncatedSVD(algorithm='randomized', n_components=5, n_iter=5, random_state=42, tol=0.0) >>> print(svd.explained_variance_ratio_) # doctest: +ELLIPSIS [ 0.07825... 0.05528... 0.05445... 0.04997... 0.04134...] >>> print(svd.explained_variance_ratio_.sum()) # doctest: +ELLIPSIS 0.27930... See also -------- PCA RandomizedPCA References ---------- Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions Halko, et al., 2009 (arXiv:909) http://arxiv.org/pdf/0909.4061 Notes ----- SVD suffers from a problem called "sign indeterminancy", which means the sign of the ``components_`` and the output from transform depend on the algorithm and random state. To work around this, fit instances of this class to data once, then keep the instance around to do transformations. """ def __init__(self, n_components=2, algorithm="randomized", n_iter=5, random_state=None, tol=0.): self.algorithm = algorithm self.n_components = n_components self.n_iter = n_iter self.random_state = random_state self.tol = tol def fit(self, X, y=None): """Fit LSI model on training data X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data. Returns ------- self : object Returns the transformer object. """ self.fit_transform(X) return self def fit_transform(self, X, y=None): """Fit LSI model to X and perform dimensionality reduction on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data. Returns ------- X_new : array, shape (n_samples, n_components) Reduced version of X. This will always be a dense array. """ X = as_float_array(X, copy=False) random_state = check_random_state(self.random_state) # If sparse and not csr or csc, convert to csr if sp.issparse(X) and X.getformat() not in ["csr", "csc"]: X = X.tocsr() if self.algorithm == "arpack": U, Sigma, VT = svds(X, k=self.n_components, tol=self.tol) # svds doesn't abide by scipy.linalg.svd/randomized_svd # conventions, so reverse its outputs. Sigma = Sigma[::-1] U, VT = svd_flip(U[:, ::-1], VT[::-1]) elif self.algorithm == "randomized": k = self.n_components n_features = X.shape[1] if k >= n_features: raise ValueError("n_components must be < n_features;" " got %d >= %d" % (k, n_features)) U, Sigma, VT = randomized_svd(X, self.n_components, n_iter=self.n_iter, random_state=random_state) else: raise ValueError("unknown algorithm %r" % self.algorithm) self.components_ = VT # Calculate explained variance & explained variance ratio X_transformed = np.dot(U, np.diag(Sigma)) self.explained_variance_ = exp_var = np.var(X_transformed, axis=0) if sp.issparse(X): _, full_var = mean_variance_axis(X, axis=0) full_var = full_var.sum() else: full_var = np.var(X, axis=0).sum() self.explained_variance_ratio_ = exp_var / full_var return X_transformed def transform(self, X): """Perform dimensionality reduction on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) New data. Returns ------- X_new : array, shape (n_samples, n_components) Reduced version of X. This will always be a dense array. """ X = check_array(X, accept_sparse='csr') return safe_sparse_dot(X, self.components_.T) def inverse_transform(self, X): """Transform X back to its original space. Returns an array X_original whose transform would be X. Parameters ---------- X : array-like, shape (n_samples, n_components) New data. Returns ------- X_original : array, shape (n_samples, n_features) Note that this is always a dense array. """ X = check_array(X) return np.dot(X, self.components_)
bsd-3-clause
Jgarcia-IAS/Fidelizacion_odoo
openerp/report/render/rml2pdf/utils.py
381
7143
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2003, Fabien Pinckaers, UCL, FSA # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # ############################################################################## import copy import locale import logging import re import reportlab import openerp.tools as tools from openerp.tools.safe_eval import safe_eval as eval from openerp.tools.misc import ustr _logger = logging.getLogger(__name__) _regex = re.compile('\[\[(.+?)\]\]') def str2xml(s): return (s or '').replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;') def xml2str(s): return (s or '').replace('&amp;','&').replace('&lt;','<').replace('&gt;','>') def _child_get(node, self=None, tagname=None): for n in node: if self and self.localcontext and n.get('rml_loop'): for ctx in eval(n.get('rml_loop'),{}, self.localcontext): self.localcontext.update(ctx) if (tagname is None) or (n.tag==tagname): if n.get('rml_except', False): try: eval(n.get('rml_except'), {}, self.localcontext) except GeneratorExit: continue except Exception, e: _logger.warning('rml_except: "%s"', n.get('rml_except',''), exc_info=True) continue if n.get('rml_tag'): try: (tag,attr) = eval(n.get('rml_tag'),{}, self.localcontext) n2 = copy.deepcopy(n) n2.tag = tag n2.attrib.update(attr) yield n2 except GeneratorExit: yield n except Exception, e: _logger.warning('rml_tag: "%s"', n.get('rml_tag',''), exc_info=True) yield n else: yield n continue if self and self.localcontext and n.get('rml_except'): try: eval(n.get('rml_except'), {}, self.localcontext) except GeneratorExit: continue except Exception, e: _logger.warning('rml_except: "%s"', n.get('rml_except',''), exc_info=True) continue if self and self.localcontext and n.get('rml_tag'): try: (tag,attr) = eval(n.get('rml_tag'),{}, self.localcontext) n2 = copy.deepcopy(n) n2.tag = tag n2.attrib.update(attr or {}) yield n2 tagname = '' except GeneratorExit: pass except Exception, e: _logger.warning('rml_tag: "%s"', n.get('rml_tag',''), exc_info=True) pass if (tagname is None) or (n.tag==tagname): yield n def _process_text(self, txt): """Translate ``txt`` according to the language in the local context, replace dynamic ``[[expr]]`` with their real value, then escape the result for XML. :param str txt: original text to translate (must NOT be XML-escaped) :return: translated text, with dynamic expressions evaluated and with special XML characters escaped (``&,<,>``). """ if not self.localcontext: return str2xml(txt) if not txt: return '' result = '' sps = _regex.split(txt) while sps: # This is a simple text to translate to_translate = tools.ustr(sps.pop(0)) result += tools.ustr(self.localcontext.get('translate', lambda x:x)(to_translate)) if sps: txt = None try: expr = sps.pop(0) txt = eval(expr, self.localcontext) if txt and isinstance(txt, basestring): txt = tools.ustr(txt) except Exception: _logger.error("Failed to evaluate expression [[ %s ]] with context %r while rendering report, ignored.", expr, self.localcontext) if isinstance(txt, basestring): result += txt elif txt and (txt is not None) and (txt is not False): result += ustr(txt) return str2xml(result) def text_get(node): return ''.join([ustr(n.text) for n in node]) units = [ (re.compile('^(-?[0-9\.]+)\s*in$'), reportlab.lib.units.inch), (re.compile('^(-?[0-9\.]+)\s*cm$'), reportlab.lib.units.cm), (re.compile('^(-?[0-9\.]+)\s*mm$'), reportlab.lib.units.mm), (re.compile('^(-?[0-9\.]+)\s*$'), 1) ] def unit_get(size): global units if size: if size.find('.') == -1: decimal_point = '.' try: decimal_point = locale.nl_langinfo(locale.RADIXCHAR) except Exception: decimal_point = locale.localeconv()['decimal_point'] size = size.replace(decimal_point, '.') for unit in units: res = unit[0].search(size, 0) if res: return unit[1]*float(res.group(1)) return False def tuple_int_get(node, attr_name, default=None): if not node.get(attr_name): return default return map(int, node.get(attr_name).split(',')) def bool_get(value): return (str(value)=="1") or (value.lower()=='yes') def attr_get(node, attrs, dict=None): if dict is None: dict = {} res = {} for name in attrs: if node.get(name): res[name] = unit_get(node.get(name)) for key in dict: if node.get(key): if dict[key]=='str': res[key] = tools.ustr(node.get(key)) elif dict[key]=='bool': res[key] = bool_get(node.get(key)) elif dict[key]=='int': res[key] = int(node.get(key)) elif dict[key]=='unit': res[key] = unit_get(node.get(key)) elif dict[key] == 'float' : res[key] = float(node.get(key)) return res # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
addition-it-solutions/project-all
addons/mrp/res_config.py
4
3430
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (C) 2004-2012 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/>. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ class mrp_config_settings(osv.osv_memory): _name = 'mrp.config.settings' _inherit = 'res.config.settings' _columns = { 'module_mrp_repair': fields.boolean("Manage repairs of products ", help='Allows to manage all product repairs.\n' '* Add/remove products in the reparation\n' '* Impact for stocks\n' '* Invoicing (products and/or services)\n' '* Warranty concept\n' '* Repair quotation report\n' '* Notes for the technician and for the final customer.\n' '-This installs the module mrp_repair.'), 'module_mrp_operations': fields.boolean("Allow detailed planning of work order", help='This allows to add state, date_start,date_stop in production order operation lines (in the "Work Centers" tab).\n' '-This installs the module mrp_operations.'), 'module_mrp_byproduct': fields.boolean("Produce several products from one manufacturing order", help='You can configure by-products in the bill of material.\n' 'Without this module: A + B + C -> D.\n' 'With this module: A + B + C -> D + E.\n' '-This installs the module mrp_byproduct.'), 'group_mrp_routings': fields.boolean("Manage Work Order Operations and work orders ", implied_group='mrp.group_mrp_routings', help='Work Order Operations allow you to create and manage the manufacturing operations that should be followed ' 'within your work centers in order to produce a product. They are attached to bills of materials ' 'that will define the required raw materials.'), 'group_mrp_properties': fields.boolean("Allow several bill of materials per products using properties", implied_group='product.group_mrp_properties', help="""The selection of the right Bill of Material to use will depend on the properties specified on the sales order and the Bill of Material."""), 'group_rounding_efficiency': fields.boolean("Manage rounding and efficiency of BoM components", implied_group='mrp.group_rounding_efficiency', help="""Allow to manage product rounding on quantity and product efficiency during production process"""), }
agpl-3.0
RockySteveJobs/python-for-android
python3-alpha/python3-src/Lib/test/test_structmembers.py
88
4796
from _testcapi import _test_structmembersType, \ CHAR_MAX, CHAR_MIN, UCHAR_MAX, \ SHRT_MAX, SHRT_MIN, USHRT_MAX, \ INT_MAX, INT_MIN, UINT_MAX, \ LONG_MAX, LONG_MIN, ULONG_MAX, \ LLONG_MAX, LLONG_MIN, ULLONG_MAX, \ PY_SSIZE_T_MAX, PY_SSIZE_T_MIN import unittest from test import support ts=_test_structmembersType(False, # T_BOOL 1, # T_BYTE 2, # T_UBYTE 3, # T_SHORT 4, # T_USHORT 5, # T_INT 6, # T_UINT 7, # T_LONG 8, # T_ULONG 23, # T_PYSSIZET 9.99999,# T_FLOAT 10.1010101010, # T_DOUBLE "hi" # T_STRING_INPLACE ) class ReadWriteTests(unittest.TestCase): def test_bool(self): ts.T_BOOL = True self.assertEqual(ts.T_BOOL, True) ts.T_BOOL = False self.assertEqual(ts.T_BOOL, False) self.assertRaises(TypeError, setattr, ts, 'T_BOOL', 1) def test_byte(self): ts.T_BYTE = CHAR_MAX self.assertEqual(ts.T_BYTE, CHAR_MAX) ts.T_BYTE = CHAR_MIN self.assertEqual(ts.T_BYTE, CHAR_MIN) ts.T_UBYTE = UCHAR_MAX self.assertEqual(ts.T_UBYTE, UCHAR_MAX) def test_short(self): ts.T_SHORT = SHRT_MAX self.assertEqual(ts.T_SHORT, SHRT_MAX) ts.T_SHORT = SHRT_MIN self.assertEqual(ts.T_SHORT, SHRT_MIN) ts.T_USHORT = USHRT_MAX self.assertEqual(ts.T_USHORT, USHRT_MAX) def test_int(self): ts.T_INT = INT_MAX self.assertEqual(ts.T_INT, INT_MAX) ts.T_INT = INT_MIN self.assertEqual(ts.T_INT, INT_MIN) ts.T_UINT = UINT_MAX self.assertEqual(ts.T_UINT, UINT_MAX) def test_long(self): ts.T_LONG = LONG_MAX self.assertEqual(ts.T_LONG, LONG_MAX) ts.T_LONG = LONG_MIN self.assertEqual(ts.T_LONG, LONG_MIN) ts.T_ULONG = ULONG_MAX self.assertEqual(ts.T_ULONG, ULONG_MAX) def test_py_ssize_t(self): ts.T_PYSSIZET = PY_SSIZE_T_MAX self.assertEqual(ts.T_PYSSIZET, PY_SSIZE_T_MAX) ts.T_PYSSIZET = PY_SSIZE_T_MIN self.assertEqual(ts.T_PYSSIZET, PY_SSIZE_T_MIN) @unittest.skipUnless(hasattr(ts, "T_LONGLONG"), "long long not present") def test_longlong(self): ts.T_LONGLONG = LLONG_MAX self.assertEqual(ts.T_LONGLONG, LLONG_MAX) ts.T_LONGLONG = LLONG_MIN self.assertEqual(ts.T_LONGLONG, LLONG_MIN) ts.T_ULONGLONG = ULLONG_MAX self.assertEqual(ts.T_ULONGLONG, ULLONG_MAX) ## make sure these will accept a plain int as well as a long ts.T_LONGLONG = 3 self.assertEqual(ts.T_LONGLONG, 3) ts.T_ULONGLONG = 4 self.assertEqual(ts.T_ULONGLONG, 4) def test_bad_assignments(self): integer_attributes = [ 'T_BOOL', 'T_BYTE', 'T_UBYTE', 'T_SHORT', 'T_USHORT', 'T_INT', 'T_UINT', 'T_LONG', 'T_ULONG', 'T_PYSSIZET' ] if hasattr(ts, 'T_LONGLONG'): integer_attributes.extend(['T_LONGLONG', 'T_ULONGLONG']) # issue8014: this produced 'bad argument to internal function' # internal error for nonint in None, 3.2j, "full of eels", {}, []: for attr in integer_attributes: self.assertRaises(TypeError, setattr, ts, attr, nonint) def test_inplace_string(self): self.assertEqual(ts.T_STRING_INPLACE, "hi") self.assertRaises(TypeError, setattr, ts, "T_STRING_INPLACE", "s") self.assertRaises(TypeError, delattr, ts, "T_STRING_INPLACE") class TestWarnings(unittest.TestCase): def test_byte_max(self): with support.check_warnings(('', RuntimeWarning)): ts.T_BYTE = CHAR_MAX+1 def test_byte_min(self): with support.check_warnings(('', RuntimeWarning)): ts.T_BYTE = CHAR_MIN-1 def test_ubyte_max(self): with support.check_warnings(('', RuntimeWarning)): ts.T_UBYTE = UCHAR_MAX+1 def test_short_max(self): with support.check_warnings(('', RuntimeWarning)): ts.T_SHORT = SHRT_MAX+1 def test_short_min(self): with support.check_warnings(('', RuntimeWarning)): ts.T_SHORT = SHRT_MIN-1 def test_ushort_max(self): with support.check_warnings(('', RuntimeWarning)): ts.T_USHORT = USHRT_MAX+1 def test_main(verbose=None): support.run_unittest(__name__) if __name__ == "__main__": test_main(verbose=True)
apache-2.0
RO-ny9/python-for-android
python3-alpha/python3-src/Lib/tkinter/tix.py
45
77690
# -*-mode: python; fill-column: 75; tab-width: 8 -*- # # $Id$ # # Tix.py -- Tix widget wrappers. # # For Tix, see http://tix.sourceforge.net # # - Sudhir Shenoy (sshenoy@gol.com), Dec. 1995. # based on an idea of Jean-Marc Lugrin (lugrin@ms.com) # # NOTE: In order to minimize changes to Tkinter.py, some of the code here # (TixWidget.__init__) has been taken from Tkinter (Widget.__init__) # and will break if there are major changes in Tkinter. # # The Tix widgets are represented by a class hierarchy in python with proper # inheritance of base classes. # # As a result after creating a 'w = StdButtonBox', I can write # w.ok['text'] = 'Who Cares' # or w.ok['bg'] = w['bg'] # or even w.ok.invoke() # etc. # # Compare the demo tixwidgets.py to the original Tcl program and you will # appreciate the advantages. # from tkinter import * from tkinter import _flatten, _cnfmerge, _default_root # WARNING - TkVersion is a limited precision floating point number if TkVersion < 3.999: raise ImportError("This version of Tix.py requires Tk 4.0 or higher") import _tkinter # If this fails your Python may not be configured for Tk # Some more constants (for consistency with Tkinter) WINDOW = 'window' TEXT = 'text' STATUS = 'status' IMMEDIATE = 'immediate' IMAGE = 'image' IMAGETEXT = 'imagetext' BALLOON = 'balloon' AUTO = 'auto' ACROSSTOP = 'acrosstop' # A few useful constants for the Grid widget ASCII = 'ascii' CELL = 'cell' COLUMN = 'column' DECREASING = 'decreasing' INCREASING = 'increasing' INTEGER = 'integer' MAIN = 'main' MAX = 'max' REAL = 'real' ROW = 'row' S_REGION = 's-region' X_REGION = 'x-region' Y_REGION = 'y-region' # Some constants used by Tkinter dooneevent() TCL_DONT_WAIT = 1 << 1 TCL_WINDOW_EVENTS = 1 << 2 TCL_FILE_EVENTS = 1 << 3 TCL_TIMER_EVENTS = 1 << 4 TCL_IDLE_EVENTS = 1 << 5 TCL_ALL_EVENTS = 0 # BEWARE - this is implemented by copying some code from the Widget class # in Tkinter (to override Widget initialization) and is therefore # liable to break. import tkinter, os # Could probably add this to Tkinter.Misc class tixCommand: """The tix commands provide access to miscellaneous elements of Tix's internal state and the Tix application context. Most of the information manipulated by these commands pertains to the application as a whole, or to a screen or display, rather than to a particular window. This is a mixin class, assumed to be mixed to Tkinter.Tk that supports the self.tk.call method. """ def tix_addbitmapdir(self, directory): """Tix maintains a list of directories under which the tix_getimage and tix_getbitmap commands will search for image files. The standard bitmap directory is $TIX_LIBRARY/bitmaps. The addbitmapdir command adds directory into this list. By using this command, the image files of an applications can also be located using the tix_getimage or tix_getbitmap command. """ return self.tk.call('tix', 'addbitmapdir', directory) def tix_cget(self, option): """Returns the current value of the configuration option given by option. Option may be any of the options described in the CONFIGURATION OPTIONS section. """ return self.tk.call('tix', 'cget', option) def tix_configure(self, cnf=None, **kw): """Query or modify the configuration options of the Tix application context. If no option is specified, returns a dictionary all of the available options. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given option(s) to have the given value(s); in this case the command returns an empty string. Option may be any of the configuration options. """ # Copied from Tkinter.py if kw: cnf = _cnfmerge((cnf, kw)) elif cnf: cnf = _cnfmerge(cnf) if cnf is None: cnf = {} for x in self.tk.split(self.tk.call('tix', 'configure')): cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf if isinstance(cnf, StringType): x = self.tk.split(self.tk.call('tix', 'configure', '-'+cnf)) return (x[0][1:],) + x[1:] return self.tk.call(('tix', 'configure') + self._options(cnf)) def tix_filedialog(self, dlgclass=None): """Returns the file selection dialog that may be shared among different calls from this application. This command will create a file selection dialog widget when it is called the first time. This dialog will be returned by all subsequent calls to tix_filedialog. An optional dlgclass parameter can be passed to specified what type of file selection dialog widget is desired. Possible options are tix FileSelectDialog or tixExFileSelectDialog. """ if dlgclass is not None: return self.tk.call('tix', 'filedialog', dlgclass) else: return self.tk.call('tix', 'filedialog') def tix_getbitmap(self, name): """Locates a bitmap file of the name name.xpm or name in one of the bitmap directories (see the tix_addbitmapdir command above). By using tix_getbitmap, you can avoid hard coding the pathnames of the bitmap files in your application. When successful, it returns the complete pathname of the bitmap file, prefixed with the character '@'. The returned value can be used to configure the -bitmap option of the TK and Tix widgets. """ return self.tk.call('tix', 'getbitmap', name) def tix_getimage(self, name): """Locates an image file of the name name.xpm, name.xbm or name.ppm in one of the bitmap directories (see the addbitmapdir command above). If more than one file with the same name (but different extensions) exist, then the image type is chosen according to the depth of the X display: xbm images are chosen on monochrome displays and color images are chosen on color displays. By using tix_ getimage, you can avoid hard coding the pathnames of the image files in your application. When successful, this command returns the name of the newly created image, which can be used to configure the -image option of the Tk and Tix widgets. """ return self.tk.call('tix', 'getimage', name) def tix_option_get(self, name): """Gets the options maintained by the Tix scheme mechanism. Available options include: active_bg active_fg bg bold_font dark1_bg dark1_fg dark2_bg dark2_fg disabled_fg fg fixed_font font inactive_bg inactive_fg input1_bg input2_bg italic_font light1_bg light1_fg light2_bg light2_fg menu_font output1_bg output2_bg select_bg select_fg selector """ # could use self.tk.globalgetvar('tixOption', name) return self.tk.call('tix', 'option', 'get', name) def tix_resetoptions(self, newScheme, newFontSet, newScmPrio=None): """Resets the scheme and fontset of the Tix application to newScheme and newFontSet, respectively. This affects only those widgets created after this call. Therefore, it is best to call the resetoptions command before the creation of any widgets in a Tix application. The optional parameter newScmPrio can be given to reset the priority level of the Tk options set by the Tix schemes. Because of the way Tk handles the X option database, after Tix has been has imported and inited, it is not possible to reset the color schemes and font sets using the tix config command. Instead, the tix_resetoptions command must be used. """ if newScmPrio is not None: return self.tk.call('tix', 'resetoptions', newScheme, newFontSet, newScmPrio) else: return self.tk.call('tix', 'resetoptions', newScheme, newFontSet) class Tk(tkinter.Tk, tixCommand): """Toplevel widget of Tix which represents mostly the main window of an application. It has an associated Tcl interpreter.""" def __init__(self, screenName=None, baseName=None, className='Tix'): tkinter.Tk.__init__(self, screenName, baseName, className) tixlib = os.environ.get('TIX_LIBRARY') self.tk.eval('global auto_path; lappend auto_path [file dir [info nameof]]') if tixlib is not None: self.tk.eval('global auto_path; lappend auto_path {%s}' % tixlib) self.tk.eval('global tcl_pkgPath; lappend tcl_pkgPath {%s}' % tixlib) # Load Tix - this should work dynamically or statically # If it's static, tcl/tix8.1/pkgIndex.tcl should have # 'load {} Tix' # If it's dynamic under Unix, tcl/tix8.1/pkgIndex.tcl should have # 'load libtix8.1.8.3.so Tix' self.tk.eval('package require Tix') def destroy(self): # For safety, remove an delete_window binding before destroy self.protocol("WM_DELETE_WINDOW", "") tkinter.Tk.destroy(self) # The Tix 'tixForm' geometry manager class Form: """The Tix Form geometry manager Widgets can be arranged by specifying attachments to other widgets. See Tix documentation for complete details""" def config(self, cnf={}, **kw): self.tk.call('tixForm', self._w, *self._options(cnf, kw)) form = config def __setitem__(self, key, value): Form.form(self, {key: value}) def check(self): return self.tk.call('tixForm', 'check', self._w) def forget(self): self.tk.call('tixForm', 'forget', self._w) def grid(self, xsize=0, ysize=0): if (not xsize) and (not ysize): x = self.tk.call('tixForm', 'grid', self._w) y = self.tk.splitlist(x) z = () for x in y: z = z + (self.tk.getint(x),) return z return self.tk.call('tixForm', 'grid', self._w, xsize, ysize) def info(self, option=None): if not option: return self.tk.call('tixForm', 'info', self._w) if option[0] != '-': option = '-' + option return self.tk.call('tixForm', 'info', self._w, option) def slaves(self): return [self._nametowidget(x) for x in self.tk.splitlist( self.tk.call( 'tixForm', 'slaves', self._w))] tkinter.Widget.__bases__ = tkinter.Widget.__bases__ + (Form,) class TixWidget(tkinter.Widget): """A TixWidget class is used to package all (or most) Tix widgets. Widget initialization is extended in two ways: 1) It is possible to give a list of options which must be part of the creation command (so called Tix 'static' options). These cannot be given as a 'config' command later. 2) It is possible to give the name of an existing TK widget. These are child widgets created automatically by a Tix mega-widget. The Tk call to create these widgets is therefore bypassed in TixWidget.__init__ Both options are for use by subclasses only. """ def __init__ (self, master=None, widgetName=None, static_options=None, cnf={}, kw={}): # Merge keywords and dictionary arguments if kw: cnf = _cnfmerge((cnf, kw)) else: cnf = _cnfmerge(cnf) # Move static options into extra. static_options must be # a list of keywords (or None). extra=() # 'options' is always a static option if static_options: static_options.append('options') else: static_options = ['options'] for k,v in list(cnf.items()): if k in static_options: extra = extra + ('-' + k, v) del cnf[k] self.widgetName = widgetName Widget._setup(self, master, cnf) # If widgetName is None, this is a dummy creation call where the # corresponding Tk widget has already been created by Tix if widgetName: self.tk.call(widgetName, self._w, *extra) # Non-static options - to be done via a 'config' command if cnf: Widget.config(self, cnf) # Dictionary to hold subwidget names for easier access. We can't # use the children list because the public Tix names may not be the # same as the pathname component self.subwidget_list = {} # We set up an attribute access function so that it is possible to # do w.ok['text'] = 'Hello' rather than w.subwidget('ok')['text'] = 'Hello' # when w is a StdButtonBox. # We can even do w.ok.invoke() because w.ok is subclassed from the # Button class if you go through the proper constructors def __getattr__(self, name): if name in self.subwidget_list: return self.subwidget_list[name] raise AttributeError(name) def set_silent(self, value): """Set a variable without calling its action routine""" self.tk.call('tixSetSilent', self._w, value) def subwidget(self, name): """Return the named subwidget (which must have been created by the sub-class).""" n = self._subwidget_name(name) if not n: raise TclError("Subwidget " + name + " not child of " + self._name) # Remove header of name and leading dot n = n[len(self._w)+1:] return self._nametowidget(n) def subwidgets_all(self): """Return all subwidgets.""" names = self._subwidget_names() if not names: return [] retlist = [] for name in names: name = name[len(self._w)+1:] try: retlist.append(self._nametowidget(name)) except: # some of the widgets are unknown e.g. border in LabelFrame pass return retlist def _subwidget_name(self,name): """Get a subwidget name (returns a String, not a Widget !)""" try: return self.tk.call(self._w, 'subwidget', name) except TclError: return None def _subwidget_names(self): """Return the name of all subwidgets.""" try: x = self.tk.call(self._w, 'subwidgets', '-all') return self.tk.split(x) except TclError: return None def config_all(self, option, value): """Set configuration options for all subwidgets (and self).""" if option == '': return elif not isinstance(option, StringType): option = repr(option) if not isinstance(value, StringType): value = repr(value) names = self._subwidget_names() for name in names: self.tk.call(name, 'configure', '-' + option, value) # These are missing from Tkinter def image_create(self, imgtype, cnf={}, master=None, **kw): if not master: master = tkinter._default_root if not master: raise RuntimeError('Too early to create image') if kw and cnf: cnf = _cnfmerge((cnf, kw)) elif kw: cnf = kw options = () for k, v in cnf.items(): if hasattr(v, '__call__'): v = self._register(v) options = options + ('-'+k, v) return master.tk.call(('image', 'create', imgtype,) + options) def image_delete(self, imgname): try: self.tk.call('image', 'delete', imgname) except TclError: # May happen if the root was destroyed pass # Subwidgets are child widgets created automatically by mega-widgets. # In python, we have to create these subwidgets manually to mirror their # existence in Tk/Tix. class TixSubWidget(TixWidget): """Subwidget class. This is used to mirror child widgets automatically created by Tix/Tk as part of a mega-widget in Python (which is not informed of this)""" def __init__(self, master, name, destroy_physically=1, check_intermediate=1): if check_intermediate: path = master._subwidget_name(name) try: path = path[len(master._w)+1:] plist = path.split('.') except: plist = [] if not check_intermediate: # immediate descendant TixWidget.__init__(self, master, None, None, {'name' : name}) else: # Ensure that the intermediate widgets exist parent = master for i in range(len(plist) - 1): n = '.'.join(plist[:i+1]) try: w = master._nametowidget(n) parent = w except KeyError: # Create the intermediate widget parent = TixSubWidget(parent, plist[i], destroy_physically=0, check_intermediate=0) # The Tk widget name is in plist, not in name if plist: name = plist[-1] TixWidget.__init__(self, parent, None, None, {'name' : name}) self.destroy_physically = destroy_physically def destroy(self): # For some widgets e.g., a NoteBook, when we call destructors, # we must be careful not to destroy the frame widget since this # also destroys the parent NoteBook thus leading to an exception # in Tkinter when it finally calls Tcl to destroy the NoteBook for c in list(self.children.values()): c.destroy() if self._name in self.master.children: del self.master.children[self._name] if self._name in self.master.subwidget_list: del self.master.subwidget_list[self._name] if self.destroy_physically: # This is bypassed only for a few widgets self.tk.call('destroy', self._w) # Useful func. to split Tcl lists and return as a dict. From Tkinter.py def _lst2dict(lst): dict = {} for x in lst: dict[x[0][1:]] = (x[0][1:],) + x[1:] return dict # Useful class to create a display style - later shared by many items. # Contributed by Steffen Kremser class DisplayStyle: """DisplayStyle - handle configuration options shared by (multiple) Display Items""" def __init__(self, itemtype, cnf={}, **kw): master = _default_root # global from Tkinter if not master and 'refwindow' in cnf: master=cnf['refwindow'] elif not master and 'refwindow' in kw: master= kw['refwindow'] elif not master: raise RuntimeError("Too early to create display style: no root window") self.tk = master.tk self.stylename = self.tk.call('tixDisplayStyle', itemtype, *self._options(cnf,kw) ) def __str__(self): return self.stylename def _options(self, cnf, kw): if kw and cnf: cnf = _cnfmerge((cnf, kw)) elif kw: cnf = kw opts = () for k, v in cnf.items(): opts = opts + ('-'+k, v) return opts def delete(self): self.tk.call(self.stylename, 'delete') def __setitem__(self,key,value): self.tk.call(self.stylename, 'configure', '-%s'%key, value) def config(self, cnf={}, **kw): return _lst2dict( self.tk.split( self.tk.call( self.stylename, 'configure', *self._options(cnf,kw)))) def __getitem__(self,key): return self.tk.call(self.stylename, 'cget', '-%s'%key) ###################################################### ### The Tix Widget classes - in alphabetical order ### ###################################################### class Balloon(TixWidget): """Balloon help widget. Subwidget Class --------- ----- label Label message Message""" # FIXME: It should inherit -superclass tixShell def __init__(self, master=None, cnf={}, **kw): # static seem to be -installcolormap -initwait -statusbar -cursor static = ['options', 'installcolormap', 'initwait', 'statusbar', 'cursor'] TixWidget.__init__(self, master, 'tixBalloon', static, cnf, kw) self.subwidget_list['label'] = _dummyLabel(self, 'label', destroy_physically=0) self.subwidget_list['message'] = _dummyLabel(self, 'message', destroy_physically=0) def bind_widget(self, widget, cnf={}, **kw): """Bind balloon widget to another. One balloon widget may be bound to several widgets at the same time""" self.tk.call(self._w, 'bind', widget._w, *self._options(cnf, kw)) def unbind_widget(self, widget): self.tk.call(self._w, 'unbind', widget._w) class ButtonBox(TixWidget): """ButtonBox - A container for pushbuttons. Subwidgets are the buttons added with the add method. """ def __init__(self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixButtonBox', ['orientation', 'options'], cnf, kw) def add(self, name, cnf={}, **kw): """Add a button with given name to box.""" btn = self.tk.call(self._w, 'add', name, *self._options(cnf, kw)) self.subwidget_list[name] = _dummyButton(self, name) return btn def invoke(self, name): if name in self.subwidget_list: self.tk.call(self._w, 'invoke', name) class ComboBox(TixWidget): """ComboBox - an Entry field with a dropdown menu. The user can select a choice by either typing in the entry subwidget or selecting from the listbox subwidget. Subwidget Class --------- ----- entry Entry arrow Button slistbox ScrolledListBox tick Button cross Button : present if created with the fancy option""" # FIXME: It should inherit -superclass tixLabelWidget def __init__ (self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixComboBox', ['editable', 'dropdown', 'fancy', 'options'], cnf, kw) self.subwidget_list['label'] = _dummyLabel(self, 'label') self.subwidget_list['entry'] = _dummyEntry(self, 'entry') self.subwidget_list['arrow'] = _dummyButton(self, 'arrow') self.subwidget_list['slistbox'] = _dummyScrolledListBox(self, 'slistbox') try: self.subwidget_list['tick'] = _dummyButton(self, 'tick') self.subwidget_list['cross'] = _dummyButton(self, 'cross') except TypeError: # unavailable when -fancy not specified pass # align def add_history(self, str): self.tk.call(self._w, 'addhistory', str) def append_history(self, str): self.tk.call(self._w, 'appendhistory', str) def insert(self, index, str): self.tk.call(self._w, 'insert', index, str) def pick(self, index): self.tk.call(self._w, 'pick', index) class Control(TixWidget): """Control - An entry field with value change arrows. The user can adjust the value by pressing the two arrow buttons or by entering the value directly into the entry. The new value will be checked against the user-defined upper and lower limits. Subwidget Class --------- ----- incr Button decr Button entry Entry label Label""" # FIXME: It should inherit -superclass tixLabelWidget def __init__ (self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixControl', ['options'], cnf, kw) self.subwidget_list['incr'] = _dummyButton(self, 'incr') self.subwidget_list['decr'] = _dummyButton(self, 'decr') self.subwidget_list['label'] = _dummyLabel(self, 'label') self.subwidget_list['entry'] = _dummyEntry(self, 'entry') def decrement(self): self.tk.call(self._w, 'decr') def increment(self): self.tk.call(self._w, 'incr') def invoke(self): self.tk.call(self._w, 'invoke') def update(self): self.tk.call(self._w, 'update') class DirList(TixWidget): """DirList - displays a list view of a directory, its previous directories and its sub-directories. The user can choose one of the directories displayed in the list or change to another directory. Subwidget Class --------- ----- hlist HList hsb Scrollbar vsb Scrollbar""" # FIXME: It should inherit -superclass tixScrolledHList def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixDirList', ['options'], cnf, kw) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') def chdir(self, dir): self.tk.call(self._w, 'chdir', dir) class DirTree(TixWidget): """DirTree - Directory Listing in a hierarchical view. Displays a tree view of a directory, its previous directories and its sub-directories. The user can choose one of the directories displayed in the list or change to another directory. Subwidget Class --------- ----- hlist HList hsb Scrollbar vsb Scrollbar""" # FIXME: It should inherit -superclass tixScrolledHList def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixDirTree', ['options'], cnf, kw) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') def chdir(self, dir): self.tk.call(self._w, 'chdir', dir) class DirSelectBox(TixWidget): """DirSelectBox - Motif style file select box. It is generally used for the user to choose a file. FileSelectBox stores the files mostly recently selected into a ComboBox widget so that they can be quickly selected again. Subwidget Class --------- ----- selection ComboBox filter ComboBox dirlist ScrolledListBox filelist ScrolledListBox""" def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixDirSelectBox', ['options'], cnf, kw) self.subwidget_list['dirlist'] = _dummyDirList(self, 'dirlist') self.subwidget_list['dircbx'] = _dummyFileComboBox(self, 'dircbx') class ExFileSelectBox(TixWidget): """ExFileSelectBox - MS Windows style file select box. It provides an convenient method for the user to select files. Subwidget Class --------- ----- cancel Button ok Button hidden Checkbutton types ComboBox dir ComboBox file ComboBox dirlist ScrolledListBox filelist ScrolledListBox""" def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixExFileSelectBox', ['options'], cnf, kw) self.subwidget_list['cancel'] = _dummyButton(self, 'cancel') self.subwidget_list['ok'] = _dummyButton(self, 'ok') self.subwidget_list['hidden'] = _dummyCheckbutton(self, 'hidden') self.subwidget_list['types'] = _dummyComboBox(self, 'types') self.subwidget_list['dir'] = _dummyComboBox(self, 'dir') self.subwidget_list['dirlist'] = _dummyDirList(self, 'dirlist') self.subwidget_list['file'] = _dummyComboBox(self, 'file') self.subwidget_list['filelist'] = _dummyScrolledListBox(self, 'filelist') def filter(self): self.tk.call(self._w, 'filter') def invoke(self): self.tk.call(self._w, 'invoke') # Should inherit from a Dialog class class DirSelectDialog(TixWidget): """The DirSelectDialog widget presents the directories in the file system in a dialog window. The user can use this dialog window to navigate through the file system to select the desired directory. Subwidgets Class ---------- ----- dirbox DirSelectDialog""" # FIXME: It should inherit -superclass tixDialogShell def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixDirSelectDialog', ['options'], cnf, kw) self.subwidget_list['dirbox'] = _dummyDirSelectBox(self, 'dirbox') # cancel and ok buttons are missing def popup(self): self.tk.call(self._w, 'popup') def popdown(self): self.tk.call(self._w, 'popdown') # Should inherit from a Dialog class class ExFileSelectDialog(TixWidget): """ExFileSelectDialog - MS Windows style file select dialog. It provides an convenient method for the user to select files. Subwidgets Class ---------- ----- fsbox ExFileSelectBox""" # FIXME: It should inherit -superclass tixDialogShell def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixExFileSelectDialog', ['options'], cnf, kw) self.subwidget_list['fsbox'] = _dummyExFileSelectBox(self, 'fsbox') def popup(self): self.tk.call(self._w, 'popup') def popdown(self): self.tk.call(self._w, 'popdown') class FileSelectBox(TixWidget): """ExFileSelectBox - Motif style file select box. It is generally used for the user to choose a file. FileSelectBox stores the files mostly recently selected into a ComboBox widget so that they can be quickly selected again. Subwidget Class --------- ----- selection ComboBox filter ComboBox dirlist ScrolledListBox filelist ScrolledListBox""" def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixFileSelectBox', ['options'], cnf, kw) self.subwidget_list['dirlist'] = _dummyScrolledListBox(self, 'dirlist') self.subwidget_list['filelist'] = _dummyScrolledListBox(self, 'filelist') self.subwidget_list['filter'] = _dummyComboBox(self, 'filter') self.subwidget_list['selection'] = _dummyComboBox(self, 'selection') def apply_filter(self): # name of subwidget is same as command self.tk.call(self._w, 'filter') def invoke(self): self.tk.call(self._w, 'invoke') # Should inherit from a Dialog class class FileSelectDialog(TixWidget): """FileSelectDialog - Motif style file select dialog. Subwidgets Class ---------- ----- btns StdButtonBox fsbox FileSelectBox""" # FIXME: It should inherit -superclass tixStdDialogShell def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixFileSelectDialog', ['options'], cnf, kw) self.subwidget_list['btns'] = _dummyStdButtonBox(self, 'btns') self.subwidget_list['fsbox'] = _dummyFileSelectBox(self, 'fsbox') def popup(self): self.tk.call(self._w, 'popup') def popdown(self): self.tk.call(self._w, 'popdown') class FileEntry(TixWidget): """FileEntry - Entry field with button that invokes a FileSelectDialog. The user can type in the filename manually. Alternatively, the user can press the button widget that sits next to the entry, which will bring up a file selection dialog. Subwidgets Class ---------- ----- button Button entry Entry""" # FIXME: It should inherit -superclass tixLabelWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixFileEntry', ['dialogtype', 'options'], cnf, kw) self.subwidget_list['button'] = _dummyButton(self, 'button') self.subwidget_list['entry'] = _dummyEntry(self, 'entry') def invoke(self): self.tk.call(self._w, 'invoke') def file_dialog(self): # FIXME: return python object pass class HList(TixWidget, XView, YView): """HList - Hierarchy display widget can be used to display any data that have a hierarchical structure, for example, file system directory trees. The list entries are indented and connected by branch lines according to their places in the hierarchy. Subwidgets - None""" def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self, master, 'tixHList', ['columns', 'options'], cnf, kw) def add(self, entry, cnf={}, **kw): return self.tk.call(self._w, 'add', entry, *self._options(cnf, kw)) def add_child(self, parent=None, cnf={}, **kw): if not parent: parent = '' return self.tk.call( self._w, 'addchild', parent, *self._options(cnf, kw)) def anchor_set(self, entry): self.tk.call(self._w, 'anchor', 'set', entry) def anchor_clear(self): self.tk.call(self._w, 'anchor', 'clear') def column_width(self, col=0, width=None, chars=None): if not chars: return self.tk.call(self._w, 'column', 'width', col, width) else: return self.tk.call(self._w, 'column', 'width', col, '-char', chars) def delete_all(self): self.tk.call(self._w, 'delete', 'all') def delete_entry(self, entry): self.tk.call(self._w, 'delete', 'entry', entry) def delete_offsprings(self, entry): self.tk.call(self._w, 'delete', 'offsprings', entry) def delete_siblings(self, entry): self.tk.call(self._w, 'delete', 'siblings', entry) def dragsite_set(self, index): self.tk.call(self._w, 'dragsite', 'set', index) def dragsite_clear(self): self.tk.call(self._w, 'dragsite', 'clear') def dropsite_set(self, index): self.tk.call(self._w, 'dropsite', 'set', index) def dropsite_clear(self): self.tk.call(self._w, 'dropsite', 'clear') def header_create(self, col, cnf={}, **kw): self.tk.call(self._w, 'header', 'create', col, *self._options(cnf, kw)) def header_configure(self, col, cnf={}, **kw): if cnf is None: return _lst2dict( self.tk.split( self.tk.call(self._w, 'header', 'configure', col))) self.tk.call(self._w, 'header', 'configure', col, *self._options(cnf, kw)) def header_cget(self, col, opt): return self.tk.call(self._w, 'header', 'cget', col, opt) def header_exists(self, col): return self.tk.call(self._w, 'header', 'exists', col) def header_delete(self, col): self.tk.call(self._w, 'header', 'delete', col) def header_size(self, col): return self.tk.call(self._w, 'header', 'size', col) def hide_entry(self, entry): self.tk.call(self._w, 'hide', 'entry', entry) def indicator_create(self, entry, cnf={}, **kw): self.tk.call( self._w, 'indicator', 'create', entry, *self._options(cnf, kw)) def indicator_configure(self, entry, cnf={}, **kw): if cnf is None: return _lst2dict( self.tk.split( self.tk.call(self._w, 'indicator', 'configure', entry))) self.tk.call( self._w, 'indicator', 'configure', entry, *self._options(cnf, kw)) def indicator_cget(self, entry, opt): return self.tk.call(self._w, 'indicator', 'cget', entry, opt) def indicator_exists(self, entry): return self.tk.call (self._w, 'indicator', 'exists', entry) def indicator_delete(self, entry): self.tk.call(self._w, 'indicator', 'delete', entry) def indicator_size(self, entry): return self.tk.call(self._w, 'indicator', 'size', entry) def info_anchor(self): return self.tk.call(self._w, 'info', 'anchor') def info_bbox(self, entry): return self._getints( self.tk.call(self._w, 'info', 'bbox', entry)) or None def info_children(self, entry=None): c = self.tk.call(self._w, 'info', 'children', entry) return self.tk.splitlist(c) def info_data(self, entry): return self.tk.call(self._w, 'info', 'data', entry) def info_dragsite(self): return self.tk.call(self._w, 'info', 'dragsite') def info_dropsite(self): return self.tk.call(self._w, 'info', 'dropsite') def info_exists(self, entry): return self.tk.call(self._w, 'info', 'exists', entry) def info_hidden(self, entry): return self.tk.call(self._w, 'info', 'hidden', entry) def info_next(self, entry): return self.tk.call(self._w, 'info', 'next', entry) def info_parent(self, entry): return self.tk.call(self._w, 'info', 'parent', entry) def info_prev(self, entry): return self.tk.call(self._w, 'info', 'prev', entry) def info_selection(self): c = self.tk.call(self._w, 'info', 'selection') return self.tk.splitlist(c) def item_cget(self, entry, col, opt): return self.tk.call(self._w, 'item', 'cget', entry, col, opt) def item_configure(self, entry, col, cnf={}, **kw): if cnf is None: return _lst2dict( self.tk.split( self.tk.call(self._w, 'item', 'configure', entry, col))) self.tk.call(self._w, 'item', 'configure', entry, col, *self._options(cnf, kw)) def item_create(self, entry, col, cnf={}, **kw): self.tk.call( self._w, 'item', 'create', entry, col, *self._options(cnf, kw)) def item_exists(self, entry, col): return self.tk.call(self._w, 'item', 'exists', entry, col) def item_delete(self, entry, col): self.tk.call(self._w, 'item', 'delete', entry, col) def entrycget(self, entry, opt): return self.tk.call(self._w, 'entrycget', entry, opt) def entryconfigure(self, entry, cnf={}, **kw): if cnf is None: return _lst2dict( self.tk.split( self.tk.call(self._w, 'entryconfigure', entry))) self.tk.call(self._w, 'entryconfigure', entry, *self._options(cnf, kw)) def nearest(self, y): return self.tk.call(self._w, 'nearest', y) def see(self, entry): self.tk.call(self._w, 'see', entry) def selection_clear(self, cnf={}, **kw): self.tk.call(self._w, 'selection', 'clear', *self._options(cnf, kw)) def selection_includes(self, entry): return self.tk.call(self._w, 'selection', 'includes', entry) def selection_set(self, first, last=None): self.tk.call(self._w, 'selection', 'set', first, last) def show_entry(self, entry): return self.tk.call(self._w, 'show', 'entry', entry) class InputOnly(TixWidget): """InputOnly - Invisible widget. Unix only. Subwidgets - None""" def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self, master, 'tixInputOnly', None, cnf, kw) class LabelEntry(TixWidget): """LabelEntry - Entry field with label. Packages an entry widget and a label into one mega widget. It can beused be used to simplify the creation of ``entry-form'' type of interface. Subwidgets Class ---------- ----- label Label entry Entry""" def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self, master, 'tixLabelEntry', ['labelside','options'], cnf, kw) self.subwidget_list['label'] = _dummyLabel(self, 'label') self.subwidget_list['entry'] = _dummyEntry(self, 'entry') class LabelFrame(TixWidget): """LabelFrame - Labelled Frame container. Packages a frame widget and a label into one mega widget. To create widgets inside a LabelFrame widget, one creates the new widgets relative to the frame subwidget and manage them inside the frame subwidget. Subwidgets Class ---------- ----- label Label frame Frame""" def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self, master, 'tixLabelFrame', ['labelside','options'], cnf, kw) self.subwidget_list['label'] = _dummyLabel(self, 'label') self.subwidget_list['frame'] = _dummyFrame(self, 'frame') class ListNoteBook(TixWidget): """A ListNoteBook widget is very similar to the TixNoteBook widget: it can be used to display many windows in a limited space using a notebook metaphor. The notebook is divided into a stack of pages (windows). At one time only one of these pages can be shown. The user can navigate through these pages by choosing the name of the desired page in the hlist subwidget.""" def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixListNoteBook', ['options'], cnf, kw) # Is this necessary? It's not an exposed subwidget in Tix. self.subwidget_list['pane'] = _dummyPanedWindow(self, 'pane', destroy_physically=0) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['shlist'] = _dummyScrolledHList(self, 'shlist') def add(self, name, cnf={}, **kw): self.tk.call(self._w, 'add', name, *self._options(cnf, kw)) self.subwidget_list[name] = TixSubWidget(self, name) return self.subwidget_list[name] def page(self, name): return self.subwidget(name) def pages(self): # Can't call subwidgets_all directly because we don't want .nbframe names = self.tk.split(self.tk.call(self._w, 'pages')) ret = [] for x in names: ret.append(self.subwidget(x)) return ret def raise_page(self, name): # raise is a python keyword self.tk.call(self._w, 'raise', name) class Meter(TixWidget): """The Meter widget can be used to show the progress of a background job which may take a long time to execute. """ def __init__(self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixMeter', ['options'], cnf, kw) class NoteBook(TixWidget): """NoteBook - Multi-page container widget (tabbed notebook metaphor). Subwidgets Class ---------- ----- nbframe NoteBookFrame <pages> page widgets added dynamically with the add method""" def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self,master,'tixNoteBook', ['options'], cnf, kw) self.subwidget_list['nbframe'] = TixSubWidget(self, 'nbframe', destroy_physically=0) def add(self, name, cnf={}, **kw): self.tk.call(self._w, 'add', name, *self._options(cnf, kw)) self.subwidget_list[name] = TixSubWidget(self, name) return self.subwidget_list[name] def delete(self, name): self.tk.call(self._w, 'delete', name) self.subwidget_list[name].destroy() del self.subwidget_list[name] def page(self, name): return self.subwidget(name) def pages(self): # Can't call subwidgets_all directly because we don't want .nbframe names = self.tk.split(self.tk.call(self._w, 'pages')) ret = [] for x in names: ret.append(self.subwidget(x)) return ret def raise_page(self, name): # raise is a python keyword self.tk.call(self._w, 'raise', name) def raised(self): return self.tk.call(self._w, 'raised') class NoteBookFrame(TixWidget): # FIXME: This is dangerous to expose to be called on its own. pass class OptionMenu(TixWidget): """OptionMenu - creates a menu button of options. Subwidget Class --------- ----- menubutton Menubutton menu Menu""" def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixOptionMenu', ['options'], cnf, kw) self.subwidget_list['menubutton'] = _dummyMenubutton(self, 'menubutton') self.subwidget_list['menu'] = _dummyMenu(self, 'menu') def add_command(self, name, cnf={}, **kw): self.tk.call(self._w, 'add', 'command', name, *self._options(cnf, kw)) def add_separator(self, name, cnf={}, **kw): self.tk.call(self._w, 'add', 'separator', name, *self._options(cnf, kw)) def delete(self, name): self.tk.call(self._w, 'delete', name) def disable(self, name): self.tk.call(self._w, 'disable', name) def enable(self, name): self.tk.call(self._w, 'enable', name) class PanedWindow(TixWidget): """PanedWindow - Multi-pane container widget allows the user to interactively manipulate the sizes of several panes. The panes can be arranged either vertically or horizontally.The user changes the sizes of the panes by dragging the resize handle between two panes. Subwidgets Class ---------- ----- <panes> g/p widgets added dynamically with the add method.""" def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixPanedWindow', ['orientation', 'options'], cnf, kw) # add delete forget panecget paneconfigure panes setsize def add(self, name, cnf={}, **kw): self.tk.call(self._w, 'add', name, *self._options(cnf, kw)) self.subwidget_list[name] = TixSubWidget(self, name, check_intermediate=0) return self.subwidget_list[name] def delete(self, name): self.tk.call(self._w, 'delete', name) self.subwidget_list[name].destroy() del self.subwidget_list[name] def forget(self, name): self.tk.call(self._w, 'forget', name) def panecget(self, entry, opt): return self.tk.call(self._w, 'panecget', entry, opt) def paneconfigure(self, entry, cnf={}, **kw): if cnf is None: return _lst2dict( self.tk.split( self.tk.call(self._w, 'paneconfigure', entry))) self.tk.call(self._w, 'paneconfigure', entry, *self._options(cnf, kw)) def panes(self): names = self.tk.splitlist(self.tk.call(self._w, 'panes')) return [self.subwidget(x) for x in names] class PopupMenu(TixWidget): """PopupMenu widget can be used as a replacement of the tk_popup command. The advantage of the Tix PopupMenu widget is it requires less application code to manipulate. Subwidgets Class ---------- ----- menubutton Menubutton menu Menu""" # FIXME: It should inherit -superclass tixShell def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixPopupMenu', ['options'], cnf, kw) self.subwidget_list['menubutton'] = _dummyMenubutton(self, 'menubutton') self.subwidget_list['menu'] = _dummyMenu(self, 'menu') def bind_widget(self, widget): self.tk.call(self._w, 'bind', widget._w) def unbind_widget(self, widget): self.tk.call(self._w, 'unbind', widget._w) def post_widget(self, widget, x, y): self.tk.call(self._w, 'post', widget._w, x, y) class ResizeHandle(TixWidget): """Internal widget to draw resize handles on Scrolled widgets.""" def __init__(self, master, cnf={}, **kw): # There seems to be a Tix bug rejecting the configure method # Let's try making the flags -static flags = ['options', 'command', 'cursorfg', 'cursorbg', 'handlesize', 'hintcolor', 'hintwidth', 'x', 'y'] # In fact, x y height width are configurable TixWidget.__init__(self, master, 'tixResizeHandle', flags, cnf, kw) def attach_widget(self, widget): self.tk.call(self._w, 'attachwidget', widget._w) def detach_widget(self, widget): self.tk.call(self._w, 'detachwidget', widget._w) def hide(self, widget): self.tk.call(self._w, 'hide', widget._w) def show(self, widget): self.tk.call(self._w, 'show', widget._w) class ScrolledHList(TixWidget): """ScrolledHList - HList with automatic scrollbars.""" # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixScrolledHList', ['options'], cnf, kw) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') class ScrolledListBox(TixWidget): """ScrolledListBox - Listbox with automatic scrollbars.""" # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixScrolledListBox', ['options'], cnf, kw) self.subwidget_list['listbox'] = _dummyListbox(self, 'listbox') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') class ScrolledText(TixWidget): """ScrolledText - Text with automatic scrollbars.""" # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixScrolledText', ['options'], cnf, kw) self.subwidget_list['text'] = _dummyText(self, 'text') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') class ScrolledTList(TixWidget): """ScrolledTList - TList with automatic scrollbars.""" # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixScrolledTList', ['options'], cnf, kw) self.subwidget_list['tlist'] = _dummyTList(self, 'tlist') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') class ScrolledWindow(TixWidget): """ScrolledWindow - Window with automatic scrollbars.""" # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixScrolledWindow', ['options'], cnf, kw) self.subwidget_list['window'] = _dummyFrame(self, 'window') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') class Select(TixWidget): """Select - Container of button subwidgets. It can be used to provide radio-box or check-box style of selection options for the user. Subwidgets are buttons added dynamically using the add method.""" # FIXME: It should inherit -superclass tixLabelWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixSelect', ['allowzero', 'radio', 'orientation', 'labelside', 'options'], cnf, kw) self.subwidget_list['label'] = _dummyLabel(self, 'label') def add(self, name, cnf={}, **kw): self.tk.call(self._w, 'add', name, *self._options(cnf, kw)) self.subwidget_list[name] = _dummyButton(self, name) return self.subwidget_list[name] def invoke(self, name): self.tk.call(self._w, 'invoke', name) class Shell(TixWidget): """Toplevel window. Subwidgets - None""" def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self, master, 'tixShell', ['options', 'title'], cnf, kw) class DialogShell(TixWidget): """Toplevel window, with popup popdown and center methods. It tells the window manager that it is a dialog window and should be treated specially. The exact treatment depends on the treatment of the window manager. Subwidgets - None""" # FIXME: It should inherit from Shell def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self, master, 'tixDialogShell', ['options', 'title', 'mapped', 'minheight', 'minwidth', 'parent', 'transient'], cnf, kw) def popdown(self): self.tk.call(self._w, 'popdown') def popup(self): self.tk.call(self._w, 'popup') def center(self): self.tk.call(self._w, 'center') class StdButtonBox(TixWidget): """StdButtonBox - Standard Button Box (OK, Apply, Cancel and Help) """ def __init__(self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixStdButtonBox', ['orientation', 'options'], cnf, kw) self.subwidget_list['ok'] = _dummyButton(self, 'ok') self.subwidget_list['apply'] = _dummyButton(self, 'apply') self.subwidget_list['cancel'] = _dummyButton(self, 'cancel') self.subwidget_list['help'] = _dummyButton(self, 'help') def invoke(self, name): if name in self.subwidget_list: self.tk.call(self._w, 'invoke', name) class TList(TixWidget, XView, YView): """TList - Hierarchy display widget which can be used to display data in a tabular format. The list entries of a TList widget are similar to the entries in the Tk listbox widget. The main differences are (1) the TList widget can display the list entries in a two dimensional format and (2) you can use graphical images as well as multiple colors and fonts for the list entries. Subwidgets - None""" def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self, master, 'tixTList', ['options'], cnf, kw) def active_set(self, index): self.tk.call(self._w, 'active', 'set', index) def active_clear(self): self.tk.call(self._w, 'active', 'clear') def anchor_set(self, index): self.tk.call(self._w, 'anchor', 'set', index) def anchor_clear(self): self.tk.call(self._w, 'anchor', 'clear') def delete(self, from_, to=None): self.tk.call(self._w, 'delete', from_, to) def dragsite_set(self, index): self.tk.call(self._w, 'dragsite', 'set', index) def dragsite_clear(self): self.tk.call(self._w, 'dragsite', 'clear') def dropsite_set(self, index): self.tk.call(self._w, 'dropsite', 'set', index) def dropsite_clear(self): self.tk.call(self._w, 'dropsite', 'clear') def insert(self, index, cnf={}, **kw): self.tk.call(self._w, 'insert', index, *self._options(cnf, kw)) def info_active(self): return self.tk.call(self._w, 'info', 'active') def info_anchor(self): return self.tk.call(self._w, 'info', 'anchor') def info_down(self, index): return self.tk.call(self._w, 'info', 'down', index) def info_left(self, index): return self.tk.call(self._w, 'info', 'left', index) def info_right(self, index): return self.tk.call(self._w, 'info', 'right', index) def info_selection(self): c = self.tk.call(self._w, 'info', 'selection') return self.tk.splitlist(c) def info_size(self): return self.tk.call(self._w, 'info', 'size') def info_up(self, index): return self.tk.call(self._w, 'info', 'up', index) def nearest(self, x, y): return self.tk.call(self._w, 'nearest', x, y) def see(self, index): self.tk.call(self._w, 'see', index) def selection_clear(self, cnf={}, **kw): self.tk.call(self._w, 'selection', 'clear', *self._options(cnf, kw)) def selection_includes(self, index): return self.tk.call(self._w, 'selection', 'includes', index) def selection_set(self, first, last=None): self.tk.call(self._w, 'selection', 'set', first, last) class Tree(TixWidget): """Tree - The tixTree widget can be used to display hierarchical data in a tree form. The user can adjust the view of the tree by opening or closing parts of the tree.""" # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixTree', ['options'], cnf, kw) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') def autosetmode(self): '''This command calls the setmode method for all the entries in this Tree widget: if an entry has no child entries, its mode is set to none. Otherwise, if the entry has any hidden child entries, its mode is set to open; otherwise its mode is set to close.''' self.tk.call(self._w, 'autosetmode') def close(self, entrypath): '''Close the entry given by entryPath if its mode is close.''' self.tk.call(self._w, 'close', entrypath) def getmode(self, entrypath): '''Returns the current mode of the entry given by entryPath.''' return self.tk.call(self._w, 'getmode', entrypath) def open(self, entrypath): '''Open the entry given by entryPath if its mode is open.''' self.tk.call(self._w, 'open', entrypath) def setmode(self, entrypath, mode='none'): '''This command is used to indicate whether the entry given by entryPath has children entries and whether the children are visible. mode must be one of open, close or none. If mode is set to open, a (+) indicator is drawn next the the entry. If mode is set to close, a (-) indicator is drawn next the the entry. If mode is set to none, no indicators will be drawn for this entry. The default mode is none. The open mode indicates the entry has hidden children and this entry can be opened by the user. The close mode indicates that all the children of the entry are now visible and the entry can be closed by the user.''' self.tk.call(self._w, 'setmode', entrypath, mode) # Could try subclassing Tree for CheckList - would need another arg to init class CheckList(TixWidget): """The CheckList widget displays a list of items to be selected by the user. CheckList acts similarly to the Tk checkbutton or radiobutton widgets, except it is capable of handling many more items than checkbuttons or radiobuttons. """ # FIXME: It should inherit -superclass tixTree def __init__(self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixCheckList', ['options', 'radio'], cnf, kw) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') def autosetmode(self): '''This command calls the setmode method for all the entries in this Tree widget: if an entry has no child entries, its mode is set to none. Otherwise, if the entry has any hidden child entries, its mode is set to open; otherwise its mode is set to close.''' self.tk.call(self._w, 'autosetmode') def close(self, entrypath): '''Close the entry given by entryPath if its mode is close.''' self.tk.call(self._w, 'close', entrypath) def getmode(self, entrypath): '''Returns the current mode of the entry given by entryPath.''' return self.tk.call(self._w, 'getmode', entrypath) def open(self, entrypath): '''Open the entry given by entryPath if its mode is open.''' self.tk.call(self._w, 'open', entrypath) def getselection(self, mode='on'): '''Returns a list of items whose status matches status. If status is not specified, the list of items in the "on" status will be returned. Mode can be on, off, default''' c = self.tk.split(self.tk.call(self._w, 'getselection', mode)) return self.tk.splitlist(c) def getstatus(self, entrypath): '''Returns the current status of entryPath.''' return self.tk.call(self._w, 'getstatus', entrypath) def setstatus(self, entrypath, mode='on'): '''Sets the status of entryPath to be status. A bitmap will be displayed next to the entry its status is on, off or default.''' self.tk.call(self._w, 'setstatus', entrypath, mode) ########################################################################### ### The subclassing below is used to instantiate the subwidgets in each ### ### mega widget. This allows us to access their methods directly. ### ########################################################################### class _dummyButton(Button, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyCheckbutton(Checkbutton, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyEntry(Entry, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyFrame(Frame, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyLabel(Label, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyListbox(Listbox, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyMenu(Menu, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyMenubutton(Menubutton, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyScrollbar(Scrollbar, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyText(Text, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyScrolledListBox(ScrolledListBox, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) self.subwidget_list['listbox'] = _dummyListbox(self, 'listbox') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') class _dummyHList(HList, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyScrolledHList(ScrolledHList, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') class _dummyTList(TList, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyComboBox(ComboBox, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, ['fancy',destroy_physically]) self.subwidget_list['label'] = _dummyLabel(self, 'label') self.subwidget_list['entry'] = _dummyEntry(self, 'entry') self.subwidget_list['arrow'] = _dummyButton(self, 'arrow') self.subwidget_list['slistbox'] = _dummyScrolledListBox(self, 'slistbox') try: self.subwidget_list['tick'] = _dummyButton(self, 'tick') #cross Button : present if created with the fancy option self.subwidget_list['cross'] = _dummyButton(self, 'cross') except TypeError: # unavailable when -fancy not specified pass class _dummyDirList(DirList, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') class _dummyDirSelectBox(DirSelectBox, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) self.subwidget_list['dirlist'] = _dummyDirList(self, 'dirlist') self.subwidget_list['dircbx'] = _dummyFileComboBox(self, 'dircbx') class _dummyExFileSelectBox(ExFileSelectBox, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) self.subwidget_list['cancel'] = _dummyButton(self, 'cancel') self.subwidget_list['ok'] = _dummyButton(self, 'ok') self.subwidget_list['hidden'] = _dummyCheckbutton(self, 'hidden') self.subwidget_list['types'] = _dummyComboBox(self, 'types') self.subwidget_list['dir'] = _dummyComboBox(self, 'dir') self.subwidget_list['dirlist'] = _dummyScrolledListBox(self, 'dirlist') self.subwidget_list['file'] = _dummyComboBox(self, 'file') self.subwidget_list['filelist'] = _dummyScrolledListBox(self, 'filelist') class _dummyFileSelectBox(FileSelectBox, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) self.subwidget_list['dirlist'] = _dummyScrolledListBox(self, 'dirlist') self.subwidget_list['filelist'] = _dummyScrolledListBox(self, 'filelist') self.subwidget_list['filter'] = _dummyComboBox(self, 'filter') self.subwidget_list['selection'] = _dummyComboBox(self, 'selection') class _dummyFileComboBox(ComboBox, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) self.subwidget_list['dircbx'] = _dummyComboBox(self, 'dircbx') class _dummyStdButtonBox(StdButtonBox, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) self.subwidget_list['ok'] = _dummyButton(self, 'ok') self.subwidget_list['apply'] = _dummyButton(self, 'apply') self.subwidget_list['cancel'] = _dummyButton(self, 'cancel') self.subwidget_list['help'] = _dummyButton(self, 'help') class _dummyNoteBookFrame(NoteBookFrame, TixSubWidget): def __init__(self, master, name, destroy_physically=0): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyPanedWindow(PanedWindow, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) ######################## ### Utility Routines ### ######################## #mike Should tixDestroy be exposed as a wrapper? - but not for widgets. def OptionName(widget): '''Returns the qualified path name for the widget. Normally used to set default options for subwidgets. See tixwidgets.py''' return widget.tk.call('tixOptionName', widget._w) # Called with a dictionary argument of the form # {'*.c':'C source files', '*.txt':'Text Files', '*':'All files'} # returns a string which can be used to configure the fsbox file types # in an ExFileSelectBox. i.e., # '{{*} {* - All files}} {{*.c} {*.c - C source files}} {{*.txt} {*.txt - Text Files}}' def FileTypeList(dict): s = '' for type in dict.keys(): s = s + '{{' + type + '} {' + type + ' - ' + dict[type] + '}} ' return s # Still to be done: # tixIconView class CObjView(TixWidget): """This file implements the Canvas Object View widget. This is a base class of IconView. It implements automatic placement/adjustment of the scrollbars according to the canvas objects inside the canvas subwidget. The scrollbars are adjusted so that the canvas is just large enough to see all the objects. """ # FIXME: It should inherit -superclass tixScrolledWidget pass class Grid(TixWidget, XView, YView): '''The Tix Grid command creates a new window and makes it into a tixGrid widget. Additional options, may be specified on the command line or in the option database to configure aspects such as its cursor and relief. A Grid widget displays its contents in a two dimensional grid of cells. Each cell may contain one Tix display item, which may be in text, graphics or other formats. See the DisplayStyle class for more information about Tix display items. Individual cells, or groups of cells, can be formatted with a wide range of attributes, such as its color, relief and border. Subwidgets - None''' # valid specific resources as of Tk 8.4 # editdonecmd, editnotifycmd, floatingcols, floatingrows, formatcmd, # highlightbackground, highlightcolor, leftmargin, itemtype, selectmode, # selectunit, topmargin, def __init__(self, master=None, cnf={}, **kw): static= [] self.cnf= cnf TixWidget.__init__(self, master, 'tixGrid', static, cnf, kw) # valid options as of Tk 8.4 # anchor, bdtype, cget, configure, delete, dragsite, dropsite, entrycget, # edit, entryconfigure, format, geometryinfo, info, index, move, nearest, # selection, set, size, unset, xview, yview def anchor_clear(self): """Removes the selection anchor.""" self.tk.call(self, 'anchor', 'clear') def anchor_get(self): "Get the (x,y) coordinate of the current anchor cell" return self._getints(self.tk.call(self, 'anchor', 'get')) def anchor_set(self, x, y): """Set the selection anchor to the cell at (x, y).""" self.tk.call(self, 'anchor', 'set', x, y) def delete_row(self, from_, to=None): """Delete rows between from_ and to inclusive. If to is not provided, delete only row at from_""" if to is None: self.tk.call(self, 'delete', 'row', from_) else: self.tk.call(self, 'delete', 'row', from_, to) def delete_column(self, from_, to=None): """Delete columns between from_ and to inclusive. If to is not provided, delete only column at from_""" if to is None: self.tk.call(self, 'delete', 'column', from_) else: self.tk.call(self, 'delete', 'column', from_, to) def edit_apply(self): """If any cell is being edited, de-highlight the cell and applies the changes.""" self.tk.call(self, 'edit', 'apply') def edit_set(self, x, y): """Highlights the cell at (x, y) for editing, if the -editnotify command returns True for this cell.""" self.tk.call(self, 'edit', 'set', x, y) def entrycget(self, x, y, option): "Get the option value for cell at (x,y)" if option and option[0] != '-': option = '-' + option return self.tk.call(self, 'entrycget', x, y, option) def entryconfigure(self, x, y, cnf=None, **kw): return self._configure(('entryconfigure', x, y), cnf, kw) # def format # def index def info_exists(self, x, y): "Return True if display item exists at (x,y)" return self._getboolean(self.tk.call(self, 'info', 'exists', x, y)) def info_bbox(self, x, y): # This seems to always return '', at least for 'text' displayitems return self.tk.call(self, 'info', 'bbox', x, y) def move_column(self, from_, to, offset): """Moves the the range of columns from position FROM through TO by the distance indicated by OFFSET. For example, move_column(2, 4, 1) moves the columns 2,3,4 to columns 3,4,5.""" self.tk.call(self, 'move', 'column', from_, to, offset) def move_row(self, from_, to, offset): """Moves the the range of rows from position FROM through TO by the distance indicated by OFFSET. For example, move_row(2, 4, 1) moves the rows 2,3,4 to rows 3,4,5.""" self.tk.call(self, 'move', 'row', from_, to, offset) def nearest(self, x, y): "Return coordinate of cell nearest pixel coordinate (x,y)" return self._getints(self.tk.call(self, 'nearest', x, y)) # def selection adjust # def selection clear # def selection includes # def selection set # def selection toggle def set(self, x, y, itemtype=None, **kw): args= self._options(self.cnf, kw) if itemtype is not None: args= ('-itemtype', itemtype) + args self.tk.call(self, 'set', x, y, *args) def size_column(self, index, **kw): """Queries or sets the size of the column given by INDEX. INDEX may be any non-negative integer that gives the position of a given column. INDEX can also be the string "default"; in this case, this command queries or sets the default size of all columns. When no option-value pair is given, this command returns a tuple containing the current size setting of the given column. When option-value pairs are given, the corresponding options of the size setting of the given column are changed. Options may be one of the follwing: pad0 pixels Specifies the paddings to the left of a column. pad1 pixels Specifies the paddings to the right of a column. size val Specifies the width of a column . Val may be: "auto" -- the width of the column is set the the widest cell in the column; a valid Tk screen distance unit; or a real number following by the word chars (e.g. 3.4chars) that sets the width of the column to the given number of characters.""" return self.tk.split(self.tk.call(self._w, 'size', 'column', index, *self._options({}, kw))) def size_row(self, index, **kw): """Queries or sets the size of the row given by INDEX. INDEX may be any non-negative integer that gives the position of a given row . INDEX can also be the string "default"; in this case, this command queries or sets the default size of all rows. When no option-value pair is given, this command returns a list con- taining the current size setting of the given row . When option-value pairs are given, the corresponding options of the size setting of the given row are changed. Options may be one of the follwing: pad0 pixels Specifies the paddings to the top of a row. pad1 pixels Specifies the paddings to the the bottom of a row. size val Specifies the height of a row. Val may be: "auto" -- the height of the row is set the the highest cell in the row; a valid Tk screen distance unit; or a real number following by the word chars (e.g. 3.4chars) that sets the height of the row to the given number of characters.""" return self.tk.split(self.tk.call( self, 'size', 'row', index, *self._options({}, kw))) def unset(self, x, y): """Clears the cell at (x, y) by removing its display item.""" self.tk.call(self._w, 'unset', x, y) class ScrolledGrid(Grid): '''Scrolled Grid widgets''' # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master=None, cnf={}, **kw): static= [] self.cnf= cnf TixWidget.__init__(self, master, 'tixScrolledGrid', static, cnf, kw)
apache-2.0
sobomax/virtualbox_64bit_edd
src/VBox/Devices/EFI/Firmware/BaseTools/Source/Python/Table/TableDsc.py
11
4793
## @file # This file is used to create/update/query/erase table for dsc datas # # Copyright (c) 2008, Intel Corporation. All rights reserved.<BR> # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the license may be found at # http://opensource.org/licenses/bsd-license.php # # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. # ## # Import Modules # import Common.EdkLogger as EdkLogger import CommonDataClass.DataClass as DataClass from Table import Table from Common.String import ConvertToSqlString ## TableDsc # # This class defined a table used for data model # # @param object: Inherited from object class # # class TableDsc(Table): def __init__(self, Cursor): Table.__init__(self, Cursor) self.Table = 'Dsc' ## Create table # # Create table Dsc # # @param ID: ID of a Dsc item # @param Model: Model of a Dsc item # @param Value1: Value1 of a Dsc item # @param Value2: Value2 of a Dsc item # @param Value3: Value3 of a Dsc item # @param Arch: Arch of a Dsc item # @param BelongsToItem: The item belongs to which another item # @param BelongsToFile: The item belongs to which dsc file # @param StartLine: StartLine of a Dsc item # @param StartColumn: StartColumn of a Dsc item # @param EndLine: EndLine of a Dsc item # @param EndColumn: EndColumn of a Dsc item # @param Enabled: If this item enabled # def Create(self): SqlCommand = """create table IF NOT EXISTS %s (ID INTEGER PRIMARY KEY, Model INTEGER NOT NULL, Value1 VARCHAR NOT NULL, Value2 VARCHAR, Value3 VARCHAR, Arch VarCHAR, BelongsToItem SINGLE NOT NULL, BelongsToFile SINGLE NOT NULL, StartLine INTEGER NOT NULL, StartColumn INTEGER NOT NULL, EndLine INTEGER NOT NULL, EndColumn INTEGER NOT NULL, Enabled INTEGER DEFAULT 0 )""" % self.Table Table.Create(self, SqlCommand) ## Insert table # # Insert a record into table Dsc # # @param ID: ID of a Dsc item # @param Model: Model of a Dsc item # @param Value1: Value1 of a Dsc item # @param Value2: Value2 of a Dsc item # @param Value3: Value3 of a Dsc item # @param Arch: Arch of a Dsc item # @param BelongsToItem: The item belongs to which another item # @param BelongsToFile: The item belongs to which dsc file # @param StartLine: StartLine of a Dsc item # @param StartColumn: StartColumn of a Dsc item # @param EndLine: EndLine of a Dsc item # @param EndColumn: EndColumn of a Dsc item # @param Enabled: If this item enabled # def Insert(self, Model, Value1, Value2, Value3, Arch, BelongsToItem, BelongsToFile, StartLine, StartColumn, EndLine, EndColumn, Enabled): self.ID = self.ID + 1 (Value1, Value2, Value3, Arch) = ConvertToSqlString((Value1, Value2, Value3, Arch)) SqlCommand = """insert into %s values(%s, %s, '%s', '%s', '%s', '%s', %s, %s, %s, %s, %s, %s, %s)""" \ % (self.Table, self.ID, Model, Value1, Value2, Value3, Arch, BelongsToItem, BelongsToFile, StartLine, StartColumn, EndLine, EndColumn, Enabled) Table.Insert(self, SqlCommand) return self.ID ## Query table # # @param Model: The Model of Record # # @retval: A recordSet of all found records # def Query(self, Model): SqlCommand = """select ID, Value1, Value2, Value3, Arch, BelongsToItem, BelongsToFile, StartLine from %s where Model = %s and Enabled > -1""" % (self.Table, Model) EdkLogger.debug(4, "SqlCommand: %s" % SqlCommand) self.Cur.execute(SqlCommand) return self.Cur.fetchall()
gpl-2.0
Acehaidrey/incubator-airflow
tests/sensors/test_filesystem.py
7
5534
# # 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 os.path import shutil import tempfile import unittest from airflow.exceptions import AirflowSensorTimeout from airflow.models.dag import DAG from airflow.sensors.filesystem import FileSensor from airflow.utils.timezone import datetime TEST_DAG_ID = 'unit_tests_file_sensor' DEFAULT_DATE = datetime(2015, 1, 1) class TestFileSensor(unittest.TestCase): def setUp(self): from airflow.hooks.filesystem import FSHook hook = FSHook() args = {'owner': 'airflow', 'start_date': DEFAULT_DATE} dag = DAG(TEST_DAG_ID + 'test_schedule_dag_once', default_args=args) self.hook = hook self.dag = dag def test_simple(self): with tempfile.NamedTemporaryFile() as tmp: task = FileSensor( task_id="test", filepath=tmp.name[1:], fs_conn_id='fs_default', dag=self.dag, timeout=0, ) task._hook = self.hook task.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_file_in_nonexistent_dir(self): temp_dir = tempfile.mkdtemp() task = FileSensor( task_id="test", filepath=temp_dir[1:] + "/file", fs_conn_id='fs_default', dag=self.dag, timeout=0, poke_interval=1, ) task._hook = self.hook try: with self.assertRaises(AirflowSensorTimeout): task.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) finally: shutil.rmtree(temp_dir) def test_empty_dir(self): temp_dir = tempfile.mkdtemp() task = FileSensor( task_id="test", filepath=temp_dir[1:], fs_conn_id='fs_default', dag=self.dag, timeout=0, poke_interval=1, ) task._hook = self.hook try: with self.assertRaises(AirflowSensorTimeout): task.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) finally: shutil.rmtree(temp_dir) def test_file_in_dir(self): temp_dir = tempfile.mkdtemp() task = FileSensor( task_id="test", filepath=temp_dir[1:], fs_conn_id='fs_default', dag=self.dag, timeout=0, ) task._hook = self.hook try: # `touch` the dir open(temp_dir + "/file", "a").close() task.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) finally: shutil.rmtree(temp_dir) def test_default_fs_conn_id(self): with tempfile.NamedTemporaryFile() as tmp: task = FileSensor( task_id="test", filepath=tmp.name[1:], dag=self.dag, timeout=0, ) task._hook = self.hook task.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_wildcard_file(self): suffix = '.txt' with tempfile.NamedTemporaryFile(suffix=suffix) as tmp: fileglob = os.path.join(os.path.dirname(tmp.name), '*' + suffix) task = FileSensor( task_id='test', filepath=fileglob, fs_conn_id='fs_default', dag=self.dag, timeout=0, ) task._hook = self.hook task.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_subdirectory_not_empty(self): suffix = '.txt' temp_dir = tempfile.mkdtemp() subdir = tempfile.mkdtemp(dir=temp_dir) with tempfile.NamedTemporaryFile(suffix=suffix, dir=subdir): task = FileSensor( task_id='test', filepath=temp_dir, fs_conn_id='fs_default', dag=self.dag, timeout=0, ) task._hook = self.hook task.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) shutil.rmtree(temp_dir) def test_subdirectory_empty(self): temp_dir = tempfile.mkdtemp() tempfile.mkdtemp(dir=temp_dir) task = FileSensor( task_id='test', filepath=temp_dir, fs_conn_id='fs_default', dag=self.dag, timeout=0, poke_interval=1, ) task._hook = self.hook with self.assertRaises(AirflowSensorTimeout): task.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) shutil.rmtree(temp_dir)
apache-2.0
walac/servo
tests/wpt/web-platform-tests/tools/html5lib/html5lib/tests/test_stream.py
446
6264
from __future__ import absolute_import, division, unicode_literals from . import support # flake8: noqa import unittest import codecs from io import BytesIO from six.moves import http_client from html5lib.inputstream import (BufferedStream, HTMLInputStream, HTMLUnicodeInputStream, HTMLBinaryInputStream) class BufferedStreamTest(unittest.TestCase): def test_basic(self): s = b"abc" fp = BufferedStream(BytesIO(s)) read = fp.read(10) assert read == s def test_read_length(self): fp = BufferedStream(BytesIO(b"abcdef")) read1 = fp.read(1) assert read1 == b"a" read2 = fp.read(2) assert read2 == b"bc" read3 = fp.read(3) assert read3 == b"def" read4 = fp.read(4) assert read4 == b"" def test_tell(self): fp = BufferedStream(BytesIO(b"abcdef")) read1 = fp.read(1) assert fp.tell() == 1 read2 = fp.read(2) assert fp.tell() == 3 read3 = fp.read(3) assert fp.tell() == 6 read4 = fp.read(4) assert fp.tell() == 6 def test_seek(self): fp = BufferedStream(BytesIO(b"abcdef")) read1 = fp.read(1) assert read1 == b"a" fp.seek(0) read2 = fp.read(1) assert read2 == b"a" read3 = fp.read(2) assert read3 == b"bc" fp.seek(2) read4 = fp.read(2) assert read4 == b"cd" fp.seek(4) read5 = fp.read(2) assert read5 == b"ef" def test_seek_tell(self): fp = BufferedStream(BytesIO(b"abcdef")) read1 = fp.read(1) assert fp.tell() == 1 fp.seek(0) read2 = fp.read(1) assert fp.tell() == 1 read3 = fp.read(2) assert fp.tell() == 3 fp.seek(2) read4 = fp.read(2) assert fp.tell() == 4 fp.seek(4) read5 = fp.read(2) assert fp.tell() == 6 class HTMLUnicodeInputStreamShortChunk(HTMLUnicodeInputStream): _defaultChunkSize = 2 class HTMLBinaryInputStreamShortChunk(HTMLBinaryInputStream): _defaultChunkSize = 2 class HTMLInputStreamTest(unittest.TestCase): def test_char_ascii(self): stream = HTMLInputStream(b"'", encoding='ascii') self.assertEqual(stream.charEncoding[0], 'ascii') self.assertEqual(stream.char(), "'") def test_char_utf8(self): stream = HTMLInputStream('\u2018'.encode('utf-8'), encoding='utf-8') self.assertEqual(stream.charEncoding[0], 'utf-8') self.assertEqual(stream.char(), '\u2018') def test_char_win1252(self): stream = HTMLInputStream("\xa9\xf1\u2019".encode('windows-1252')) self.assertEqual(stream.charEncoding[0], 'windows-1252') self.assertEqual(stream.char(), "\xa9") self.assertEqual(stream.char(), "\xf1") self.assertEqual(stream.char(), "\u2019") def test_bom(self): stream = HTMLInputStream(codecs.BOM_UTF8 + b"'") self.assertEqual(stream.charEncoding[0], 'utf-8') self.assertEqual(stream.char(), "'") def test_utf_16(self): stream = HTMLInputStream((' ' * 1025).encode('utf-16')) self.assertTrue(stream.charEncoding[0] in ['utf-16-le', 'utf-16-be'], stream.charEncoding) self.assertEqual(len(stream.charsUntil(' ', True)), 1025) def test_newlines(self): stream = HTMLBinaryInputStreamShortChunk(codecs.BOM_UTF8 + b"a\nbb\r\nccc\rddddxe") self.assertEqual(stream.position(), (1, 0)) self.assertEqual(stream.charsUntil('c'), "a\nbb\n") self.assertEqual(stream.position(), (3, 0)) self.assertEqual(stream.charsUntil('x'), "ccc\ndddd") self.assertEqual(stream.position(), (4, 4)) self.assertEqual(stream.charsUntil('e'), "x") self.assertEqual(stream.position(), (4, 5)) def test_newlines2(self): size = HTMLUnicodeInputStream._defaultChunkSize stream = HTMLInputStream("\r" * size + "\n") self.assertEqual(stream.charsUntil('x'), "\n" * size) def test_position(self): stream = HTMLBinaryInputStreamShortChunk(codecs.BOM_UTF8 + b"a\nbb\nccc\nddde\nf\ngh") self.assertEqual(stream.position(), (1, 0)) self.assertEqual(stream.charsUntil('c'), "a\nbb\n") self.assertEqual(stream.position(), (3, 0)) stream.unget("\n") self.assertEqual(stream.position(), (2, 2)) self.assertEqual(stream.charsUntil('c'), "\n") self.assertEqual(stream.position(), (3, 0)) stream.unget("\n") self.assertEqual(stream.position(), (2, 2)) self.assertEqual(stream.char(), "\n") self.assertEqual(stream.position(), (3, 0)) self.assertEqual(stream.charsUntil('e'), "ccc\nddd") self.assertEqual(stream.position(), (4, 3)) self.assertEqual(stream.charsUntil('h'), "e\nf\ng") self.assertEqual(stream.position(), (6, 1)) def test_position2(self): stream = HTMLUnicodeInputStreamShortChunk("abc\nd") self.assertEqual(stream.position(), (1, 0)) self.assertEqual(stream.char(), "a") self.assertEqual(stream.position(), (1, 1)) self.assertEqual(stream.char(), "b") self.assertEqual(stream.position(), (1, 2)) self.assertEqual(stream.char(), "c") self.assertEqual(stream.position(), (1, 3)) self.assertEqual(stream.char(), "\n") self.assertEqual(stream.position(), (2, 0)) self.assertEqual(stream.char(), "d") self.assertEqual(stream.position(), (2, 1)) def test_python_issue_20007(self): """ Make sure we have a work-around for Python bug #20007 http://bugs.python.org/issue20007 """ class FakeSocket(object): def makefile(self, _mode, _bufsize=None): return BytesIO(b"HTTP/1.1 200 Ok\r\n\r\nText") source = http_client.HTTPResponse(FakeSocket()) source.begin() stream = HTMLInputStream(source) self.assertEqual(stream.charsUntil(" "), "Text") def buildTestSuite(): return unittest.defaultTestLoader.loadTestsFromName(__name__) def main(): buildTestSuite() unittest.main() if __name__ == '__main__': main()
mpl-2.0
pkilambi/ceilometer
ceilometer/event/converter.py
2
16032
# # Copyright 2013 Rackspace Hosting. # # 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 fnmatch import os import jsonpath_rw from oslo_config import cfg from oslo_log import log from oslo_utils import timeutils import six import yaml from ceilometer.event.storage import models from ceilometer.i18n import _ OPTS = [ cfg.StrOpt('definitions_cfg_file', default="event_definitions.yaml", help="Configuration file for event definitions." ), cfg.BoolOpt('drop_unmatched_notifications', default=False, help='Drop notifications if no event definition matches. ' '(Otherwise, we convert them with just the default traits)'), cfg.MultiStrOpt('store_raw', default=[], help='Store the raw notification for select priority ' 'levels (info and/or error). By default, raw details are ' 'not captured.') ] cfg.CONF.register_opts(OPTS, group='event') LOG = log.getLogger(__name__) class EventDefinitionException(Exception): def __init__(self, message, definition_cfg): super(EventDefinitionException, self).__init__(message) self.definition_cfg = definition_cfg def __str__(self): return '%s %s: %s' % (self.__class__.__name__, self.definition_cfg, self.message) class TraitDefinition(object): def __init__(self, name, trait_cfg, plugin_manager): self.cfg = trait_cfg self.name = name type_name = trait_cfg.get('type', 'text') if 'plugin' in trait_cfg: plugin_cfg = trait_cfg['plugin'] if isinstance(plugin_cfg, six.string_types): plugin_name = plugin_cfg plugin_params = {} else: try: plugin_name = plugin_cfg['name'] except KeyError: raise EventDefinitionException( _('Plugin specified, but no plugin name supplied for ' 'trait %s') % name, self.cfg) plugin_params = plugin_cfg.get('parameters') if plugin_params is None: plugin_params = {} try: plugin_ext = plugin_manager[plugin_name] except KeyError: raise EventDefinitionException( _('No plugin named %(plugin)s available for ' 'trait %(trait)s') % dict(plugin=plugin_name, trait=name), self.cfg) plugin_class = plugin_ext.plugin self.plugin = plugin_class(**plugin_params) else: self.plugin = None if 'fields' not in trait_cfg: raise EventDefinitionException( _("Required field in trait definition not specified: " "'%s'") % 'fields', self.cfg) fields = trait_cfg['fields'] if not isinstance(fields, six.string_types): # NOTE(mdragon): if not a string, we assume a list. if len(fields) == 1: fields = fields[0] else: fields = '|'.join('(%s)' % path for path in fields) try: self.fields = jsonpath_rw.parse(fields) except Exception as e: raise EventDefinitionException( _("Parse error in JSONPath specification " "'%(jsonpath)s' for %(trait)s: %(err)s") % dict(jsonpath=fields, trait=name, err=e), self.cfg) self.trait_type = models.Trait.get_type_by_name(type_name) if self.trait_type is None: raise EventDefinitionException( _("Invalid trait type '%(type)s' for trait %(trait)s") % dict(type=type_name, trait=name), self.cfg) def _get_path(self, match): if match.context is not None: for path_element in self._get_path(match.context): yield path_element yield str(match.path) def to_trait(self, notification_body): values = [match for match in self.fields.find(notification_body) if match.value is not None] if self.plugin is not None: value_map = [('.'.join(self._get_path(match)), match.value) for match in values] value = self.plugin.trait_value(value_map) else: value = values[0].value if values else None if value is None: return None # NOTE(mdragon): some openstack projects (mostly Nova) emit '' # for null fields for things like dates. if self.trait_type != models.Trait.TEXT_TYPE and value == '': return None value = models.Trait.convert_value(self.trait_type, value) return models.Trait(self.name, self.trait_type, value) class EventDefinition(object): DEFAULT_TRAITS = dict( service=dict(type='text', fields='publisher_id'), request_id=dict(type='text', fields='_context_request_id'), tenant_id=dict(type='text', fields=['payload.tenant_id', '_context_tenant']), ) def __init__(self, definition_cfg, trait_plugin_mgr): self._included_types = [] self._excluded_types = [] self.traits = dict() self.cfg = definition_cfg self.raw_levels = [level.lower() for level in cfg.CONF.event.store_raw] try: event_type = definition_cfg['event_type'] traits = definition_cfg['traits'] except KeyError as err: raise EventDefinitionException( _("Required field %s not specified") % err.args[0], self.cfg) if isinstance(event_type, six.string_types): event_type = [event_type] for t in event_type: if t.startswith('!'): self._excluded_types.append(t[1:]) else: self._included_types.append(t) if self._excluded_types and not self._included_types: self._included_types.append('*') for trait_name in self.DEFAULT_TRAITS: self.traits[trait_name] = TraitDefinition( trait_name, self.DEFAULT_TRAITS[trait_name], trait_plugin_mgr) for trait_name in traits: self.traits[trait_name] = TraitDefinition( trait_name, traits[trait_name], trait_plugin_mgr) def included_type(self, event_type): for t in self._included_types: if fnmatch.fnmatch(event_type, t): return True return False def excluded_type(self, event_type): for t in self._excluded_types: if fnmatch.fnmatch(event_type, t): return True return False def match_type(self, event_type): return (self.included_type(event_type) and not self.excluded_type(event_type)) @property def is_catchall(self): return '*' in self._included_types and not self._excluded_types @staticmethod def _extract_when(body): """Extract the generated datetime from the notification.""" # NOTE: I am keeping the logic the same as it was in the collector, # However, *ALL* notifications should have a 'timestamp' field, it's # part of the notification envelope spec. If this was put here because # some openstack project is generating notifications without a # timestamp, then that needs to be filed as a bug with the offending # project (mdragon) when = body.get('timestamp', body.get('_context_timestamp')) if when: return timeutils.normalize_time(timeutils.parse_isotime(when)) return timeutils.utcnow() def to_event(self, notification_body): event_type = notification_body['event_type'] message_id = notification_body['message_id'] when = self._extract_when(notification_body) traits = (self.traits[t].to_trait(notification_body) for t in self.traits) # Only accept non-None value traits ... traits = [trait for trait in traits if trait is not None] raw = (notification_body if notification_body.get('priority') in self.raw_levels else {}) event = models.Event(message_id, event_type, when, traits, raw) return event class NotificationEventsConverter(object): """Notification Event Converter The NotificationEventsConverter handles the conversion of Notifications from openstack systems into Ceilometer Events. The conversion is handled according to event definitions in a config file. The config is a list of event definitions. Order is significant, a notification will be processed according to the LAST definition that matches it's event_type. (We use the last matching definition because that allows you to use YAML merge syntax in the definitions file.) Each definition is a dictionary with the following keys (all are required): - event_type: this is a list of notification event_types this definition will handle. These can be wildcarded with unix shell glob (not regex!) wildcards. An exclusion listing (starting with a '!') will exclude any types listed from matching. If ONLY exclusions are listed, the definition will match anything not matching the exclusions. This item can also be a string, which will be taken as equivalent to 1 item list. Examples: * ['compute.instance.exists'] will only match compute.intance.exists notifications * "compute.instance.exists" Same as above. * ["image.create", "image.delete"] will match image.create and image.delete, but not anything else. * "compute.instance.*" will match compute.instance.create.start but not image.upload * ['*.start','*.end', '!scheduler.*'] will match compute.instance.create.start, and image.delete.end, but NOT compute.instance.exists or scheduler.run_instance.start * '!image.*' matches any notification except image notifications. * ['*', '!image.*'] same as above. - traits: (dict) The keys are trait names, the values are the trait definitions. Each trait definition is a dictionary with the following keys: - type (optional): The data type for this trait. (as a string) Valid options are: 'text', 'int', 'float' and 'datetime', defaults to 'text' if not specified. - fields: a path specification for the field(s) in the notification you wish to extract. The paths can be specified with a dot syntax (e.g. 'payload.host') or dictionary syntax (e.g. 'payload[host]') is also supported. In either case, if the key for the field you are looking for contains special characters, like '.', it will need to be quoted (with double or single quotes) like so:: "payload.image_meta.'org.openstack__1__architecture'" The syntax used for the field specification is a variant of JSONPath, and is fairly flexible. (see: https://github.com/kennknowles/python-jsonpath-rw for more info) Specifications can be written to match multiple possible fields, the value for the trait will be derived from the matching fields that exist and have a non-null (i.e. is not None) values in the notification. By default the value will be the first such field. (plugins can alter that, if they wish) This configuration value is normally a string, for convenience, it can be specified as a list of specifications, which will be OR'ed together (a union query in jsonpath terms) - plugin (optional): (dictionary) with the following keys: - name: (string) name of a plugin to load - parameters: (optional) Dictionary of keyword args to pass to the plugin on initialization. See documentation on each plugin to see what arguments it accepts. For convenience, this value can also be specified as a string, which is interpreted as a plugin name, which will be loaded with no parameters. """ def __init__(self, events_config, trait_plugin_mgr, add_catchall=True): self.definitions = [ EventDefinition(event_def, trait_plugin_mgr) for event_def in reversed(events_config)] if add_catchall and not any(d.is_catchall for d in self.definitions): event_def = dict(event_type='*', traits={}) self.definitions.append(EventDefinition(event_def, trait_plugin_mgr)) def to_event(self, notification_body): event_type = notification_body['event_type'] message_id = notification_body['message_id'] edef = None for d in self.definitions: if d.match_type(event_type): edef = d break if edef is None: msg = (_('Dropping Notification %(type)s (uuid:%(msgid)s)') % dict(type=event_type, msgid=message_id)) if cfg.CONF.event.drop_unmatched_notifications: LOG.debug(msg) else: # If drop_unmatched_notifications is False, this should # never happen. (mdragon) LOG.error(msg) return None return edef.to_event(notification_body) def get_config_file(): config_file = cfg.CONF.event.definitions_cfg_file if not os.path.exists(config_file): config_file = cfg.CONF.find_file(config_file) return config_file def setup_events(trait_plugin_mgr): """Setup the event definitions from yaml config file.""" config_file = get_config_file() if config_file is not None: LOG.debug(_("Event Definitions configuration file: %s"), config_file) with open(config_file) as cf: config = cf.read() try: events_config = yaml.safe_load(config) except yaml.YAMLError as err: if hasattr(err, 'problem_mark'): mark = err.problem_mark errmsg = (_("Invalid YAML syntax in Event Definitions file " "%(file)s at line: %(line)s, column: %(column)s.") % dict(file=config_file, line=mark.line + 1, column=mark.column + 1)) else: errmsg = (_("YAML error reading Event Definitions file " "%(file)s") % dict(file=config_file)) LOG.error(errmsg) raise else: LOG.debug(_("No Event Definitions configuration file found!" " Using default config.")) events_config = [] LOG.info(_("Event Definitions: %s"), events_config) allow_drop = cfg.CONF.event.drop_unmatched_notifications return NotificationEventsConverter(events_config, trait_plugin_mgr, add_catchall=not allow_drop)
apache-2.0
xzhou/AppDepriv
androguard/core/analysis/sign.py
38
13670
# This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # 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 androguard.core.analysis.analysis import TAINTED_PACKAGE_CREATE, TAINTED_PACKAGE_CALL from androguard.core.bytecodes import dvm TAINTED_PACKAGE_INTERNAL_CALL = 2 FIELD_ACCESS = { "R" : 0, "W" : 1 } PACKAGE_ACCESS = { TAINTED_PACKAGE_CREATE : 0, TAINTED_PACKAGE_CALL : 1, TAINTED_PACKAGE_INTERNAL_CALL : 2 } class Sign : def __init__(self) : self.levels = {} self.hlevels = [] def add(self, level, value) : self.levels[ level ] = value self.hlevels.append( level ) def get_level(self, l) : return self.levels[ "L%d" % l ] def get_string(self) : buff = "" for i in self.hlevels : buff += self.levels[ i ] return buff def get_list(self) : return self.levels[ "sequencebb" ] class Signature : def __init__(self, vmx) : self.vmx = vmx self.tainted_packages = self.vmx.get_tainted_packages() self.tainted_variables = self.vmx.get_tainted_variables() self._cached_signatures = {} self._cached_fields = {} self._cached_packages = {} self._global_cached = {} self.levels = { # Classical method signature with basic blocks, strings, fields, packages "L0" : { 0 : ( "_get_strings_a", "_get_fields_a", "_get_packages_a" ), 1 : ( "_get_strings_pa", "_get_fields_a", "_get_packages_a" ), 2 : ( "_get_strings_a", "_get_fields_a", "_get_packages_pa_1" ), 3 : ( "_get_strings_a", "_get_fields_a", "_get_packages_pa_2" ), }, # strings "L1" : [ "_get_strings_a1" ], # exceptions "L2" : [ "_get_exceptions" ], # fill array data "L3" : [ "_get_fill_array_data" ], } self.classes_names = None self._init_caches() def _get_method_info(self, m) : m1 = m.get_method() return "%s-%s-%s" % (m1.get_class_name(), m1.get_name(), m1.get_descriptor()) def _get_sequence_bb(self, analysis_method) : l = [] for i in analysis_method.basic_blocks.get() : buff = "" instructions = [j for j in i.get_instructions()] if len(instructions) > 5 : for ins in instructions : buff += ins.get_name() if buff != "" : l.append( buff ) return l def _get_hex(self, analysis_method) : code = analysis_method.get_method().get_code() if code == None : return "" buff = "" for i in code.get_bc().get_instructions() : buff += dvm.clean_name_instruction( i ) buff += dvm.static_operand_instruction( i ) return buff def _get_bb(self, analysis_method, functions, options) : bbs = [] for b in analysis_method.basic_blocks.get() : l = [] l.append( (b.start, "B") ) l.append( (b.start, "[") ) internal = [] op_value = b.get_last().get_op_value() # return if op_value >= 0x0e and op_value <= 0x11 : internal.append( (b.end-1, "R") ) # if elif op_value >= 0x32 and op_value <= 0x3d : internal.append( (b.end-1, "I") ) # goto elif op_value >= 0x28 and op_value <= 0x2a : internal.append( (b.end-1, "G") ) # sparse or packed switch elif op_value >= 0x2b and op_value <= 0x2c : internal.append( (b.end-1, "G") ) for f in functions : try : internal.extend( getattr( self, f )( analysis_method, options ) ) except TypeError : internal.extend( getattr( self, f )( analysis_method ) ) internal.sort() for i in internal : if i[0] >= b.start and i[0] < b.end : l.append( i ) del internal l.append( (b.end, "]") ) bbs.append( ''.join(i[1] for i in l) ) return bbs def _init_caches(self) : if self._cached_fields == {} : for f_t, f in self.tainted_variables.get_fields() : self._cached_fields[ f ] = f_t.get_paths_length() n = 0 for f in sorted( self._cached_fields ) : self._cached_fields[ f ] = n n += 1 if self._cached_packages == {} : for m_t, m in self.tainted_packages.get_packages() : self._cached_packages[ m ] = m_t.get_paths_length() n = 0 for m in sorted( self._cached_packages ) : self._cached_packages[ m ] = n n += 1 def _get_fill_array_data(self, analysis_method) : buff = "" for b in analysis_method.basic_blocks.get() : for i in b.get_instructions() : if i.get_name() == "FILL-ARRAY-DATA" : buff_tmp = i.get_operands() for j in range(0, len(buff_tmp)) : buff += "\\x%02x" % ord( buff_tmp[j] ) return buff def _get_exceptions(self, analysis_method) : buff = "" method = analysis_method.get_method() code = method.get_code() if code == None or code.get_tries_size() <= 0 : return buff handler_catch_list = code.get_handlers() for handler_catch in handler_catch_list.get_list() : for handler in handler_catch.get_handlers() : buff += analysis_method.get_vm().get_cm_type( handler.get_type_idx() ) return buff def _get_strings_a1(self, analysis_method) : buff = "" strings_method = self.tainted_variables.get_strings_by_method( analysis_method.get_method() ) for s in strings_method : for path in strings_method[s] : buff += s.replace('\n', ' ') return buff def _get_strings_pa(self, analysis_method) : l = [] strings_method = self.tainted_variables.get_strings_by_method( analysis_method.get_method() ) for s in strings_method : for path in strings_method[s] : l.append( ( path[1], "S%d" % len(s) ) ) return l def _get_strings_a(self, analysis_method) : key = "SA-%s" % self._get_method_info(analysis_method) if key in self._global_cached : return self._global_cached[ key ] l = [] strings_method = self.tainted_variables.get_strings_by_method( analysis_method.get_method() ) for s in strings_method : for path in strings_method[s] : l.append( ( path[1], "S") ) self._global_cached[ key ] = l return l def _get_fields_a(self, analysis_method) : key = "FA-%s" % self._get_method_info(analysis_method) if key in self._global_cached : return self._global_cached[ key ] fields_method = self.tainted_variables.get_fields_by_method( analysis_method.get_method() ) l = [] for f in fields_method : for path in fields_method[ f ] : l.append( (path[1], "F%d" % FIELD_ACCESS[ path[0] ]) ) self._global_cached[ key ] = l return l def _get_packages_a(self, analysis_method) : packages_method = self.tainted_packages.get_packages_by_method( analysis_method.get_method() ) l = [] for m in packages_method : for path in packages_method[ m ] : l.append( (path.get_idx(), "P%s" % (PACKAGE_ACCESS[ path.get_access_flag() ]) ) ) return l def _get_packages(self, analysis_method, include_packages) : l = self._get_packages_pa_1( analysis_method, include_packages ) return "".join([ i[1] for i in l ]) def _get_packages_pa_1(self, analysis_method, include_packages) : key = "PA1-%s-%s" % (self._get_method_info(analysis_method), include_packages) if key in self._global_cached : return self._global_cached[ key ] packages_method = self.tainted_packages.get_packages_by_method( analysis_method.get_method() ) if self.classes_names == None : self.classes_names = analysis_method.get_vm().get_classes_names() l = [] for m in packages_method : for path in packages_method[ m ] : present = False for i in include_packages : if m.find(i) == 0 : present = True break if path.get_access_flag() == 1 : dst_class_name, dst_method_name, dst_descriptor = path.get_dst( analysis_method.get_vm().get_class_manager() ) if dst_class_name in self.classes_names : l.append( (path.get_idx(), "P%s" % (PACKAGE_ACCESS[ 2 ]) ) ) else : if present == True : l.append( (path.get_idx(), "P%s{%s%s%s}" % (PACKAGE_ACCESS[ path.get_access_flag() ], dst_class_name, dst_method_name, dst_descriptor ) ) ) else : l.append( (path.get_idx(), "P%s" % (PACKAGE_ACCESS[ path.get_access_flag() ]) ) ) else : if present == True : l.append( (path.get_idx(), "P%s{%s}" % (PACKAGE_ACCESS[ path.get_access_flag() ], m) ) ) else : l.append( (path.get_idx(), "P%s" % (PACKAGE_ACCESS[ path.get_access_flag() ]) ) ) self._global_cached[ key ] = l return l def _get_packages_pa_2(self, analysis_method, include_packages) : packages_method = self.tainted_packages.get_packages_by_method( analysis_method.get_method() ) l = [] for m in packages_method : for path in packages_method[ m ] : present = False for i in include_packages : if m.find(i) == 0 : present = True break if present == True : l.append( (path.get_idx(), "P%s" % (PACKAGE_ACCESS[ path.get_access_flag() ]) ) ) continue if path.get_access_flag() == 1 : dst_class_name, dst_method_name, dst_descriptor = path.get_dst( analysis_method.get_vm().get_class_manager() ) l.append( (path.get_idx(), "P%s{%s%s%s}" % (PACKAGE_ACCESS[ path.get_access_flag() ], dst_class_name, dst_method_name, dst_descriptor ) ) ) else : l.append( (path.get_idx(), "P%s{%s}" % (PACKAGE_ACCESS[ path.get_access_flag() ], m) ) ) return l def get_method(self, analysis_method, signature_type, signature_arguments={}) : key = "%s-%s-%s" % (self._get_method_info(analysis_method), signature_type, signature_arguments) if key in self._cached_signatures : return self._cached_signatures[ key ] s = Sign() #print signature_type, signature_arguments for i in signature_type.split(":") : # print i, signature_arguments[ i ] if i == "L0" : _type = self.levels[ i ][ signature_arguments[ i ][ "type" ] ] try : _arguments = signature_arguments[ i ][ "arguments" ] except KeyError : _arguments = [] value = self._get_bb( analysis_method, _type, _arguments ) s.add( i, ''.join(z for z in value) ) elif i == "L4" : try : _arguments = signature_arguments[ i ][ "arguments" ] except KeyError : _arguments = [] value = self._get_packages( analysis_method, _arguments ) s.add( i , value ) elif i == "hex" : value = self._get_hex( analysis_method ) s.add( i, value ) elif i == "sequencebb" : _type = ('_get_strings_a', '_get_fields_a', '_get_packages_pa_1') _arguments = ['Landroid', 'Ljava'] #value = self._get_bb( analysis_method, _type, _arguments ) #s.add( i, value ) value = self._get_sequence_bb( analysis_method ) s.add( i, value ) else : for f in self.levels[ i ] : value = getattr( self, f )( analysis_method ) s.add( i, value ) self._cached_signatures[ key ] = s return s
apache-2.0
UnbDroid/robomagellan
Codigos/Raspberry/desenvolvimentoRos/devel/lib/python2.7/dist-packages/geometry_msgs/msg/_Point32.py
1
3876
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from geometry_msgs/Point32.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class Point32(genpy.Message): _md5sum = "cc153912f1453b708d221682bc23d9ac" _type = "geometry_msgs/Point32" _has_header = False #flag to mark the presence of a Header object _full_text = """# This contains the position of a point in free space(with 32 bits of precision). # It is recommeded to use Point wherever possible instead of Point32. # # This recommendation is to promote interoperability. # # This message is designed to take up less space when sending # lots of points at once, as in the case of a PointCloud. float32 x float32 y float32 z""" __slots__ = ['x','y','z'] _slot_types = ['float32','float32','float32'] def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: x,y,z :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(Point32, self).__init__(*args, **kwds) #message fields cannot be None, assign default values for those that are if self.x is None: self.x = 0. if self.y is None: self.y = 0. if self.z is None: self.z = 0. else: self.x = 0. self.y = 0. self.z = 0. def _get_types(self): """ internal API method """ return self._slot_types def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: _x = self buff.write(_struct_3f.pack(_x.x, _x.y, _x.z)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize(self, str): """ unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str`` """ try: end = 0 _x = self start = end end += 12 (_x.x, _x.y, _x.z,) = _struct_3f.unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: _x = self buff.write(_struct_3f.pack(_x.x, _x.y, _x.z)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize_numpy(self, str, numpy): """ unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module """ try: end = 0 _x = self start = end end += 12 (_x.x, _x.y, _x.z,) = _struct_3f.unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill _struct_I = genpy.struct_I _struct_3f = struct.Struct("<3f")
gpl-3.0
lahwaacz/qutebrowser
tests/helpers/test_stubs.py
2
2854
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser 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. # # qutebrowser 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 qutebrowser. If not, see <http://www.gnu.org/licenses/>. """Test test stubs.""" from unittest import mock import pytest @pytest.fixture def timer(stubs): return stubs.FakeTimer() def test_timeout(timer): """Test whether timeout calls the functions.""" func = mock.Mock() func2 = mock.Mock() timer.timeout.connect(func) timer.timeout.connect(func2) assert not func.called assert not func2.called timer.timeout.emit() func.assert_called_once_with() func2.assert_called_once_with() def test_disconnect_all(timer): """Test disconnect without arguments.""" func = mock.Mock() timer.timeout.connect(func) timer.timeout.disconnect() timer.timeout.emit() assert not func.called def test_disconnect_one(timer): """Test disconnect with a single argument.""" func = mock.Mock() timer.timeout.connect(func) timer.timeout.disconnect(func) timer.timeout.emit() assert not func.called def test_disconnect_all_invalid(timer): """Test disconnecting with no connections.""" with pytest.raises(TypeError): timer.timeout.disconnect() def test_disconnect_one_invalid(timer): """Test disconnecting with an invalid connection.""" func1 = mock.Mock() func2 = mock.Mock() timer.timeout.connect(func1) with pytest.raises(TypeError): timer.timeout.disconnect(func2) assert not func1.called assert not func2.called timer.timeout.emit() func1.assert_called_once_with() def test_singleshot(timer): """Test setting singleShot.""" assert not timer.isSingleShot() timer.setSingleShot(True) assert timer.isSingleShot() timer.start() assert timer.isActive() timer.timeout.emit() assert not timer.isActive() def test_active(timer): """Test isActive.""" assert not timer.isActive() timer.start() assert timer.isActive() timer.stop() assert not timer.isActive() def test_interval(timer): """Test setting an interval.""" assert timer.interval() == 0 timer.setInterval(1000) assert timer.interval() == 1000
gpl-3.0
radicalbit/ambari
ambari-server/src/test/python/stacks/2.2/common/test_stack_advisor_perf.py
1
3190
''' 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 json import os import time import imp from unittest import TestCase from mock.mock import patch class TestHDP22StackAdvisor(TestCase): def instantiate_stack_advisor(self, testDirectory): default_stack_advisor_path = os.path.join(testDirectory, '../../../../../main/resources/stacks/stack_advisor.py') hdp_206_stack_advisor_path = os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') hdp_21_stack_advisor_path = os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.1/services/stack_advisor.py') hdp_22_stack_advisor_path = os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.2/services/stack_advisor.py') hdp_206_stack_advisor_classname = 'HDP206StackAdvisor' with open(default_stack_advisor_path, 'rb') as fp: imp.load_module('stack_advisor', fp, default_stack_advisor_path, ('.py', 'rb', imp.PY_SOURCE)) with open(hdp_206_stack_advisor_path, 'rb') as fp: imp.load_module('stack_advisor_impl', fp, hdp_206_stack_advisor_path, ('.py', 'rb', imp.PY_SOURCE)) with open(hdp_21_stack_advisor_path, 'rb') as fp: imp.load_module('stack_advisor_impl', fp, hdp_21_stack_advisor_path, ('.py', 'rb', imp.PY_SOURCE)) with open(hdp_22_stack_advisor_path, 'rb') as fp: stack_advisor_impl = imp.load_module('stack_advisor_impl', fp, hdp_22_stack_advisor_path, ('.py', 'rb', imp.PY_SOURCE)) clazz = getattr(stack_advisor_impl, hdp_206_stack_advisor_classname) return clazz() @patch('socket.getfqdn') def test_performance(self, getfqdn_method): getfqdn_method.side_effect = lambda host='perf400-a-1.c.pramod-thangali.internal': host testDirectory = os.path.dirname(os.path.abspath(__file__)) current_stack_advisor_path = os.path.join(testDirectory, '../../../../../main/resources/stacks/stack_advisor.py') for folder_name in ['1', '2']: services = json.load(open(os.path.join(testDirectory, folder_name + '/services.json'))) hosts = json.load(open(os.path.join(testDirectory, folder_name + '/hosts.json'))) stack_advisor = self.instantiate_stack_advisor(testDirectory) start = time.time() recommendation = stack_advisor.recommendComponentLayout(services, hosts) time_taken = time.time() - start print "time taken by current stack_advisor.py = " + str(time_taken) self.assertTrue(time_taken < 0.1)
apache-2.0
mpasternak/michaldtz-fixes-518-522
tests/window/WINDOW_SET_VSYNC.py
29
2009
#!/usr/bin/env python '''Test that vsync can be set. Expected behaviour: A window will alternate between red and green fill. - Press "v" to toggle vsync on/off. "Tearing" should only be visible when vsync is off (as indicated at the terminal). Not all video drivers support vsync. On Linux, check the output of `tools/info.py`: - If GLX_SGI_video_sync extension is present, should work as expected. - If GLX_MESA_swap_control extension is present, should work as expected. - If GLX_SGI_swap_control extension is present, vsync can be enabled, but once enabled, it cannot be switched off (there will be no error message). - If none of these extensions are present, vsync is not supported by your driver, but no error message or warning will be printed. 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 from pyglet.gl import * class WINDOW_SET_VSYNC(unittest.TestCase): colors = [(1, 0, 0, 1), (0, 1, 0, 1)] color_index = 0 def open_window(self): return window.Window(200, 200, vsync=False) def on_key_press(self, symbol, modifiers): if symbol == key.V: vsync = not self.w1.vsync self.w1.set_vsync(vsync) print 'vsync is %r' % self.w1.vsync def draw_window(self, window, colour): window.switch_to() glClearColor(*colour) glClear(GL_COLOR_BUFFER_BIT) window.flip() def test_open_window(self): self.w1 = self.open_window() self.w1.push_handlers(self) print 'vsync is %r' % self.w1.vsync while not self.w1.has_exit: self.color_index = 1 - self.color_index self.draw_window(self.w1, self.colors[self.color_index]) self.w1.dispatch_events() self.w1.close() if __name__ == '__main__': unittest.main()
bsd-3-clause
gabisurita/kinto-codegen-tutorial
python-client/test/test_inline_response_200.py
1
2249
# coding: utf-8 """ kinto Kinto is a minimalist JSON storage service with synchronisation and sharing abilities. It is meant to be easy to use and easy to self-host. **Limitations of this OpenAPI specification:** 1. Validation on OR clauses is not supported (e.g. provide `data` or `permissions` in patch operations). 2. [Filtering](http://kinto.readthedocs.io/en/stable/api/1.x/filtering.html) is supported on any field by using `?{prefix}{field_name}={value}`. 3. [Backoff headers](http://kinto.readthedocs.io/en/stable/api/1.x/backoff.html) may occur with any response, but they are only present if the server is under in heavy load, so we cannot validate them on every request. They are listed only on the default error message. 4. [Collection schemas](http://kinto.readthedocs.io/en/stable/api/1.x/collections.html#collection-json-schema) can be provided when defining a collection, but they are not validated by this specification. OpenAPI spec version: 1.13 Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from __future__ import absolute_import import os import sys import unittest import swagger_client from swagger_client.rest import ApiException from swagger_client.models.inline_response_200 import InlineResponse200 class TestInlineResponse200(unittest.TestCase): """ InlineResponse200 unit test stubs """ def setUp(self): pass def tearDown(self): pass def testInlineResponse200(self): """ Test InlineResponse200 """ model = swagger_client.models.inline_response_200.InlineResponse200() if __name__ == '__main__': unittest.main()
mit
jlegendary/opencog
tests/python/blending_test/test_conceptual_blending_base.py
4
6851
__author__ = 'DongMin Kim' from opencog.atomspace import * # Only run the unit tests if the required dependencies have been installed # (see: https://github.com/opencog/opencog/issues/337) try: __import__("nose.tools") except ImportError: import unittest raise unittest.SkipTest( "ImportError exception: " + "Can't find Nose. " + "make sure the required dependencies are installed." ) else: # noinspection PyPackageRequirements from nose.tools import * try: __import__("opencog.scheme_wrapper") except ImportError: import unittest raise unittest.SkipTest( "ImportError exception: " + "Can't find Scheme wrapper for Python. " + "make sure the required dependencies are installed." ) else: from opencog.scheme_wrapper import * try: __import__("blending.blend") except ImportError: import unittest raise unittest.SkipTest( "ImportError exception: " + "Can't find Python Conceptual Blender. " + "make sure the required dependencies are installed." ) else: from blending.blend import ConceptualBlending try: from blending.util.py_cog_execute import PyCogExecute PyCogExecute().load_scheme() except (ImportError, RuntimeError): import unittest raise unittest.SkipTest( "Can't load Scheme." + "make sure the you installed atomspace to /usr/local/share/opencog." ) # noinspection PyArgumentList, PyTypeChecker class TestConceptualBlendingBase(object): """ Unit tests for the OpenCog ConceptualBlending. Attributes: :type a: opencog.atomspace_details.AtomSpace """ __test__ = False def __init__(self): self.a = AtomSpace() self.blender = None self.sample_nodes = dict() # noinspection PyPep8Naming def setUp(self): """This method is run once before _each_ test method is executed""" self.blender = ConceptualBlending(self.a) """ Make test nodes. """ # Nodes will be blended: self.sample_nodes["car"] = self.a.add_node(types.ConceptNode, "car") self.sample_nodes["man"] = self.a.add_node(types.ConceptNode, "man") # A. Car is metal. (Not duplicated) self.sample_nodes["metal"] = self.a.add_node(types.ConceptNode, "metal") # B. Car moves, man moves. (Duplicated, not conflicted) self.sample_nodes["move"] = self.a.add_node(types.ConceptNode, "move") # C.1. Car is vehicle, man is not vehicle. (Duplicated and conflicted) # C.2. Car is not person, man is person. (Duplicated and conflicted) self.sample_nodes["vehicle"] = self.a.add_node( types.ConceptNode, "vehicle" ) self.sample_nodes["person"] = self.a.add_node( types.ConceptNode, "person" ) """ Give some stimulates. """ self.a.set_av(self.sample_nodes["car"].h, 19) self.a.set_av(self.sample_nodes["man"].h, 18) self.a.set_av(self.sample_nodes["metal"].h, 2) self.a.set_av(self.sample_nodes["move"].h, 1) self.a.set_av(self.sample_nodes["vehicle"].h, 13) self.a.set_av(self.sample_nodes["person"].h, 12) """ Make test links. """ # A. Not duplicated link. l1 = self.a.add_link( types.MemberLink, [ self.sample_nodes["car"], self.sample_nodes["metal"] ] ) self.a.set_tv(l1.h, TruthValue(0.6, 0.8)) # B. Duplicated, not conflicted link. l2 = self.a.add_link( types.SimilarityLink, [ self.sample_nodes["car"], self.sample_nodes["move"] ] ) l3 = self.a.add_link( types.SimilarityLink, [ self.sample_nodes["man"], self.sample_nodes["move"] ] ) self.a.set_tv(l2.h, TruthValue(0.9, 0.8)) self.a.set_tv(l3.h, TruthValue(0.7, 0.9)) # C.1 Duplicated, conflicted link. l4 = self.a.add_link( types.SimilarityLink, [ self.sample_nodes["car"], self.sample_nodes["vehicle"] ] ) l5 = self.a.add_link( types.SimilarityLink, [ self.sample_nodes["man"], self.sample_nodes["vehicle"] ] ) self.a.set_tv(l4.h, TruthValue(0.9, 0.8)) self.a.set_tv(l5.h, TruthValue(0.1, 0.9)) # C.2 Duplicated, conflicted link. l6 = self.a.add_link( types.SimilarityLink, [ self.sample_nodes["car"], self.sample_nodes["person"] ] ) l7 = self.a.add_link( types.SimilarityLink, [ self.sample_nodes["man"], self.sample_nodes["person"] ] ) self.a.set_tv(l6.h, TruthValue(0.1, 0.8)) self.a.set_tv(l7.h, TruthValue(0.8, 0.9)) """ Make default configs. """ self.a.add_link( types.InheritanceLink, [ self.a.add_node(types.ConceptNode, "default-config"), self.a.add_node(types.ConceptNode, "BLEND") ] ) self.a.add_link( types.ExecutionLink, [ self.a.add_node(types.SchemaNode, "BLEND:atoms-chooser"), self.a.add_node(types.ConceptNode, "default-config"), self.a.add_node(types.ConceptNode, "ChooseNull") ] ) self.a.add_link( types.ExecutionLink, [ self.a.add_node(types.SchemaNode, "BLEND:blending-decider"), self.a.add_node(types.ConceptNode, "default-config"), self.a.add_node(types.ConceptNode, "DecideNull") ] ) self.a.add_link( types.ExecutionLink, [ self.a.add_node(types.SchemaNode, "BLEND:new-blend-atom-maker"), self.a.add_node(types.ConceptNode, "default-config"), self.a.add_node(types.ConceptNode, "MakeSimple") ] ) self.a.add_link( types.ExecutionLink, [ self.a.add_node(types.SchemaNode, "BLEND:link-connector"), self.a.add_node(types.ConceptNode, "default-config"), self.a.add_node(types.ConceptNode, "ConnectSimple") ] ) # noinspection PyPep8Naming def tearDown(self): """This method is run once after _each_ test method is executed""" self.a.clear() del self.sample_nodes del self.blender
agpl-3.0
nerzhul/ansible
lib/ansible/module_utils/api.py
106
3560
# # (c) 2015 Brian Ccoa, <bcoca@ansible.com> # # 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 module adds shared support for generic api modules In order to use this module, include it as part of a custom module as shown below. ** Note: The order of the import statements does matter. ** from ansible.module_utils.basic import * from ansible.module_utils.api import * The 'api' module provides the following common argument specs: * rate limit spec - rate: number of requests per time unit (int) - rate_limit: time window in which the limit is applied in seconds * retry spec - retries: number of attempts - retry_pause: delay between attempts in seconds """ import time def rate_limit_argument_spec(spec=None): """Creates an argument spec for working with rate limiting""" arg_spec = (dict( rate=dict(type='int'), rate_limit=dict(type='int'), )) if spec: arg_spec.update(spec) return arg_spec def retry_argument_spec(spec=None): """Creates an argument spec for working with retrying""" arg_spec = (dict( retries=dict(type='int'), retry_pause=dict(type='float', default=1), )) if spec: arg_spec.update(spec) return arg_spec def basic_auth_argument_spec(spec=None): arg_spec = (dict( api_username=dict(type='str', required=False), api_password=dict(type='str', required=False, no_log=True), api_url=dict(type='str', required=False), validate_certs=dict(type='bool', default=True) )) if spec: arg_spec.update(spec) return arg_spec def rate_limit(rate=None, rate_limit=None): """rate limiting decorator""" minrate = None if rate is not None and rate_limit is not None: minrate = float(rate_limit) / float(rate) def wrapper(f): last = [0.0] def ratelimited(*args,**kwargs): if minrate is not None: elapsed = time.clock() - last[0] left = minrate - elapsed if left > 0: time.sleep(left) last[0] = time.clock() ret = f(*args,**kwargs) return ret return ratelimited return wrapper def retry(retries=None, retry_pause=1): """Retry decorator""" def wrapper(f): retry_count = 0 def retried(*args,**kwargs): if retries is not None: ret = None while True: retry_count += 1 if retry_count >= retries: raise Exception("Retry limit exceeded: %d" % retries) try: ret = f(*args,**kwargs) except: pass if ret: break time.sleep(retry_pause) return ret return retried return wrapper
gpl-3.0
tboyce021/home-assistant
homeassistant/components/wink/lock.py
9
6584
"""Support for Wink locks.""" import pywink import voluptuous as vol from homeassistant.components.lock import LockEntity from homeassistant.const import ( ATTR_CODE, ATTR_ENTITY_ID, ATTR_MODE, ATTR_NAME, STATE_UNKNOWN, ) import homeassistant.helpers.config_validation as cv from . import DOMAIN, WinkDevice SERVICE_SET_VACATION_MODE = "set_lock_vacation_mode" SERVICE_SET_ALARM_MODE = "set_lock_alarm_mode" SERVICE_SET_ALARM_SENSITIVITY = "set_lock_alarm_sensitivity" SERVICE_SET_ALARM_STATE = "set_lock_alarm_state" SERVICE_SET_BEEPER_STATE = "set_lock_beeper_state" SERVICE_ADD_KEY = "add_new_lock_key_code" ATTR_ENABLED = "enabled" ATTR_SENSITIVITY = "sensitivity" ALARM_SENSITIVITY_MAP = { "low": 0.2, "medium_low": 0.4, "medium": 0.6, "medium_high": 0.8, "high": 1.0, } ALARM_MODES_MAP = { "activity": "alert", "forced_entry": "forced_entry", "tamper": "tamper", } SET_ENABLED_SCHEMA = vol.Schema( {vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Required(ATTR_ENABLED): cv.string} ) SET_SENSITIVITY_SCHEMA = vol.Schema( { vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Required(ATTR_SENSITIVITY): vol.In(ALARM_SENSITIVITY_MAP), } ) SET_ALARM_MODES_SCHEMA = vol.Schema( { vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Required(ATTR_MODE): vol.In(ALARM_MODES_MAP), } ) ADD_KEY_SCHEMA = vol.Schema( { vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Required(ATTR_NAME): cv.string, vol.Required(ATTR_CODE): cv.positive_int, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Wink platform.""" for lock in pywink.get_locks(): _id = lock.object_id() + lock.name() if _id not in hass.data[DOMAIN]["unique_ids"]: add_entities([WinkLockDevice(lock, hass)]) def service_handle(service): """Handle for services.""" entity_ids = service.data.get("entity_id") all_locks = hass.data[DOMAIN]["entities"]["lock"] locks_to_set = [] if entity_ids is None: locks_to_set = all_locks else: for lock in all_locks: if lock.entity_id in entity_ids: locks_to_set.append(lock) for lock in locks_to_set: if service.service == SERVICE_SET_VACATION_MODE: lock.set_vacation_mode(service.data.get(ATTR_ENABLED)) elif service.service == SERVICE_SET_ALARM_STATE: lock.set_alarm_state(service.data.get(ATTR_ENABLED)) elif service.service == SERVICE_SET_BEEPER_STATE: lock.set_beeper_state(service.data.get(ATTR_ENABLED)) elif service.service == SERVICE_SET_ALARM_MODE: lock.set_alarm_mode(service.data.get(ATTR_MODE)) elif service.service == SERVICE_SET_ALARM_SENSITIVITY: lock.set_alarm_sensitivity(service.data.get(ATTR_SENSITIVITY)) elif service.service == SERVICE_ADD_KEY: name = service.data.get(ATTR_NAME) code = service.data.get(ATTR_CODE) lock.add_new_key(code, name) hass.services.register( DOMAIN, SERVICE_SET_VACATION_MODE, service_handle, schema=SET_ENABLED_SCHEMA ) hass.services.register( DOMAIN, SERVICE_SET_ALARM_STATE, service_handle, schema=SET_ENABLED_SCHEMA ) hass.services.register( DOMAIN, SERVICE_SET_BEEPER_STATE, service_handle, schema=SET_ENABLED_SCHEMA ) hass.services.register( DOMAIN, SERVICE_SET_ALARM_MODE, service_handle, schema=SET_ALARM_MODES_SCHEMA ) hass.services.register( DOMAIN, SERVICE_SET_ALARM_SENSITIVITY, service_handle, schema=SET_SENSITIVITY_SCHEMA, ) hass.services.register( DOMAIN, SERVICE_ADD_KEY, service_handle, schema=ADD_KEY_SCHEMA ) class WinkLockDevice(WinkDevice, LockEntity): """Representation of a Wink lock.""" async def async_added_to_hass(self): """Call when entity is added to hass.""" self.hass.data[DOMAIN]["entities"]["lock"].append(self) @property def is_locked(self): """Return true if device is locked.""" return self.wink.state() def lock(self, **kwargs): """Lock the device.""" self.wink.set_state(True) def unlock(self, **kwargs): """Unlock the device.""" self.wink.set_state(False) def set_alarm_state(self, enabled): """Set lock's alarm state.""" self.wink.set_alarm_state(enabled) def set_vacation_mode(self, enabled): """Set lock's vacation mode.""" self.wink.set_vacation_mode(enabled) def set_beeper_state(self, enabled): """Set lock's beeper mode.""" self.wink.set_beeper_mode(enabled) def add_new_key(self, code, name): """Add a new user key code.""" self.wink.add_new_key(code, name) def set_alarm_sensitivity(self, sensitivity): """ Set lock's alarm sensitivity. Valid sensitivities: 0.2, 0.4, 0.6, 0.8, 1.0 """ self.wink.set_alarm_sensitivity(sensitivity) def set_alarm_mode(self, mode): """ Set lock's alarm mode. Valid modes: alert - Beep when lock is locked or unlocked tamper - 15 sec alarm when lock is disturbed when locked forced_entry - 3 min alarm when significant force applied to door when locked. """ self.wink.set_alarm_mode(mode) @property def device_state_attributes(self): """Return the state attributes.""" super_attrs = super().device_state_attributes sensitivity = dict_value_to_key( ALARM_SENSITIVITY_MAP, self.wink.alarm_sensitivity() ) super_attrs["alarm_sensitivity"] = sensitivity super_attrs["vacation_mode"] = self.wink.vacation_mode_enabled() super_attrs["beeper_mode"] = self.wink.beeper_enabled() super_attrs["auto_lock"] = self.wink.auto_lock_enabled() alarm_mode = dict_value_to_key(ALARM_MODES_MAP, self.wink.alarm_mode()) super_attrs["alarm_mode"] = alarm_mode super_attrs["alarm_enabled"] = self.wink.alarm_enabled() return super_attrs def dict_value_to_key(dict_map, comp_value): """Return the key that has the provided value.""" for key, value in dict_map.items(): if value == comp_value: return key return STATE_UNKNOWN
apache-2.0
NeuralEnsemble/neuroConstruct
lib/jython/Lib/test/test_userdict.py
23
13413
# Check every path through every method of UserDict import test.test_support, unittest from sets import Set import UserDict class TestMappingProtocol(unittest.TestCase): # This base class can be used to check that an object conforms to the # mapping protocol # Functions that can be useful to override to adapt to dictionary # semantics _tested_class = dict # which class is being tested def _reference(self): """Return a dictionary of values which are invariant by storage in the object under test.""" return {1:2, "key1":"value1", "key2":(1,2,3)} def _empty_mapping(self): """Return an empty mapping object""" return self._tested_class() def _full_mapping(self, data): """Return a mapping object with the value contained in data dictionary""" x = self._empty_mapping() for key, value in data.items(): x[key] = value return x def __init__(self, *args, **kw): unittest.TestCase.__init__(self, *args, **kw) self.reference = self._reference().copy() key, value = self.reference.popitem() self.other = {key:value} def test_read(self): # Test for read only operations on mapping p = self._empty_mapping() p1 = dict(p) #workaround for singleton objects d = self._full_mapping(self.reference) if d is p: p = p1 #Indexing for key, value in self.reference.items(): self.assertEqual(d[key], value) knownkey = self.other.keys()[0] self.failUnlessRaises(KeyError, lambda:d[knownkey]) #len self.assertEqual(len(p), 0) self.assertEqual(len(d), len(self.reference)) #has_key for k in self.reference: self.assert_(d.has_key(k)) self.assert_(k in d) for k in self.other: self.failIf(d.has_key(k)) self.failIf(k in d) #cmp self.assertEqual(cmp(p,p), 0) self.assertEqual(cmp(d,d), 0) self.assertEqual(cmp(p,d), -1) self.assertEqual(cmp(d,p), 1) #__non__zero__ if p: self.fail("Empty mapping must compare to False") if not d: self.fail("Full mapping must compare to True") # keys(), items(), iterkeys() ... def check_iterandlist(iter, lst, ref): self.assert_(hasattr(iter, 'next')) self.assert_(hasattr(iter, '__iter__')) x = list(iter) self.assert_(Set(x)==Set(lst)==Set(ref)) check_iterandlist(d.iterkeys(), d.keys(), self.reference.keys()) check_iterandlist(iter(d), d.keys(), self.reference.keys()) check_iterandlist(d.itervalues(), d.values(), self.reference.values()) check_iterandlist(d.iteritems(), d.items(), self.reference.items()) #get key, value = d.iteritems().next() knownkey, knownvalue = self.other.iteritems().next() self.assertEqual(d.get(key, knownvalue), value) self.assertEqual(d.get(knownkey, knownvalue), knownvalue) self.failIf(knownkey in d) def test_write(self): # Test for write operations on mapping p = self._empty_mapping() #Indexing for key, value in self.reference.items(): p[key] = value self.assertEqual(p[key], value) for key in self.reference.keys(): del p[key] self.failUnlessRaises(KeyError, lambda:p[key]) p = self._empty_mapping() #update p.update(self.reference) self.assertEqual(dict(p), self.reference) d = self._full_mapping(self.reference) #setdefaullt key, value = d.iteritems().next() knownkey, knownvalue = self.other.iteritems().next() self.assertEqual(d.setdefault(key, knownvalue), value) self.assertEqual(d[key], value) self.assertEqual(d.setdefault(knownkey, knownvalue), knownvalue) self.assertEqual(d[knownkey], knownvalue) #pop self.assertEqual(d.pop(knownkey), knownvalue) self.failIf(knownkey in d) self.assertRaises(KeyError, d.pop, knownkey) default = 909 d[knownkey] = knownvalue self.assertEqual(d.pop(knownkey, default), knownvalue) self.failIf(knownkey in d) self.assertEqual(d.pop(knownkey, default), default) #popitem key, value = d.popitem() self.failIf(key in d) self.assertEqual(value, self.reference[key]) p=self._empty_mapping() self.assertRaises(KeyError, p.popitem) d0 = {} d1 = {"one": 1} d2 = {"one": 1, "two": 2} d3 = {"one": 1, "two": 3, "three": 5} d4 = {"one": None, "two": None} d5 = {"one": 1, "two": 1} class UserDictTest(TestMappingProtocol): _tested_class = UserDict.IterableUserDict def test_all(self): # Test constructors u = UserDict.UserDict() u0 = UserDict.UserDict(d0) u1 = UserDict.UserDict(d1) u2 = UserDict.IterableUserDict(d2) uu = UserDict.UserDict(u) uu0 = UserDict.UserDict(u0) uu1 = UserDict.UserDict(u1) uu2 = UserDict.UserDict(u2) # keyword arg constructor self.assertEqual(UserDict.UserDict(one=1, two=2), d2) # item sequence constructor self.assertEqual(UserDict.UserDict([('one',1), ('two',2)]), d2) self.assertEqual(UserDict.UserDict(dict=[('one',1), ('two',2)]), d2) # both together self.assertEqual(UserDict.UserDict([('one',1), ('two',2)], two=3, three=5), d3) # alternate constructor self.assertEqual(UserDict.UserDict.fromkeys('one two'.split()), d4) self.assertEqual(UserDict.UserDict().fromkeys('one two'.split()), d4) self.assertEqual(UserDict.UserDict.fromkeys('one two'.split(), 1), d5) self.assertEqual(UserDict.UserDict().fromkeys('one two'.split(), 1), d5) self.assert_(u1.fromkeys('one two'.split()) is not u1) self.assert_(isinstance(u1.fromkeys('one two'.split()), UserDict.UserDict)) self.assert_(isinstance(u2.fromkeys('one two'.split()), UserDict.IterableUserDict)) # Test __repr__ # zyasoft - the below is not necessarily true, we cannot # depend on the ordering of how the string is constructed; # unless we require that it be sorted, or otherwise ordered in # some consistent fashion # for repr, we can use eval, so that's what we will do here # self.assertEqual(str(u0), str(d0)) # self.assertEqual(repr(u1), repr(d1)) # self.assertEqual(`u2`, `d2`) self.assertEqual(eval(repr(u1)), eval(repr(d1))) self.assertEqual(eval(`u2`), eval(`d2`)) # end zyasoft ~ # Test __cmp__ and __len__ all = [d0, d1, d2, u, u0, u1, u2, uu, uu0, uu1, uu2] for a in all: for b in all: self.assertEqual(cmp(a, b), cmp(len(a), len(b))) # Test __getitem__ self.assertEqual(u2["one"], 1) self.assertRaises(KeyError, u1.__getitem__, "two") # Test __setitem__ u3 = UserDict.UserDict(u2) u3["two"] = 2 u3["three"] = 3 # Test __delitem__ del u3["three"] self.assertRaises(KeyError, u3.__delitem__, "three") # Test clear u3.clear() self.assertEqual(u3, {}) # Test copy() u2a = u2.copy() self.assertEqual(u2a, u2) u2b = UserDict.UserDict(x=42, y=23) u2c = u2b.copy() # making a copy of a UserDict is special cased self.assertEqual(u2b, u2c) class MyUserDict(UserDict.UserDict): def display(self): print self m2 = MyUserDict(u2) m2a = m2.copy() self.assertEqual(m2a, m2) # SF bug #476616 -- copy() of UserDict subclass shared data m2['foo'] = 'bar' self.assertNotEqual(m2a, m2) # zyasoft - changed the following three assertions to use sets # to remove order dependency # Test keys, items, values self.assertEqual(set(u2.keys()), set(d2.keys())) self.assertEqual(set(u2.items()), set(d2.items())) self.assertEqual(set(u2.values()), set(d2.values())) # Test has_key and "in". for i in u2.keys(): self.assert_(u2.has_key(i)) self.assert_(i in u2) self.assertEqual(u1.has_key(i), d1.has_key(i)) self.assertEqual(i in u1, i in d1) self.assertEqual(u0.has_key(i), d0.has_key(i)) self.assertEqual(i in u0, i in d0) # Test update t = UserDict.UserDict() t.update(u2) self.assertEqual(t, u2) class Items: def items(self): return (("x", 42), ("y", 23)) t = UserDict.UserDict() t.update(Items()) self.assertEqual(t, {"x": 42, "y": 23}) # Test get for i in u2.keys(): self.assertEqual(u2.get(i), u2[i]) self.assertEqual(u1.get(i), d1.get(i)) self.assertEqual(u0.get(i), d0.get(i)) # Test "in" iteration. for i in xrange(20): u2[i] = str(i) ikeys = [] for k in u2: ikeys.append(k) keys = u2.keys() self.assertEqual(Set(ikeys), Set(keys)) # Test setdefault t = UserDict.UserDict() self.assertEqual(t.setdefault("x", 42), 42) self.assert_(t.has_key("x")) self.assertEqual(t.setdefault("x", 23), 42) # Test pop t = UserDict.UserDict(x=42) self.assertEqual(t.pop("x"), 42) self.assertRaises(KeyError, t.pop, "x") self.assertEqual(t.pop("x", 1), 1) t["x"] = 42 self.assertEqual(t.pop("x", 1), 42) # Test popitem t = UserDict.UserDict(x=42) self.assertEqual(t.popitem(), ("x", 42)) self.assertRaises(KeyError, t.popitem) ########################## # Test Dict Mixin class SeqDict(UserDict.DictMixin): """Dictionary lookalike implemented with lists. Used to test and demonstrate DictMixin """ def __init__(self): self.keylist = [] self.valuelist = [] def __getitem__(self, key): try: i = self.keylist.index(key) except ValueError: raise KeyError return self.valuelist[i] def __setitem__(self, key, value): try: i = self.keylist.index(key) self.valuelist[i] = value except ValueError: self.keylist.append(key) self.valuelist.append(value) def __delitem__(self, key): try: i = self.keylist.index(key) except ValueError: raise KeyError self.keylist.pop(i) self.valuelist.pop(i) def keys(self): return list(self.keylist) class UserDictMixinTest(TestMappingProtocol): _tested_class = SeqDict def test_all(self): ## Setup test and verify working of the test class # check init s = SeqDict() # exercise setitem s[10] = 'ten' s[20] = 'twenty' s[30] = 'thirty' # exercise delitem del s[20] # check getitem and setitem self.assertEqual(s[10], 'ten') # check keys() and delitem self.assertEqual(s.keys(), [10, 30]) ## Now, test the DictMixin methods one by one # has_key self.assert_(s.has_key(10)) self.assert_(not s.has_key(20)) # __contains__ self.assert_(10 in s) self.assert_(20 not in s) # __iter__ self.assertEqual([k for k in s], [10, 30]) # __len__ self.assertEqual(len(s), 2) # iteritems self.assertEqual(list(s.iteritems()), [(10,'ten'), (30, 'thirty')]) # iterkeys self.assertEqual(list(s.iterkeys()), [10, 30]) # itervalues self.assertEqual(list(s.itervalues()), ['ten', 'thirty']) # values self.assertEqual(s.values(), ['ten', 'thirty']) # items self.assertEqual(s.items(), [(10,'ten'), (30, 'thirty')]) # get self.assertEqual(s.get(10), 'ten') self.assertEqual(s.get(15,'fifteen'), 'fifteen') self.assertEqual(s.get(15), None) # setdefault self.assertEqual(s.setdefault(40, 'forty'), 'forty') self.assertEqual(s.setdefault(10, 'null'), 'ten') del s[40] # pop self.assertEqual(s.pop(10), 'ten') self.assert_(10 not in s) s[10] = 'ten' self.assertEqual(s.pop("x", 1), 1) s["x"] = 42 self.assertEqual(s.pop("x", 1), 42) # popitem k, v = s.popitem() self.assert_(k not in s) s[k] = v # clear s.clear() self.assertEqual(len(s), 0) # empty popitem self.assertRaises(KeyError, s.popitem) # update s.update({10: 'ten', 20:'twenty'}) self.assertEqual(s[10], 'ten') self.assertEqual(s[20], 'twenty') # cmp self.assertEqual(s, {10: 'ten', 20:'twenty'}) t = SeqDict() t[20] = 'twenty' t[10] = 'ten' self.assertEqual(s, t) def test_main(): test.test_support.run_unittest( TestMappingProtocol, UserDictTest, UserDictMixinTest ) if __name__ == "__main__": test_main()
gpl-2.0
philetus/geosolver
workbench/ui_prefViews.py
1
18004
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'prefviews.ui' # # Created: Mon Oct 15 21:18:35 2007 # by: PyQt4 UI code generator 4.2 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_viewsForm(object): def setupUi(self, viewsForm): viewsForm.setObjectName("viewsForm") viewsForm.resize(QtCore.QSize(QtCore.QRect(0,0,439,453).size()).expandedTo(viewsForm.minimumSizeHint())) self.tabWidget = QtGui.QTabWidget(viewsForm) self.tabWidget.setGeometry(QtCore.QRect(9,9,421,431)) self.tabWidget.setTabPosition(QtGui.QTabWidget.North) self.tabWidget.setTabShape(QtGui.QTabWidget.Rounded) self.tabWidget.setObjectName("tabWidget") self.compositionTab = QtGui.QWidget() self.compositionTab.setObjectName("compositionTab") self.treeGroupBox = QtGui.QGroupBox(self.compositionTab) self.treeGroupBox.setGeometry(QtCore.QRect(10,60,399,150)) self.treeGroupBox.setMaximumSize(QtCore.QSize(16777215,150)) self.treeGroupBox.setObjectName("treeGroupBox") self.label = QtGui.QLabel(self.treeGroupBox) self.label.setGeometry(QtCore.QRect(11,48,151,22)) font = QtGui.QFont() font.setPointSize(9) font.setWeight(75) font.setBold(True) self.label.setFont(font) self.label.setObjectName("label") self.alignTreeComboBox = QtGui.QComboBox(self.treeGroupBox) self.alignTreeComboBox.setGeometry(QtCore.QRect(120,50,93,22)) self.alignTreeComboBox.setMaximumSize(QtCore.QSize(100,16777215)) self.alignTreeComboBox.setObjectName("alignTreeComboBox") self.radioConnectionButton = QtGui.QRadioButton(self.treeGroupBox) self.radioConnectionButton.setGeometry(QtCore.QRect(120,90,56,23)) self.radioConnectionButton.setMinimumSize(QtCore.QSize(0,0)) self.radioConnectionButton.setObjectName("radioConnectionButton") self.label_2 = QtGui.QLabel(self.treeGroupBox) self.label_2.setGeometry(QtCore.QRect(10,80,85,41)) font = QtGui.QFont() font.setPointSize(9) font.setWeight(75) font.setBold(True) self.label_2.setFont(font) self.label_2.setObjectName("label_2") self.radioCurvedButton = QtGui.QRadioButton(self.treeGroupBox) self.radioCurvedButton.setGeometry(QtCore.QRect(190,90,67,23)) self.radioCurvedButton.setMinimumSize(QtCore.QSize(0,0)) self.radioCurvedButton.setObjectName("radioCurvedButton") self.label_10 = QtGui.QLabel(self.compositionTab) self.label_10.setGeometry(QtCore.QRect(10,10,399,30)) self.label_10.setMaximumSize(QtCore.QSize(16777215,30)) font = QtGui.QFont() font.setPointSize(16) font.setWeight(50) font.setBold(False) self.label_10.setFont(font) self.label_10.setObjectName("label_10") self.tabWidget.addTab(self.compositionTab,"") self.solutionTab = QtGui.QWidget() self.solutionTab.setObjectName("solutionTab") self.label_11 = QtGui.QLabel(self.solutionTab) self.label_11.setGeometry(QtCore.QRect(20,20,371,30)) self.label_11.setMaximumSize(QtCore.QSize(16777215,30)) font = QtGui.QFont() font.setPointSize(16) font.setWeight(50) font.setBold(False) self.label_11.setFont(font) self.label_11.setObjectName("label_11") self.gridGroupBox = QtGui.QGroupBox(self.solutionTab) self.gridGroupBox.setGeometry(QtCore.QRect(20,290,371,93)) self.gridGroupBox.setObjectName("gridGroupBox") self.gridlayout = QtGui.QGridLayout(self.gridGroupBox) self.gridlayout.setMargin(9) self.gridlayout.setObjectName("gridlayout") self.svGridHeightSpin = QtGui.QSpinBox(self.gridGroupBox) self.svGridHeightSpin.setEnabled(False) self.svGridHeightSpin.setMaximumSize(QtCore.QSize(60,16777215)) self.svGridHeightSpin.setMinimum(1) self.svGridHeightSpin.setMaximum(999) self.svGridHeightSpin.setObjectName("svGridHeightSpin") self.gridlayout.addWidget(self.svGridHeightSpin,1,4,1,1) self.label_8 = QtGui.QLabel(self.gridGroupBox) font = QtGui.QFont() font.setWeight(75) font.setBold(True) self.label_8.setFont(font) self.label_8.setObjectName("label_8") self.gridlayout.addWidget(self.label_8,0,0,1,1) self.label_12 = QtGui.QLabel(self.gridGroupBox) font = QtGui.QFont() font.setWeight(75) font.setBold(True) self.label_12.setFont(font) self.label_12.setObjectName("label_12") self.gridlayout.addWidget(self.label_12,1,0,1,1) self.label_13 = QtGui.QLabel(self.gridGroupBox) self.label_13.setMinimumSize(QtCore.QSize(100,0)) self.label_13.setMaximumSize(QtCore.QSize(16777215,16777215)) font = QtGui.QFont() font.setWeight(75) font.setBold(True) self.label_13.setFont(font) self.label_13.setObjectName("label_13") self.gridlayout.addWidget(self.label_13,1,3,1,1) self.svShowgrid = QtGui.QCheckBox(self.gridGroupBox) self.svShowgrid.setChecked(False) self.svShowgrid.setObjectName("svShowgrid") self.gridlayout.addWidget(self.svShowgrid,0,1,1,1) self.svGridWidthSpin = QtGui.QSpinBox(self.gridGroupBox) self.svGridWidthSpin.setEnabled(False) self.svGridWidthSpin.setMaximumSize(QtCore.QSize(60,16777215)) self.svGridWidthSpin.setMinimum(1) self.svGridWidthSpin.setMaximum(999) self.svGridWidthSpin.setObjectName("svGridWidthSpin") self.gridlayout.addWidget(self.svGridWidthSpin,1,1,1,1) spacerItem = QtGui.QSpacerItem(20,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.gridlayout.addItem(spacerItem,1,2,1,1) self.colorsizeGroupBox = QtGui.QGroupBox(self.solutionTab) self.colorsizeGroupBox.setGeometry(QtCore.QRect(20,50,371,231)) self.colorsizeGroupBox.setObjectName("colorsizeGroupBox") self.gridlayout1 = QtGui.QGridLayout(self.colorsizeGroupBox) self.gridlayout1.setObjectName("gridlayout1") self.label_3 = QtGui.QLabel(self.colorsizeGroupBox) font = QtGui.QFont() font.setPointSize(9) font.setWeight(75) font.setBold(True) self.label_3.setFont(font) self.label_3.setObjectName("label_3") self.gridlayout1.addWidget(self.label_3,0,0,1,1) self.svPointClrButton = QtGui.QPushButton(self.colorsizeGroupBox) self.svPointClrButton.setMinimumSize(QtCore.QSize(80,0)) self.svPointClrButton.setMaximumSize(QtCore.QSize(100,16777215)) self.svPointClrButton.setFlat(False) self.svPointClrButton.setObjectName("svPointClrButton") self.gridlayout1.addWidget(self.svPointClrButton,0,1,1,1) self.svPointSizeSpin = QtGui.QSpinBox(self.colorsizeGroupBox) self.svPointSizeSpin.setMaximumSize(QtCore.QSize(50,16777215)) self.svPointSizeSpin.setMinimum(1) self.svPointSizeSpin.setObjectName("svPointSizeSpin") self.gridlayout1.addWidget(self.svPointSizeSpin,0,2,1,1) self.vPoint = QtGui.QCheckBox(self.colorsizeGroupBox) self.vPoint.setObjectName("vPoint") self.gridlayout1.addWidget(self.vPoint,0,3,1,1) self.label_14 = QtGui.QLabel(self.colorsizeGroupBox) font = QtGui.QFont() font.setPointSize(9) font.setWeight(75) font.setBold(True) self.label_14.setFont(font) self.label_14.setObjectName("label_14") self.gridlayout1.addWidget(self.label_14,1,0,1,1) self.svDistanceClrButton = QtGui.QPushButton(self.colorsizeGroupBox) self.svDistanceClrButton.setMaximumSize(QtCore.QSize(100,16777215)) self.svDistanceClrButton.setFlat(False) self.svDistanceClrButton.setObjectName("svDistanceClrButton") self.gridlayout1.addWidget(self.svDistanceClrButton,1,1,1,1) self.svLineSizeSpin = QtGui.QSpinBox(self.colorsizeGroupBox) self.svLineSizeSpin.setMaximumSize(QtCore.QSize(50,16777215)) self.svLineSizeSpin.setMinimum(1) self.svLineSizeSpin.setObjectName("svLineSizeSpin") self.gridlayout1.addWidget(self.svLineSizeSpin,1,2,1,1) self.vLine = QtGui.QCheckBox(self.colorsizeGroupBox) self.vLine.setObjectName("vLine") self.gridlayout1.addWidget(self.vLine,1,3,1,1) self.label_9 = QtGui.QLabel(self.colorsizeGroupBox) font = QtGui.QFont() font.setPointSize(9) font.setWeight(75) font.setBold(True) self.label_9.setFont(font) self.label_9.setObjectName("label_9") self.gridlayout1.addWidget(self.label_9,2,0,1,1) self.svfPointClrButton = QtGui.QPushButton(self.colorsizeGroupBox) self.svfPointClrButton.setMaximumSize(QtCore.QSize(100,16777215)) self.svfPointClrButton.setFlat(False) self.svfPointClrButton.setObjectName("svfPointClrButton") self.gridlayout1.addWidget(self.svfPointClrButton,2,1,1,1) self.svfPointSizeSpin = QtGui.QSpinBox(self.colorsizeGroupBox) self.svfPointSizeSpin.setMaximumSize(QtCore.QSize(50,16777215)) self.svfPointSizeSpin.setMinimum(1) self.svfPointSizeSpin.setObjectName("svfPointSizeSpin") self.gridlayout1.addWidget(self.svfPointSizeSpin,2,2,1,1) self.vfPoint = QtGui.QCheckBox(self.colorsizeGroupBox) self.vfPoint.setObjectName("vfPoint") self.gridlayout1.addWidget(self.vfPoint,2,3,1,1) self.label_4 = QtGui.QLabel(self.colorsizeGroupBox) font = QtGui.QFont() font.setPointSize(9) font.setWeight(75) font.setBold(True) self.label_4.setFont(font) self.label_4.setObjectName("label_4") self.gridlayout1.addWidget(self.label_4,3,0,1,1) self.svdConstraintClrButton = QtGui.QPushButton(self.colorsizeGroupBox) self.svdConstraintClrButton.setMaximumSize(QtCore.QSize(100,16777215)) self.svdConstraintClrButton.setFlat(False) self.svdConstraintClrButton.setObjectName("svdConstraintClrButton") self.gridlayout1.addWidget(self.svdConstraintClrButton,3,1,1,1) self.svDistanceSizeSpin = QtGui.QSpinBox(self.colorsizeGroupBox) self.svDistanceSizeSpin.setMaximumSize(QtCore.QSize(50,16777215)) self.svDistanceSizeSpin.setMinimum(1) self.svDistanceSizeSpin.setObjectName("svDistanceSizeSpin") self.gridlayout1.addWidget(self.svDistanceSizeSpin,3,2,1,1) self.vDistance = QtGui.QCheckBox(self.colorsizeGroupBox) self.vDistance.setObjectName("vDistance") self.gridlayout1.addWidget(self.vDistance,3,3,1,1) self.label_5 = QtGui.QLabel(self.colorsizeGroupBox) font = QtGui.QFont() font.setPointSize(9) font.setWeight(75) font.setBold(True) self.label_5.setFont(font) self.label_5.setObjectName("label_5") self.gridlayout1.addWidget(self.label_5,4,0,1,1) self.svAngleClrButton = QtGui.QPushButton(self.colorsizeGroupBox) self.svAngleClrButton.setMaximumSize(QtCore.QSize(100,16777215)) self.svAngleClrButton.setFlat(False) self.svAngleClrButton.setObjectName("svAngleClrButton") self.gridlayout1.addWidget(self.svAngleClrButton,4,1,1,1) self.vAngle = QtGui.QCheckBox(self.colorsizeGroupBox) self.vAngle.setObjectName("vAngle") self.gridlayout1.addWidget(self.vAngle,4,3,1,1) self.label_7 = QtGui.QLabel(self.colorsizeGroupBox) font = QtGui.QFont() font.setPointSize(9) font.setWeight(75) font.setBold(True) self.label_7.setFont(font) self.label_7.setObjectName("label_7") self.gridlayout1.addWidget(self.label_7,5,0,1,1) self.svBgClrButton = QtGui.QPushButton(self.colorsizeGroupBox) self.svBgClrButton.setMaximumSize(QtCore.QSize(100,16777215)) self.svBgClrButton.setFlat(False) self.svBgClrButton.setObjectName("svBgClrButton") self.gridlayout1.addWidget(self.svBgClrButton,5,1,1,1) self.tabWidget.addTab(self.solutionTab,"") self.retranslateUi(viewsForm) self.tabWidget.setCurrentIndex(1) QtCore.QObject.connect(self.svShowgrid,QtCore.SIGNAL("toggled(bool)"),self.svGridHeightSpin.setEnabled) QtCore.QObject.connect(self.svShowgrid,QtCore.SIGNAL("toggled(bool)"),self.svGridWidthSpin.setEnabled) QtCore.QMetaObject.connectSlotsByName(viewsForm) def retranslateUi(self, viewsForm): viewsForm.setWindowTitle(QtGui.QApplication.translate("viewsForm", "Form", None, QtGui.QApplication.UnicodeUTF8)) self.treeGroupBox.setTitle(QtGui.QApplication.translate("viewsForm", "Tree Visualisation", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("viewsForm", "Alignment:", None, QtGui.QApplication.UnicodeUTF8)) self.alignTreeComboBox.addItem(QtGui.QApplication.translate("viewsForm", "Top", None, QtGui.QApplication.UnicodeUTF8)) self.alignTreeComboBox.addItem(QtGui.QApplication.translate("viewsForm", "Bottom", None, QtGui.QApplication.UnicodeUTF8)) self.alignTreeComboBox.addItem(QtGui.QApplication.translate("viewsForm", "Right", None, QtGui.QApplication.UnicodeUTF8)) self.alignTreeComboBox.addItem(QtGui.QApplication.translate("viewsForm", "Left", None, QtGui.QApplication.UnicodeUTF8)) self.radioConnectionButton.setText(QtGui.QApplication.translate("viewsForm", "Lines", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.translate("viewsForm", "Connection:", None, QtGui.QApplication.UnicodeUTF8)) self.radioCurvedButton.setText(QtGui.QApplication.translate("viewsForm", "Curved", None, QtGui.QApplication.UnicodeUTF8)) self.label_10.setText(QtGui.QApplication.translate("viewsForm", "Decomposition View Options", None, QtGui.QApplication.UnicodeUTF8)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.compositionTab), QtGui.QApplication.translate("viewsForm", "Decomposition", None, QtGui.QApplication.UnicodeUTF8)) self.label_11.setText(QtGui.QApplication.translate("viewsForm", "Solution View Options", None, QtGui.QApplication.UnicodeUTF8)) self.gridGroupBox.setTitle(QtGui.QApplication.translate("viewsForm", "Grid", None, QtGui.QApplication.UnicodeUTF8)) self.svGridHeightSpin.setToolTip(QtGui.QApplication.translate("viewsForm", "Height of one cell", None, QtGui.QApplication.UnicodeUTF8)) self.label_8.setText(QtGui.QApplication.translate("viewsForm", "Show Grid:", None, QtGui.QApplication.UnicodeUTF8)) self.label_12.setText(QtGui.QApplication.translate("viewsForm", "Width:", None, QtGui.QApplication.UnicodeUTF8)) self.label_13.setText(QtGui.QApplication.translate("viewsForm", "Height:", None, QtGui.QApplication.UnicodeUTF8)) self.svShowgrid.setToolTip(QtGui.QApplication.translate("viewsForm", "Grid visibility", None, QtGui.QApplication.UnicodeUTF8)) self.svGridWidthSpin.setToolTip(QtGui.QApplication.translate("viewsForm", "Width of one cell", None, QtGui.QApplication.UnicodeUTF8)) self.colorsizeGroupBox.setTitle(QtGui.QApplication.translate("viewsForm", "Color && Size && Visibility", None, QtGui.QApplication.UnicodeUTF8)) self.label_3.setText(QtGui.QApplication.translate("viewsForm", "Point:", None, QtGui.QApplication.UnicodeUTF8)) self.svPointClrButton.setToolTip(QtGui.QApplication.translate("viewsForm", "Point color", None, QtGui.QApplication.UnicodeUTF8)) self.svPointSizeSpin.setToolTip(QtGui.QApplication.translate("viewsForm", "Radius of the point", None, QtGui.QApplication.UnicodeUTF8)) self.label_14.setText(QtGui.QApplication.translate("viewsForm", "Line:", None, QtGui.QApplication.UnicodeUTF8)) self.svDistanceClrButton.setToolTip(QtGui.QApplication.translate("viewsForm", "Line color", None, QtGui.QApplication.UnicodeUTF8)) self.svLineSizeSpin.setToolTip(QtGui.QApplication.translate("viewsForm", "Radius of line", None, QtGui.QApplication.UnicodeUTF8)) self.label_9.setText(QtGui.QApplication.translate("viewsForm", "Fixed Point Constraint:", None, QtGui.QApplication.UnicodeUTF8)) self.svfPointClrButton.setToolTip(QtGui.QApplication.translate("viewsForm", "Fixed point constraint color", None, QtGui.QApplication.UnicodeUTF8)) self.svfPointSizeSpin.setToolTip(QtGui.QApplication.translate("viewsForm", "Radius of the fixed point constraint", None, QtGui.QApplication.UnicodeUTF8)) self.label_4.setText(QtGui.QApplication.translate("viewsForm", "Distance Constraint:", None, QtGui.QApplication.UnicodeUTF8)) self.svdConstraintClrButton.setToolTip(QtGui.QApplication.translate("viewsForm", "Distance constraint color", None, QtGui.QApplication.UnicodeUTF8)) self.svDistanceSizeSpin.setToolTip(QtGui.QApplication.translate("viewsForm", "Radius of distance constraint", None, QtGui.QApplication.UnicodeUTF8)) self.label_5.setText(QtGui.QApplication.translate("viewsForm", "Angle Constraint:", None, QtGui.QApplication.UnicodeUTF8)) self.svAngleClrButton.setToolTip(QtGui.QApplication.translate("viewsForm", "Angle constraint color", None, QtGui.QApplication.UnicodeUTF8)) self.label_7.setText(QtGui.QApplication.translate("viewsForm", "Background:", None, QtGui.QApplication.UnicodeUTF8)) self.svBgClrButton.setToolTip(QtGui.QApplication.translate("viewsForm", "Background color", None, QtGui.QApplication.UnicodeUTF8)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.solutionTab), QtGui.QApplication.translate("viewsForm", "Solution", None, QtGui.QApplication.UnicodeUTF8))
gpl-3.0
Kemanth/Implementation-of-MRED-in-NS3
src/dsdv/bindings/modulegen__gcc_ILP32.py
10
510679
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) return True pybindgen.settings.error_handler = ErrorHandler() import sys def module_init(): root_module = Module('ns.dsdv', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] module.add_class('AttributeConstructionList', import_from_module='ns.core') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeAccessor> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeChecker> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeChecker']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeValue> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeValue']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::CallbackImplBase> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::EventImpl> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::EventImpl']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Hash::Implementation> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Ipv4Route> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::Ipv4Route']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NixVector> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::NixVector']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Packet> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::Packet']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::TraceSourceAccessor> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor']) ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', import_from_module='ns.core') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] module.add_class('Inet6SocketAddress', import_from_module='ns.network') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] module.add_class('InetSocketAddress', import_from_module='ns.network') ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## int-to-type.h (module 'core'): ns3::IntToType<0> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['0']) ## int-to-type.h (module 'core'): ns3::IntToType<0>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 0 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<1> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['1']) ## int-to-type.h (module 'core'): ns3::IntToType<1>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 1 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<2> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['2']) ## int-to-type.h (module 'core'): ns3::IntToType<2>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 2 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<3> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['3']) ## int-to-type.h (module 'core'): ns3::IntToType<3>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 3 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<4> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['4']) ## int-to-type.h (module 'core'): ns3::IntToType<4>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 4 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<5> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['5']) ## int-to-type.h (module 'core'): ns3::IntToType<5>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 5 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<6> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['6']) ## int-to-type.h (module 'core'): ns3::IntToType<6>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 6 >'], import_from_module='ns.core') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class] module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration] module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper [class] module.add_class('Ipv4RoutingHelper', allow_subclassing=True, import_from_module='ns.internet') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] module.add_class('Mac48Address', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::ItemType [enumeration] module.add_enum('ItemType', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simulator.h (module 'core'): ns3::Simulator [class] module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core') ## simulator.h (module 'core'): ns3::Simulator [enumeration] module.add_enum('', ['NO_CONTEXT'], outer_class=root_module['ns3::Simulator'], import_from_module='ns.core') ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## nstime.h (module 'core'): ns3::TimeWithUnit [class] module.add_class('TimeWithUnit', import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer [class] module.add_class('Timer', import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer::DestroyPolicy [enumeration] module.add_enum('DestroyPolicy', ['CANCEL_ON_DESTROY', 'REMOVE_ON_DESTROY', 'CHECK_ON_DESTROY'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer::State [enumeration] module.add_enum('State', ['RUNNING', 'EXPIRED', 'SUSPENDED'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core') ## timer-impl.h (module 'core'): ns3::TimerImpl [class] module.add_class('TimerImpl', allow_subclassing=True, import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::SupportLevel [enumeration] module.add_enum('SupportLevel', ['SUPPORTED', 'DEPRECATED', 'OBSOLETE'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-128.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## int64x64-128.h (module 'core'): ns3::int64x64_t::impl_type [enumeration] module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## dsdv-helper.h (module 'dsdv'): ns3::DsdvHelper [class] module.add_class('DsdvHelper', parent=root_module['ns3::Ipv4RoutingHelper']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header [class] module.add_class('Ipv4Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType [enumeration] module.add_enum('DscpType', ['DscpDefault', 'DSCP_CS1', 'DSCP_AF11', 'DSCP_AF12', 'DSCP_AF13', 'DSCP_CS2', 'DSCP_AF21', 'DSCP_AF22', 'DSCP_AF23', 'DSCP_CS3', 'DSCP_AF31', 'DSCP_AF32', 'DSCP_AF33', 'DSCP_CS4', 'DSCP_AF41', 'DSCP_AF42', 'DSCP_AF43', 'DSCP_CS5', 'DSCP_EF', 'DSCP_CS6', 'DSCP_CS7'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType [enumeration] module.add_enum('EcnType', ['ECN_NotECT', 'ECN_ECT1', 'ECN_ECT0', 'ECN_CE'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream [class] module.add_class('RandomVariableStream', import_from_module='ns.core', parent=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable [class] module.add_class('SequentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4MulticastRoute', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4MulticastRoute>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4Route', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4Route>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## socket.h (module 'network'): ns3::Socket [class] module.add_class('Socket', import_from_module='ns.network', parent=root_module['ns3::Object']) ## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration] module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketType [enumeration] module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketPriority [enumeration] module.add_enum('SocketPriority', ['NS3_PRIO_BESTEFFORT', 'NS3_PRIO_FILLER', 'NS3_PRIO_BULK', 'NS3_PRIO_INTERACTIVE_BULK', 'NS3_PRIO_INTERACTIVE', 'NS3_PRIO_CONTROL'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::Ipv6MulticastFilterMode [enumeration] module.add_enum('Ipv6MulticastFilterMode', ['INCLUDE', 'EXCLUDE'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::SocketIpTosTag [class] module.add_class('SocketIpTosTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpTtlTag [class] module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class] module.add_class('SocketIpv6HopLimitTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class] module.add_class('SocketIpv6TclassTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketPriorityTag [class] module.add_class('SocketPriorityTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class] module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time [class] root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable [class] module.add_class('TriangularRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable [class] module.add_class('UniformRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable [class] module.add_class('WeibullRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable [class] module.add_class('ZetaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable [class] module.add_class('ZipfRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable [class] module.add_class('ConstantRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable [class] module.add_class('DeterministicRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable [class] module.add_class('EmpiricalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor [class] module.add_class('EmptyAttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::AttributeAccessor']) ## attribute.h (module 'core'): ns3::EmptyAttributeChecker [class] module.add_class('EmptyAttributeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable [class] module.add_class('ErlangRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable [class] module.add_class('ExponentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable [class] module.add_class('GammaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## ipv4.h (module 'internet'): ns3::Ipv4 [class] module.add_class('Ipv4', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-interface.h (module 'internet'): ns3::Ipv4Interface [class] module.add_class('Ipv4Interface', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol [class] module.add_class('Ipv4L3Protocol', import_from_module='ns.internet', parent=root_module['ns3::Ipv4']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::DropReason [enumeration] module.add_enum('DropReason', ['DROP_TTL_EXPIRED', 'DROP_NO_ROUTE', 'DROP_BAD_CHECKSUM', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_FRAGMENT_TIMEOUT'], outer_class=root_module['ns3::Ipv4L3Protocol'], import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute [class] module.add_class('Ipv4MulticastRoute', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route [class] module.add_class('Ipv4Route', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol [class] module.add_class('Ipv4RoutingProtocol', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable [class] module.add_class('LogNormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class] module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class] module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable [class] module.add_class('NormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class] module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class] module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## 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']) ## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['bool', 'ns3::Ptr<ns3::Socket>', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['ns3::ObjectBase *', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'const ns3::Ipv4Header &', 'ns3::Ptr<const ns3::Packet>', 'ns3::Ipv4L3Protocol::DropReason', 'ns3::Ptr<ns3::Ipv4>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'const ns3::Ipv4Header &', 'ns3::Ptr<const ns3::Packet>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<const ns3::Packet>', 'const ns3::Ipv4Header &', 'ns3::Socket::SocketErrno', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<const ns3::Packet>', 'ns3::Ptr<ns3::Ipv4>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::Ipv4Route>', 'ns3::Ptr<const ns3::Packet>', 'const ns3::Ipv4Header &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<const ns3::Packet>', 'unsigned short', 'const ns3::Address &', 'const ns3::Address &', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting [class] module.add_class('Ipv4ListRouting', import_from_module='ns.internet', parent=root_module['ns3::Ipv4RoutingProtocol']) module.add_container('std::vector< ns3::Ipv6Address >', 'ns3::Ipv6Address', container_type=u'vector') module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type=u'map') ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace Hash nested_module = module.add_cpp_namespace('Hash') register_types_ns3_Hash(nested_module) ## Register a nested module for the namespace TracedValueCallback nested_module = module.add_cpp_namespace('TracedValueCallback') register_types_ns3_TracedValueCallback(nested_module) ## Register a nested module for the namespace dsdv nested_module = module.add_cpp_namespace('dsdv') register_types_ns3_dsdv(nested_module) 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 const )', u'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t const )*', u'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t const )&', u'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t const )', u'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t const )*', u'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t const )&', 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_types_ns3_dsdv(module): root_module = module.get_root() ## dsdv-rtable.h (module 'dsdv'): ns3::dsdv::RouteFlags [enumeration] module.add_enum('RouteFlags', ['VALID', 'INVALID']) ## dsdv-packet.h (module 'dsdv'): ns3::dsdv::DsdvHeader [class] module.add_class('DsdvHeader', parent=root_module['ns3::Header']) ## dsdv-packet-queue.h (module 'dsdv'): ns3::dsdv::PacketQueue [class] module.add_class('PacketQueue') ## dsdv-packet-queue.h (module 'dsdv'): ns3::dsdv::QueueEntry [class] module.add_class('QueueEntry') ## dsdv-routing-protocol.h (module 'dsdv'): ns3::dsdv::RoutingProtocol [class] module.add_class('RoutingProtocol', parent=root_module['ns3::Ipv4RoutingProtocol']) ## dsdv-rtable.h (module 'dsdv'): ns3::dsdv::RoutingTable [class] module.add_class('RoutingTable') ## dsdv-rtable.h (module 'dsdv'): ns3::dsdv::RoutingTableEntry [class] module.add_class('RoutingTableEntry') module.add_container('std::map< ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry >', ('ns3::Ipv4Address', 'ns3::dsdv::RoutingTableEntry'), container_type=u'map') def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3DefaultDeleter__Ns3AttributeAccessor_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeAccessor >']) register_Ns3DefaultDeleter__Ns3AttributeChecker_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeChecker >']) register_Ns3DefaultDeleter__Ns3AttributeValue_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeValue >']) register_Ns3DefaultDeleter__Ns3CallbackImplBase_methods(root_module, root_module['ns3::DefaultDeleter< ns3::CallbackImplBase >']) register_Ns3DefaultDeleter__Ns3EventImpl_methods(root_module, root_module['ns3::DefaultDeleter< ns3::EventImpl >']) register_Ns3DefaultDeleter__Ns3HashImplementation_methods(root_module, root_module['ns3::DefaultDeleter< ns3::Hash::Implementation >']) register_Ns3DefaultDeleter__Ns3Ipv4Route_methods(root_module, root_module['ns3::DefaultDeleter< ns3::Ipv4Route >']) register_Ns3DefaultDeleter__Ns3NixVector_methods(root_module, root_module['ns3::DefaultDeleter< ns3::NixVector >']) register_Ns3DefaultDeleter__Ns3Packet_methods(root_module, root_module['ns3::DefaultDeleter< ns3::Packet >']) register_Ns3DefaultDeleter__Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::DefaultDeleter< ns3::TraceSourceAccessor >']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress']) register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress']) register_Ns3IntToType__0_methods(root_module, root_module['ns3::IntToType< 0 >']) register_Ns3IntToType__1_methods(root_module, root_module['ns3::IntToType< 1 >']) register_Ns3IntToType__2_methods(root_module, root_module['ns3::IntToType< 2 >']) register_Ns3IntToType__3_methods(root_module, root_module['ns3::IntToType< 3 >']) register_Ns3IntToType__4_methods(root_module, root_module['ns3::IntToType< 4 >']) register_Ns3IntToType__5_methods(root_module, root_module['ns3::IntToType< 5 >']) register_Ns3IntToType__6_methods(root_module, root_module['ns3::IntToType< 6 >']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv4RoutingHelper_methods(root_module, root_module['ns3::Ipv4RoutingHelper']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit']) register_Ns3Timer_methods(root_module, root_module['ns3::Timer']) register_Ns3TimerImpl_methods(root_module, root_module['ns3::TimerImpl']) register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3DsdvHelper_methods(root_module, root_module['ns3::DsdvHelper']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream']) register_Ns3SequentialRandomVariable_methods(root_module, root_module['ns3::SequentialRandomVariable']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3Socket_methods(root_module, root_module['ns3::Socket']) register_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag']) register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag']) register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag']) register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag']) register_Ns3SocketPriorityTag_methods(root_module, root_module['ns3::SocketPriorityTag']) register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3TriangularRandomVariable_methods(root_module, root_module['ns3::TriangularRandomVariable']) register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable']) register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable']) register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable']) register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable']) register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable']) register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable']) register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable']) register_Ns3EmptyAttributeAccessor_methods(root_module, root_module['ns3::EmptyAttributeAccessor']) register_Ns3EmptyAttributeChecker_methods(root_module, root_module['ns3::EmptyAttributeChecker']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3ErlangRandomVariable_methods(root_module, root_module['ns3::ErlangRandomVariable']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable']) register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable']) register_Ns3Ipv4_methods(root_module, root_module['ns3::Ipv4']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4Interface_methods(root_module, root_module['ns3::Ipv4Interface']) register_Ns3Ipv4L3Protocol_methods(root_module, root_module['ns3::Ipv4L3Protocol']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv4MulticastRoute_methods(root_module, root_module['ns3::Ipv4MulticastRoute']) register_Ns3Ipv4Route_methods(root_module, root_module['ns3::Ipv4Route']) register_Ns3Ipv4RoutingProtocol_methods(root_module, root_module['ns3::Ipv4RoutingProtocol']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3LogNormalRandomVariable_methods(root_module, root_module['ns3::LogNormalRandomVariable']) register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable']) register_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_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Ns3ObjectBase___star___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Const_ns3Ipv4Header___amp___Ns3Ptr__lt__const_ns3Packet__gt___Ns3Ipv4L3ProtocolDropReason_Ns3Ptr__lt__ns3Ipv4__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Const_ns3Ipv4Header___amp___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Const_ns3Ipv4Header___amp___Ns3SocketSocketErrno_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Ns3Ptr__lt__ns3Ipv4__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Ipv4Route__gt___Ns3Ptr__lt__const_ns3Packet__gt___Const_ns3Ipv4Header___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Const_ns3Address___amp___Const_ns3Address___amp___Ns3NetDevicePacketType_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3Ipv4ListRouting_methods(root_module, root_module['ns3::Ipv4ListRouting']) register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation']) register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a']) register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32']) register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64']) register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3']) register_Ns3DsdvDsdvHeader_methods(root_module, root_module['ns3::dsdv::DsdvHeader']) register_Ns3DsdvPacketQueue_methods(root_module, root_module['ns3::dsdv::PacketQueue']) register_Ns3DsdvQueueEntry_methods(root_module, root_module['ns3::dsdv::QueueEntry']) register_Ns3DsdvRoutingProtocol_methods(root_module, root_module['ns3::dsdv::RoutingProtocol']) register_Ns3DsdvRoutingTable_methods(root_module, root_module['ns3::dsdv::RoutingTable']) register_Ns3DsdvRoutingTableEntry_methods(root_module, root_module['ns3::dsdv::RoutingTableEntry']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_output_stream_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) [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) [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<const ns3::AttributeChecker> 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'): ns3::AttributeConstructionList::CIterator ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'ns3::AttributeConstructionList::CIterator', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::CIterator ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'ns3::AttributeConstructionList::CIterator', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<const ns3::AttributeChecker> 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) [constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetRemainingSize() const [member function] cls.add_method('GetRemainingSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function] cls.add_method('PeekU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function] cls.add_method('Read', 'void', [param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Adjust(int32_t adjustment) [member function] cls.add_method('Adjust', 'void', [param('int32_t', 'adjustment')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [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_Ns3DefaultDeleter__Ns3AttributeAccessor_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeAccessor>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeAccessor>::DefaultDeleter(ns3::DefaultDeleter<ns3::AttributeAccessor> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::AttributeAccessor > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::AttributeAccessor>::Delete(ns3::AttributeAccessor * object) [member function] cls.add_method('Delete', 'void', [param('ns3::AttributeAccessor *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3AttributeChecker_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeChecker>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeChecker>::DefaultDeleter(ns3::DefaultDeleter<ns3::AttributeChecker> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::AttributeChecker > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::AttributeChecker>::Delete(ns3::AttributeChecker * object) [member function] cls.add_method('Delete', 'void', [param('ns3::AttributeChecker *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3AttributeValue_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeValue>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeValue>::DefaultDeleter(ns3::DefaultDeleter<ns3::AttributeValue> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::AttributeValue > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::AttributeValue>::Delete(ns3::AttributeValue * object) [member function] cls.add_method('Delete', 'void', [param('ns3::AttributeValue *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3CallbackImplBase_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::CallbackImplBase>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::CallbackImplBase>::DefaultDeleter(ns3::DefaultDeleter<ns3::CallbackImplBase> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::CallbackImplBase > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::CallbackImplBase>::Delete(ns3::CallbackImplBase * object) [member function] cls.add_method('Delete', 'void', [param('ns3::CallbackImplBase *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3EventImpl_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::EventImpl>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::EventImpl>::DefaultDeleter(ns3::DefaultDeleter<ns3::EventImpl> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::EventImpl > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::EventImpl>::Delete(ns3::EventImpl * object) [member function] cls.add_method('Delete', 'void', [param('ns3::EventImpl *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3HashImplementation_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Hash::Implementation>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Hash::Implementation>::DefaultDeleter(ns3::DefaultDeleter<ns3::Hash::Implementation> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::Hash::Implementation > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::Hash::Implementation>::Delete(ns3::Hash::Implementation * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Hash::Implementation *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3Ipv4Route_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Ipv4Route>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Ipv4Route>::DefaultDeleter(ns3::DefaultDeleter<ns3::Ipv4Route> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::Ipv4Route > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::Ipv4Route>::Delete(ns3::Ipv4Route * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Ipv4Route *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3NixVector_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NixVector>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NixVector>::DefaultDeleter(ns3::DefaultDeleter<ns3::NixVector> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::NixVector > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::NixVector>::Delete(ns3::NixVector * object) [member function] cls.add_method('Delete', 'void', [param('ns3::NixVector *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3Packet_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Packet>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Packet>::DefaultDeleter(ns3::DefaultDeleter<ns3::Packet> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::Packet > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::Packet>::Delete(ns3::Packet * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Packet *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3TraceSourceAccessor_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::TraceSourceAccessor>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::TraceSourceAccessor>::DefaultDeleter(ns3::DefaultDeleter<ns3::TraceSourceAccessor> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::TraceSourceAccessor > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::TraceSourceAccessor>::Delete(ns3::TraceSourceAccessor * object) [member function] cls.add_method('Delete', 'void', [param('ns3::TraceSourceAccessor *', 'object')], is_static=True) return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [constructor] cls.add_constructor([param('ns3::Hasher const &', 'arg0')]) ## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor] cls.add_constructor([]) ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function] cls.add_method('GetHash32', 'uint32_t', [param('std::string const', 's')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_Ns3Inet6SocketAddress_methods(root_module, cls): ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Inet6SocketAddress const & arg0) [constructor] cls.add_constructor([param('ns3::Inet6SocketAddress const &', 'arg0')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6) [constructor] cls.add_constructor([param('char const *', 'ipv6')]) ## inet6-socket-address.h (module 'network'): static ns3::Inet6SocketAddress ns3::Inet6SocketAddress::ConvertFrom(ns3::Address const & addr) [member function] cls.add_method('ConvertFrom', 'ns3::Inet6SocketAddress', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): ns3::Ipv6Address ns3::Inet6SocketAddress::GetIpv6() const [member function] cls.add_method('GetIpv6', 'ns3::Ipv6Address', [], is_const=True) ## inet6-socket-address.h (module 'network'): uint16_t ns3::Inet6SocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet6-socket-address.h (module 'network'): static bool ns3::Inet6SocketAddress::IsMatchingType(ns3::Address const & addr) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetIpv6(ns3::Ipv6Address ipv6) [member function] cls.add_method('SetIpv6', 'void', [param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) return def register_Ns3InetSocketAddress_methods(root_module, cls): ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::InetSocketAddress const & arg0) [constructor] cls.add_constructor([param('ns3::InetSocketAddress const &', 'arg0')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4) [constructor] cls.add_constructor([param('char const *', 'ipv4')]) ## inet-socket-address.h (module 'network'): static ns3::InetSocketAddress ns3::InetSocketAddress::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::InetSocketAddress', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): ns3::Ipv4Address ns3::InetSocketAddress::GetIpv4() const [member function] cls.add_method('GetIpv4', 'ns3::Ipv4Address', [], is_const=True) ## inet-socket-address.h (module 'network'): uint16_t ns3::InetSocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet-socket-address.h (module 'network'): uint8_t ns3::InetSocketAddress::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## inet-socket-address.h (module 'network'): static bool ns3::InetSocketAddress::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetIpv4(ns3::Ipv4Address address) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ipv4Address', 'address')]) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) return def register_Ns3IntToType__0_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType(ns3::IntToType<0> const & arg0) [constructor] cls.add_constructor([param('ns3::IntToType< 0 > const &', 'arg0')]) return def register_Ns3IntToType__1_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType(ns3::IntToType<1> const & arg0) [constructor] cls.add_constructor([param('ns3::IntToType< 1 > const &', 'arg0')]) return def register_Ns3IntToType__2_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType(ns3::IntToType<2> const & arg0) [constructor] cls.add_constructor([param('ns3::IntToType< 2 > const &', 'arg0')]) return def register_Ns3IntToType__3_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType(ns3::IntToType<3> const & arg0) [constructor] cls.add_constructor([param('ns3::IntToType< 3 > const &', 'arg0')]) return def register_Ns3IntToType__4_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType(ns3::IntToType<4> const & arg0) [constructor] cls.add_constructor([param('ns3::IntToType< 4 > const &', 'arg0')]) return def register_Ns3IntToType__5_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType(ns3::IntToType<5> const & arg0) [constructor] cls.add_constructor([param('ns3::IntToType< 5 > const &', 'arg0')]) return def register_Ns3IntToType__6_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType(ns3::IntToType<6> const & arg0) [constructor] cls.add_constructor([param('ns3::IntToType< 6 > const &', 'arg0')]) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4InterfaceAddress_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress() [constructor] cls.add_constructor([]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4Address local, ns3::Ipv4Mask mask) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'local'), param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4InterfaceAddress const & o) [constructor] cls.add_constructor([param('ns3::Ipv4InterfaceAddress const &', 'o')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetLocal() const [member function] cls.add_method('GetLocal', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Mask ns3::Ipv4InterfaceAddress::GetMask() const [member function] cls.add_method('GetMask', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e ns3::Ipv4InterfaceAddress::GetScope() const [member function] cls.add_method('GetScope', 'ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): bool ns3::Ipv4InterfaceAddress::IsSecondary() const [member function] cls.add_method('IsSecondary', 'bool', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetBroadcast(ns3::Ipv4Address broadcast) [member function] cls.add_method('SetBroadcast', 'void', [param('ns3::Ipv4Address', 'broadcast')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetLocal(ns3::Ipv4Address local) [member function] cls.add_method('SetLocal', 'void', [param('ns3::Ipv4Address', 'local')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetMask(ns3::Ipv4Mask mask) [member function] cls.add_method('SetMask', 'void', [param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetPrimary() [member function] cls.add_method('SetPrimary', 'void', []) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetScope(ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SetScope', 'void', [param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetSecondary() [member function] cls.add_method('SetSecondary', 'void', []) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv4RoutingHelper_methods(root_module, cls): ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper::Ipv4RoutingHelper() [constructor] cls.add_constructor([]) ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper::Ipv4RoutingHelper(ns3::Ipv4RoutingHelper const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4RoutingHelper const &', 'arg0')]) ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper * ns3::Ipv4RoutingHelper::Copy() const [member function] cls.add_method('Copy', 'ns3::Ipv4RoutingHelper *', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-helper.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4RoutingHelper::Create(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheAllAt(ns3::Time printTime, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintNeighborCacheAllAt', 'void', [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheAllEvery(ns3::Time printInterval, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintNeighborCacheAllEvery', 'void', [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheAt(ns3::Time printTime, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintNeighborCacheAt', 'void', [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheEvery(ns3::Time printInterval, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintNeighborCacheEvery', 'void', [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableAllAt(ns3::Time printTime, ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) [member function] cls.add_method('PrintRoutingTableAllAt', 'void', [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableAllEvery(ns3::Time printInterval, ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) [member function] cls.add_method('PrintRoutingTableAllEvery', 'void', [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableAt(ns3::Time printTime, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) [member function] cls.add_method('PrintRoutingTableAt', 'void', [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableEvery(ns3::Time printInterval, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) [member function] cls.add_method('PrintRoutingTableEvery', 'void', [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')], is_static=True) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') cls.add_binary_comparison_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) [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_output_stream_operator() cls.add_binary_comparison_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) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3Mac48Address_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_output_stream_operator() ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac48Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv4Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv6Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] cls.add_method('GetMulticast6Prefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] cls.add_method('GetMulticastPrefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function] cls.add_method('IsGroup', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3NodeContainer_methods(root_module, cls): ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [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'): ns3::NodeContainer::Iterator ns3::NodeContainer::Begin() const [member function] cls.add_method('Begin', 'ns3::NodeContainer::Iterator', [], 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'): ns3::NodeContainer::Iterator ns3::NodeContainer::End() const [member function] cls.add_method('End', 'ns3::NodeContainer::Iterator', [], 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) [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) [constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::type [variable] cls.add_instance_attribute('type', 'ns3::PacketMetadata::Item::ItemType', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function] cls.add_method('Replace', 'bool', [param('ns3::Tag &', 'tag')]) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 1 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) return def register_Ns3Simulator_methods(root_module, cls): ## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [constructor] cls.add_constructor([param('ns3::Simulator const &', 'arg0')]) ## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function] cls.add_method('Cancel', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function] cls.add_method('Destroy', 'void', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function] cls.add_method('GetContext', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function] cls.add_method('GetImplementation', 'ns3::Ptr< ns3::SimulatorImpl >', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function] cls.add_method('GetMaximumSimulationTime', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function] cls.add_method('IsExpired', 'bool', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function] cls.add_method('IsFinished', 'bool', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function] cls.add_method('Now', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function] cls.add_method('Remove', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function] cls.add_method('SetImplementation', 'void', [param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function] cls.add_method('SetScheduler', 'void', [param('ns3::ObjectFactory', 'schedulerFactory')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function] cls.add_method('Stop', 'void', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & delay) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'delay')], is_static=True) return def register_Ns3Tag_methods(root_module, cls): ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] cls.add_constructor([]) ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [constructor] cls.add_constructor([param('ns3::Tag const &', 'arg0')]) ## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_virtual=True) ## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TagBuffer_methods(root_module, cls): ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [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 v) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t v) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'v')]) ## 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) [constructor] cls.add_constructor([param('ns3::TimeWithUnit const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::Time const time, ns3::Time::Unit const unit) [constructor] cls.add_constructor([param('ns3::Time const', 'time'), param('ns3::Time::Unit const', 'unit')]) return def register_Ns3Timer_methods(root_module, cls): ## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer const & arg0) [constructor] cls.add_constructor([param('ns3::Timer const &', 'arg0')]) ## timer.h (module 'core'): ns3::Timer::Timer() [constructor] cls.add_constructor([]) ## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer::DestroyPolicy destroyPolicy) [constructor] cls.add_constructor([param('ns3::Timer::DestroyPolicy', 'destroyPolicy')]) ## timer.h (module 'core'): void ns3::Timer::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelay() const [member function] cls.add_method('GetDelay', 'ns3::Time', [], is_const=True) ## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelayLeft() const [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [], is_const=True) ## timer.h (module 'core'): ns3::Timer::State ns3::Timer::GetState() const [member function] cls.add_method('GetState', 'ns3::Timer::State', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsSuspended() const [member function] cls.add_method('IsSuspended', 'bool', [], is_const=True) ## timer.h (module 'core'): void ns3::Timer::Remove() [member function] cls.add_method('Remove', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Resume() [member function] cls.add_method('Resume', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Schedule() [member function] cls.add_method('Schedule', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Schedule(ns3::Time delay) [member function] cls.add_method('Schedule', 'void', [param('ns3::Time', 'delay')]) ## timer.h (module 'core'): void ns3::Timer::SetDelay(ns3::Time const & delay) [member function] cls.add_method('SetDelay', 'void', [param('ns3::Time const &', 'delay')]) ## timer.h (module 'core'): void ns3::Timer::Suspend() [member function] cls.add_method('Suspend', 'void', []) return def register_Ns3TimerImpl_methods(root_module, cls): ## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl() [constructor] cls.add_constructor([]) ## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl(ns3::TimerImpl const & arg0) [constructor] cls.add_constructor([param('ns3::TimerImpl const &', 'arg0')]) ## timer-impl.h (module 'core'): void ns3::TimerImpl::Invoke() [member function] cls.add_method('Invoke', 'void', [], is_pure_virtual=True, is_virtual=True) ## timer-impl.h (module 'core'): ns3::EventId ns3::TimerImpl::Schedule(ns3::Time const & delay) [member function] cls.add_method('Schedule', 'ns3::EventId', [param('ns3::Time const &', 'delay')], is_pure_virtual=True, is_virtual=True) return def register_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) [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<const ns3::AttributeAccessor> accessor, ns3::Ptr<const ns3::AttributeChecker> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SupportLevel::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SupportLevel::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<const ns3::AttributeAccessor> accessor, ns3::Ptr<const ns3::AttributeChecker> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SupportLevel::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SupportLevel::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<const ns3::TraceSourceAccessor> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<const ns3::TraceSourceAccessor> accessor, std::string callback, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SupportLevel::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor'), param('std::string', 'callback'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SupportLevel::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId::hash_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'ns3::TypeId::hash_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(ns3::TypeId::hash_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(ns3::TypeId::hash_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<const ns3::TraceSourceAccessor> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): ns3::Ptr<const ns3::TraceSourceAccessor> ns3::TypeId::LookupTraceSourceByName(std::string name, ns3::TypeId::TraceSourceInformation * info) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name'), param('ns3::TypeId::TraceSourceInformation *', 'info')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<const ns3::AttributeValue> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetSize(std::size_t size) [member function] cls.add_method('SetSize', 'ns3::TypeId', [param('std::size_t', 'size')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t uid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'uid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [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) cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportLevel [variable] cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportMsg [variable] cls.add_instance_attribute('supportMsg', 'std::string', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::callback [variable] cls.add_instance_attribute('callback', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportLevel [variable] cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportMsg [variable] cls.add_instance_attribute('supportMsg', 'std::string', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [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_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_output_stream_operator() 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_unary_numeric_operator('-') ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(double const value) [constructor] cls.add_constructor([param('double const', 'value')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long double const value) [constructor] cls.add_constructor([param('long double const', 'value')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(int const v) [constructor] cls.add_constructor([param('int const', 'v')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long int const v) [constructor] cls.add_constructor([param('long int const', 'v')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int const v) [constructor] cls.add_constructor([param('long long int const', 'v')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int const v) [constructor] cls.add_constructor([param('unsigned int const', 'v')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int const v) [constructor] cls.add_constructor([param('long unsigned int const', 'v')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int const v) [constructor] cls.add_constructor([param('long long unsigned int const', 'v')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t const hi, uint64_t const lo) [constructor] cls.add_constructor([param('int64_t const', 'hi'), param('uint64_t const', 'lo')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-128.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-128.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-128.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-128.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t const v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t const', 'v')], is_static=True) ## int64x64-128.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-128.h (module 'core'): ns3::int64x64_t::implementation [variable] cls.add_static_attribute('implementation', 'ns3::int64x64_t::impl_type const', is_const=True) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3DsdvHelper_methods(root_module, cls): ## dsdv-helper.h (module 'dsdv'): ns3::DsdvHelper::DsdvHelper(ns3::DsdvHelper const & arg0) [constructor] cls.add_constructor([param('ns3::DsdvHelper const &', 'arg0')]) ## dsdv-helper.h (module 'dsdv'): ns3::DsdvHelper::DsdvHelper() [constructor] cls.add_constructor([]) ## dsdv-helper.h (module 'dsdv'): ns3::DsdvHelper * ns3::DsdvHelper::Copy() const [member function] cls.add_method('Copy', 'ns3::DsdvHelper *', [], is_const=True, is_virtual=True) ## dsdv-helper.h (module 'dsdv'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::DsdvHelper::Create(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True, is_virtual=True) ## dsdv-helper.h (module 'dsdv'): void ns3::DsdvHelper::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Ipv4Header_methods(root_module, cls): ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header(ns3::Ipv4Header const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4Header const &', 'arg0')]) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header() [constructor] cls.add_constructor([]) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::DscpTypeToString(ns3::Ipv4Header::DscpType dscp) const [member function] cls.add_method('DscpTypeToString', 'std::string', [param('ns3::Ipv4Header::DscpType', 'dscp')], is_const=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::EcnTypeToString(ns3::Ipv4Header::EcnType ecn) const [member function] cls.add_method('EcnTypeToString', 'std::string', [param('ns3::Ipv4Header::EcnType', 'ecn')], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::EnableChecksum() [member function] cls.add_method('EnableChecksum', 'void', []) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType ns3::Ipv4Header::GetDscp() const [member function] cls.add_method('GetDscp', 'ns3::Ipv4Header::DscpType', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType ns3::Ipv4Header::GetEcn() const [member function] cls.add_method('GetEcn', 'ns3::Ipv4Header::EcnType', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetFragmentOffset() const [member function] cls.add_method('GetFragmentOffset', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetIdentification() const [member function] cls.add_method('GetIdentification', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::TypeId ns3::Ipv4Header::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetPayloadSize() const [member function] cls.add_method('GetPayloadSize', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetProtocol() const [member function] cls.add_method('GetProtocol', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): static ns3::TypeId ns3::Ipv4Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsChecksumOk() const [member function] cls.add_method('IsChecksumOk', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsDontFragment() const [member function] cls.add_method('IsDontFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsLastFragment() const [member function] cls.add_method('IsLastFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDestination(ns3::Ipv4Address destination) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'destination')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDontFragment() [member function] cls.add_method('SetDontFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDscp(ns3::Ipv4Header::DscpType dscp) [member function] cls.add_method('SetDscp', 'void', [param('ns3::Ipv4Header::DscpType', 'dscp')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetEcn(ns3::Ipv4Header::EcnType ecn) [member function] cls.add_method('SetEcn', 'void', [param('ns3::Ipv4Header::EcnType', 'ecn')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetFragmentOffset(uint16_t offsetBytes) [member function] cls.add_method('SetFragmentOffset', 'void', [param('uint16_t', 'offsetBytes')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetIdentification(uint16_t identification) [member function] cls.add_method('SetIdentification', 'void', [param('uint16_t', 'identification')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetLastFragment() [member function] cls.add_method('SetLastFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMayFragment() [member function] cls.add_method('SetMayFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMoreFragments() [member function] cls.add_method('SetMoreFragments', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetPayloadSize(uint16_t size) [member function] cls.add_method('SetPayloadSize', 'void', [param('uint16_t', 'size')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetProtocol(uint8_t num) [member function] cls.add_method('SetProtocol', 'void', [param('uint8_t', 'num')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetSource(ns3::Ipv4Address source) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'source')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3Object_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::Object() [constructor] cls.add_constructor([]) ## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function] cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) ## object.h (module 'core'): void ns3::Object::Dispose() [member function] cls.add_method('Dispose', 'void', []) ## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function] cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) ## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object.h (module 'core'): void ns3::Object::Initialize() [member function] cls.add_method('Initialize', 'void', []) ## object.h (module 'core'): bool ns3::Object::IsInitialized() const [member function] cls.add_method('IsInitialized', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [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) [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<const ns3::Object> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_Ns3RandomVariableStream_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::RandomVariableStream::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream::RandomVariableStream() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetStream(int64_t stream) [member function] cls.add_method('SetStream', 'void', [param('int64_t', 'stream')]) ## random-variable-stream.h (module 'core'): int64_t ns3::RandomVariableStream::GetStream() const [member function] cls.add_method('GetStream', 'int64_t', [], is_const=True) ## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetAntithetic(bool isAntithetic) [member function] cls.add_method('SetAntithetic', 'void', [param('bool', 'isAntithetic')]) ## random-variable-stream.h (module 'core'): bool ns3::RandomVariableStream::IsAntithetic() const [member function] cls.add_method('IsAntithetic', 'bool', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::RandomVariableStream::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_pure_virtual=True, is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::RandomVariableStream::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_pure_virtual=True, is_virtual=True) ## random-variable-stream.h (module 'core'): ns3::RngStream * ns3::RandomVariableStream::Peek() const [member function] cls.add_method('Peek', 'ns3::RngStream *', [], is_const=True, visibility='protected') return def register_Ns3SequentialRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::SequentialRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable::SequentialRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): ns3::Ptr<ns3::RandomVariableStream> ns3::SequentialRandomVariable::GetIncrement() const [member function] cls.add_method('GetIncrement', 'ns3::Ptr< ns3::RandomVariableStream >', [], is_const=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetConsecutive() const [member function] cls.add_method('GetConsecutive', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) return def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')]) return def register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4MulticastRoute > > const &', 'o')]) return def register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4Route > > const &', 'o')]) return def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')]) return def register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount(ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &', 'o')]) return def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')]) return def register_Ns3Socket_methods(root_module, cls): ## socket.h (module 'network'): ns3::Socket::Socket(ns3::Socket const & arg0) [constructor] cls.add_constructor([param('ns3::Socket const &', 'arg0')]) ## socket.h (module 'network'): ns3::Socket::Socket() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): int ns3::Socket::Bind(ns3::Address const & address) [member function] cls.add_method('Bind', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind() [member function] cls.add_method('Bind', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind6() [member function] cls.add_method('Bind6', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::BindToNetDevice(ns3::Ptr<ns3::NetDevice> netdevice) [member function] cls.add_method('BindToNetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'netdevice')], is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Close() [member function] cls.add_method('Close', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Connect(ns3::Address const & address) [member function] cls.add_method('Connect', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): static ns3::Ptr<ns3::Socket> ns3::Socket::CreateSocket(ns3::Ptr<ns3::Node> node, ns3::TypeId tid) [member function] cls.add_method('CreateSocket', 'ns3::Ptr< ns3::Socket >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::TypeId', 'tid')], is_static=True) ## socket.h (module 'network'): bool ns3::Socket::GetAllowBroadcast() const [member function] cls.add_method('GetAllowBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Socket::GetBoundNetDevice() [member function] cls.add_method('GetBoundNetDevice', 'ns3::Ptr< ns3::NetDevice >', []) ## socket.h (module 'network'): ns3::Socket::SocketErrno ns3::Socket::GetErrno() const [member function] cls.add_method('GetErrno', 'ns3::Socket::SocketErrno', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTos() const [member function] cls.add_method('GetIpTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTtl() const [member function] cls.add_method('GetIpTtl', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6HopLimit() const [member function] cls.add_method('GetIpv6HopLimit', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6Tclass() const [member function] cls.add_method('GetIpv6Tclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Socket::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::GetPeerName(ns3::Address & address) const [member function] cls.add_method('GetPeerName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetPriority() const [member function] cls.add_method('GetPriority', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetRxAvailable() const [member function] cls.add_method('GetRxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::GetSockName(ns3::Address & address) const [member function] cls.add_method('GetSockName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Socket::SocketType ns3::Socket::GetSocketType() const [member function] cls.add_method('GetSocketType', 'ns3::Socket::SocketType', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetTxAvailable() const [member function] cls.add_method('GetTxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::Socket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): static uint8_t ns3::Socket::IpTos2Priority(uint8_t ipTos) [member function] cls.add_method('IpTos2Priority', 'uint8_t', [param('uint8_t', 'ipTos')], is_static=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address, ns3::Socket::Ipv6MulticastFilterMode filterMode, std::vector<ns3::Ipv6Address, std::allocator<ns3::Ipv6Address> > sourceAddresses) [member function] cls.add_method('Ipv6JoinGroup', 'void', [param('ns3::Ipv6Address', 'address'), param('ns3::Socket::Ipv6MulticastFilterMode', 'filterMode'), param('std::vector< ns3::Ipv6Address >', 'sourceAddresses')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address) [member function] cls.add_method('Ipv6JoinGroup', 'void', [param('ns3::Ipv6Address', 'address')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6LeaveGroup() [member function] cls.add_method('Ipv6LeaveGroup', 'void', [], is_virtual=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTos() const [member function] cls.add_method('IsIpRecvTos', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTtl() const [member function] cls.add_method('IsIpRecvTtl', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvHopLimit() const [member function] cls.add_method('IsIpv6RecvHopLimit', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvTclass() const [member function] cls.add_method('IsIpv6RecvTclass', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsRecvPktInfo() const [member function] cls.add_method('IsRecvPktInfo', 'bool', [], is_const=True) ## socket.h (module 'network'): int ns3::Socket::Listen() [member function] cls.add_method('Listen', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv(uint32_t maxSize, uint32_t flags) [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', []) ## socket.h (module 'network'): int ns3::Socket::Recv(uint8_t * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Recv', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::RecvFrom(uint8_t * buf, uint32_t size, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## socket.h (module 'network'): int ns3::Socket::Send(uint8_t const * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): int ns3::Socket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function] cls.add_method('SendTo', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::SendTo(uint8_t const * buf, uint32_t size, uint32_t flags, ns3::Address const & address) [member function] cls.add_method('SendTo', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address const &', 'address')]) ## socket.h (module 'network'): void ns3::Socket::SetAcceptCallback(ns3::Callback<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionRequest, ns3::Callback<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> newConnectionCreated) [member function] cls.add_method('SetAcceptCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionRequest'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'newConnectionCreated')]) ## socket.h (module 'network'): bool ns3::Socket::SetAllowBroadcast(bool allowBroadcast) [member function] cls.add_method('SetAllowBroadcast', 'bool', [param('bool', 'allowBroadcast')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetCloseCallbacks(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> normalClose, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> errorClose) [member function] cls.add_method('SetCloseCallbacks', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'normalClose'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'errorClose')]) ## socket.h (module 'network'): void ns3::Socket::SetConnectCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionSucceeded, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionFailed) [member function] cls.add_method('SetConnectCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionSucceeded'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionFailed')]) ## socket.h (module 'network'): void ns3::Socket::SetDataSentCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> dataSent) [member function] cls.add_method('SetDataSentCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'dataSent')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTos(bool ipv4RecvTos) [member function] cls.add_method('SetIpRecvTos', 'void', [param('bool', 'ipv4RecvTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTtl(bool ipv4RecvTtl) [member function] cls.add_method('SetIpRecvTtl', 'void', [param('bool', 'ipv4RecvTtl')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTos(uint8_t ipTos) [member function] cls.add_method('SetIpTos', 'void', [param('uint8_t', 'ipTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTtl(uint8_t ipTtl) [member function] cls.add_method('SetIpTtl', 'void', [param('uint8_t', 'ipTtl')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6HopLimit(uint8_t ipHopLimit) [member function] cls.add_method('SetIpv6HopLimit', 'void', [param('uint8_t', 'ipHopLimit')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvHopLimit(bool ipv6RecvHopLimit) [member function] cls.add_method('SetIpv6RecvHopLimit', 'void', [param('bool', 'ipv6RecvHopLimit')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvTclass(bool ipv6RecvTclass) [member function] cls.add_method('SetIpv6RecvTclass', 'void', [param('bool', 'ipv6RecvTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6Tclass(int ipTclass) [member function] cls.add_method('SetIpv6Tclass', 'void', [param('int', 'ipTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetPriority(uint8_t priority) [member function] cls.add_method('SetPriority', 'void', [param('uint8_t', 'priority')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arg0) [member function] cls.add_method('SetRecvCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arg0')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvPktInfo(bool flag) [member function] cls.add_method('SetRecvPktInfo', 'void', [param('bool', 'flag')]) ## socket.h (module 'network'): void ns3::Socket::SetSendCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> sendCb) [member function] cls.add_method('SetSendCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'sendCb')]) ## socket.h (module 'network'): int ns3::Socket::ShutdownRecv() [member function] cls.add_method('ShutdownRecv', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::ShutdownSend() [member function] cls.add_method('ShutdownSend', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## socket.h (module 'network'): bool ns3::Socket::IsManualIpTtl() const [member function] cls.add_method('IsManualIpTtl', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6HopLimit() const [member function] cls.add_method('IsManualIpv6HopLimit', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6Tclass() const [member function] cls.add_method('IsManualIpv6Tclass', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionFailed() [member function] cls.add_method('NotifyConnectionFailed', 'void', [], visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::NotifyConnectionRequest(ns3::Address const & from) [member function] cls.add_method('NotifyConnectionRequest', 'bool', [param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionSucceeded() [member function] cls.add_method('NotifyConnectionSucceeded', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataRecv() [member function] cls.add_method('NotifyDataRecv', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataSent(uint32_t size) [member function] cls.add_method('NotifyDataSent', 'void', [param('uint32_t', 'size')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyErrorClose() [member function] cls.add_method('NotifyErrorClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNewConnectionCreated(ns3::Ptr<ns3::Socket> socket, ns3::Address const & from) [member function] cls.add_method('NotifyNewConnectionCreated', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket'), param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNormalClose() [member function] cls.add_method('NotifyNormalClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifySend(uint32_t spaceAvailable) [member function] cls.add_method('NotifySend', 'void', [param('uint32_t', 'spaceAvailable')], visibility='protected') return def register_Ns3SocketIpTosTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag(ns3::SocketIpTosTag const & arg0) [constructor] cls.add_constructor([param('ns3::SocketIpTosTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTosTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTosTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTosTag::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTosTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) return def register_Ns3SocketIpTtlTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag(ns3::SocketIpTtlTag const & arg0) [constructor] cls.add_constructor([param('ns3::SocketIpTtlTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTtlTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTtlTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTtlTag::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTtlTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3SocketIpv6HopLimitTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag(ns3::SocketIpv6HopLimitTag const & arg0) [constructor] cls.add_constructor([param('ns3::SocketIpv6HopLimitTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6HopLimitTag::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6HopLimitTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6HopLimitTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6HopLimitTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::SetHopLimit(uint8_t hopLimit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'hopLimit')]) return def register_Ns3SocketIpv6TclassTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag(ns3::SocketIpv6TclassTag const & arg0) [constructor] cls.add_constructor([param('ns3::SocketIpv6TclassTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6TclassTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6TclassTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6TclassTag::GetTclass() const [member function] cls.add_method('GetTclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6TclassTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::SetTclass(uint8_t tclass) [member function] cls.add_method('SetTclass', 'void', [param('uint8_t', 'tclass')]) return def register_Ns3SocketPriorityTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag(ns3::SocketPriorityTag const & arg0) [constructor] cls.add_constructor([param('ns3::SocketPriorityTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketPriorityTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketPriorityTag::GetPriority() const [member function] cls.add_method('GetPriority', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint32_t ns3::SocketPriorityTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketPriorityTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::SetPriority(uint8_t priority) [member function] cls.add_method('SetPriority', 'void', [param('uint8_t', 'priority')]) return def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [constructor] cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Disable() [member function] cls.add_method('Disable', 'void', []) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Enable() [member function] cls.add_method('Enable', 'void', []) ## socket.h (module 'network'): ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function] cls.add_method('IsEnabled', 'bool', [], is_const=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) return def register_Ns3Time_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('>=') cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') 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_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) 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() ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & v) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::TimeWithUnit ns3::Time::As(ns3::Time::Unit const unit) const [member function] cls.add_method('As', 'ns3::TimeWithUnit', [param('ns3::Time::Unit const', 'unit')], is_const=True) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value, ns3::Time::Unit unit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit unit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit unit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetDays() const [member function] cls.add_method('GetDays', 'double', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function] cls.add_method('GetFemtoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetHours() const [member function] cls.add_method('GetHours', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function] cls.add_method('GetInteger', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function] cls.add_method('GetMicroSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function] cls.add_method('GetMilliSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetMinutes() const [member function] cls.add_method('GetMinutes', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function] cls.add_method('GetNanoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function] cls.add_method('GetPicoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function] cls.add_method('GetResolution', 'ns3::Time::Unit', [], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function] cls.add_method('GetSeconds', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function] cls.add_method('GetTimeStep', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetYears() const [member function] cls.add_method('GetYears', 'double', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function] cls.add_method('IsNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function] cls.add_method('IsPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function] cls.add_method('IsStrictlyNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function] cls.add_method('IsStrictlyPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function] cls.add_method('IsZero', 'bool', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function] cls.add_method('Max', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function] cls.add_method('Min', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function] cls.add_method('StaticInit', 'bool', [], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit unit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit unit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit unit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [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_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TriangularRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::TriangularRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable::TriangularRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue(double mean, double min, double max) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'min'), param('double', 'max')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger(uint32_t mean, uint32_t min, uint32_t max) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'min'), param('uint32_t', 'max')]) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3UniformRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::UniformRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable::UniformRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue(double min, double max) [member function] cls.add_method('GetValue', 'double', [param('double', 'min'), param('double', 'max')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger(uint32_t min, uint32_t max) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'min'), param('uint32_t', 'max')]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3WeibullRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::WeibullRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable::WeibullRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetScale() const [member function] cls.add_method('GetScale', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetShape() const [member function] cls.add_method('GetShape', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue(double scale, double shape, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'scale'), param('double', 'shape'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger(uint32_t scale, uint32_t shape, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'scale'), param('uint32_t', 'shape'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZetaRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZetaRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable::ZetaRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue(double alpha) [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger(uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZipfRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZipfRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable::ZipfRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue(uint32_t n, double alpha) [member function] cls.add_method('GetValue', 'double', [param('uint32_t', 'n'), param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger(uint32_t n, uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'n'), param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [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) [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) [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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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) [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<const ns3::CallbackImplBase> 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') ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::ObjectBase*']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'void']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ptr<ns3::Ipv4Route> ']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ptr<ns3::Packet const> ']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ipv4Header const&']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Socket::SocketErrno']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ptr<ns3::NetDevice> ']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'unsigned short']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Address const&']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::NetDevice::PacketType']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ptr<ns3::Socket> ']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'bool']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'unsigned int']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ptr<ns3::Ipv4> ']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ipv4L3Protocol::DropReason']) return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_Ns3ConstantRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ConstantRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable::ConstantRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetConstant() const [member function] cls.add_method('GetConstant', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue(double constant) [member function] cls.add_method('GetValue', 'double', [param('double', 'constant')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger(uint32_t constant) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'constant')]) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3DeterministicRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::DeterministicRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable::DeterministicRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::DeterministicRandomVariable::SetValueArray(double * values, uint64_t length) [member function] cls.add_method('SetValueArray', 'void', [param('double *', 'values'), param('uint64_t', 'length')]) ## random-variable-stream.h (module 'core'): double ns3::DeterministicRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::DeterministicRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3EmpiricalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable::EmpiricalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::CDF(double v, double c) [member function] cls.add_method('CDF', 'void', [param('double', 'v'), param('double', 'c')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::EmpiricalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::EmpiricalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::Interpolate(double c1, double c2, double v1, double v2, double r) [member function] cls.add_method('Interpolate', 'double', [param('double', 'c1'), param('double', 'c2'), param('double', 'v1'), param('double', 'v2'), param('double', 'r')], visibility='private', is_virtual=True) ## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::Validate() [member function] cls.add_method('Validate', 'void', [], visibility='private', is_virtual=True) return def register_Ns3EmptyAttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor(ns3::EmptyAttributeAccessor const & arg0) [constructor] cls.add_constructor([param('ns3::EmptyAttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object'), param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) return def register_Ns3EmptyAttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker(ns3::EmptyAttributeChecker const & arg0) [constructor] cls.add_constructor([param('ns3::EmptyAttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_const=True, is_virtual=True) return def register_Ns3EmptyAttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_Ns3ErlangRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ErlangRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable::ErlangRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetK() const [member function] cls.add_method('GetK', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetLambda() const [member function] cls.add_method('GetLambda', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue(uint32_t k, double lambda) [member function] cls.add_method('GetValue', 'double', [param('uint32_t', 'k'), param('double', 'lambda')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger(uint32_t k, uint32_t lambda) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'k'), param('uint32_t', 'lambda')]) ## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3EventImpl_methods(root_module, cls): ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [constructor] cls.add_constructor([param('ns3::EventImpl const &', 'arg0')]) ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor] cls.add_constructor([]) ## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function] cls.add_method('Invoke', 'void', []) ## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function] cls.add_method('IsCancelled', 'bool', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function] cls.add_method('Notify', 'void', [], is_pure_virtual=True, visibility='protected', is_virtual=True) return def register_Ns3ExponentialRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ExponentialRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable::ExponentialRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue(double mean, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger(uint32_t mean, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3GammaRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::GammaRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable::GammaRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetBeta() const [member function] cls.add_method('GetBeta', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue(double alpha, double beta) [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha'), param('double', 'beta')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger(uint32_t alpha, uint32_t beta) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'alpha'), param('uint32_t', 'beta')]) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3Ipv4_methods(root_module, cls): ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4(ns3::Ipv4 const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4 const &', 'arg0')]) ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4() [constructor] cls.add_constructor([]) ## ipv4.h (module 'internet'): bool ns3::Ipv4::AddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', [], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4::GetAddress(uint32_t interface, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForAddress(ns3::Ipv4Address address) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv4Address', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForPrefix(ns3::Ipv4Address address, ns3::Ipv4Mask mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv4Address', 'address'), param('ns3::Ipv4Mask', 'mask')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMetric(uint32_t interface) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMtu(uint32_t interface) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4::GetNetDevice(uint32_t interface) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber, int32_t interfaceIndex) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber'), param('int32_t', 'interfaceIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): static ns3::TypeId ns3::Ipv4::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function] cls.add_method('IsDestinationAddress', 'bool', [param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsForwarding(uint32_t interface) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsUp(uint32_t interface) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SelectSourceAddress', 'ns3::Ipv4Address', [param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('SendWithHeader', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetDown(uint32_t interface) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetForwarding(uint32_t interface, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'interface'), param('bool', 'val')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetMetric(uint32_t interface, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'interface'), param('uint16_t', 'metric')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetUp(uint32_t interface) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SourceAddressSelection(uint32_t interface, ns3::Ipv4Address dest) [member function] cls.add_method('SourceAddressSelection', 'ns3::Ipv4Address', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'dest')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4::IF_ANY [variable] cls.add_static_attribute('IF_ANY', 'uint32_t const', is_const=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::GetWeakEsModel() const [member function] cls.add_method('GetWeakEsModel', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], is_pure_virtual=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetWeakEsModel(bool model) [member function] cls.add_method('SetWeakEsModel', 'void', [param('bool', 'model')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3Ipv4AddressChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [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::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Address const &', 'value')]) return def register_Ns3Ipv4Interface_methods(root_module, cls): ## ipv4-interface.h (module 'internet'): static ns3::TypeId ns3::Ipv4Interface::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-interface.h (module 'internet'): ns3::Ipv4Interface::Ipv4Interface() [constructor] cls.add_constructor([]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetTrafficControl(ns3::Ptr<ns3::TrafficControlLayer> tc) [member function] cls.add_method('SetTrafficControl', 'void', [param('ns3::Ptr< ns3::TrafficControlLayer >', 'tc')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetArpCache(ns3::Ptr<ns3::ArpCache> arpCache) [member function] cls.add_method('SetArpCache', 'void', [param('ns3::Ptr< ns3::ArpCache >', 'arpCache')]) ## ipv4-interface.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Interface::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## ipv4-interface.h (module 'internet'): ns3::Ptr<ns3::ArpCache> ns3::Ipv4Interface::GetArpCache() const [member function] cls.add_method('GetArpCache', 'ns3::Ptr< ns3::ArpCache >', [], is_const=True) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetMetric(uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint16_t', 'metric')]) ## ipv4-interface.h (module 'internet'): uint16_t ns3::Ipv4Interface::GetMetric() const [member function] cls.add_method('GetMetric', 'uint16_t', [], is_const=True) ## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::IsUp() const [member function] cls.add_method('IsUp', 'bool', [], is_const=True) ## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::IsDown() const [member function] cls.add_method('IsDown', 'bool', [], is_const=True) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetUp() [member function] cls.add_method('SetUp', 'void', []) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetDown() [member function] cls.add_method('SetDown', 'void', []) ## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::IsForwarding() const [member function] cls.add_method('IsForwarding', 'bool', [], is_const=True) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetForwarding(bool val) [member function] cls.add_method('SetForwarding', 'void', [param('bool', 'val')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::Send(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & hdr, ns3::Ipv4Address dest) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'hdr'), param('ns3::Ipv4Address', 'dest')]) ## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::AddAddress(ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('ns3::Ipv4InterfaceAddress', 'address')]) ## ipv4-interface.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4Interface::GetAddress(uint32_t index) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'index')], is_const=True) ## ipv4-interface.h (module 'internet'): uint32_t ns3::Ipv4Interface::GetNAddresses() const [member function] cls.add_method('GetNAddresses', 'uint32_t', [], is_const=True) ## ipv4-interface.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4Interface::RemoveAddress(uint32_t index) [member function] cls.add_method('RemoveAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'index')]) ## ipv4-interface.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4Interface::RemoveAddress(ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'ns3::Ipv4InterfaceAddress', [param('ns3::Ipv4Address', 'address')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3Ipv4L3Protocol_methods(root_module, cls): ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::Ipv4L3Protocol() [constructor] cls.add_constructor([]) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::AddAddress(uint32_t i, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'i'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4L3Protocol::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', [], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4L3Protocol::GetAddress(uint32_t interfaceIndex, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Interface> ns3::Ipv4L3Protocol::GetInterface(uint32_t i) const [member function] cls.add_method('GetInterface', 'ns3::Ptr< ns3::Ipv4Interface >', [param('uint32_t', 'i')], is_const=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForAddress(ns3::Ipv4Address addr) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv4Address', 'addr')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForPrefix(ns3::Ipv4Address addr, ns3::Ipv4Mask mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv4Address', 'addr'), param('ns3::Ipv4Mask', 'mask')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMetric(uint32_t i) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMtu(uint32_t i) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4L3Protocol::GetNetDevice(uint32_t i) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4L3Protocol::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4L3Protocol::GetProtocol(int protocolNumber, int32_t interfaceIndex) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber'), param('int32_t', 'interfaceIndex')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4L3Protocol::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4L3Protocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function] cls.add_method('IsDestinationAddress', 'bool', [param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsForwarding(uint32_t i) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsUnicast(ns3::Ipv4Address ad) const [member function] cls.add_method('IsUnicast', 'bool', [param('ns3::Ipv4Address', 'ad')], is_const=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsUp(uint32_t i) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Receive(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> p, uint16_t protocol, ns3::Address const & from, ns3::Address const & to, ns3::NetDevice::PacketType packetType) [member function] cls.add_method('Receive', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'p'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'from'), param('ns3::Address const &', 'to'), param('ns3::NetDevice::PacketType', 'packetType')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::RemoveAddress(uint32_t interfaceIndex, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::RemoveAddress(uint32_t interface, ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'address')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4L3Protocol::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SelectSourceAddress', 'ns3::Ipv4Address', [param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('SendWithHeader', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDefaultTtl(uint8_t ttl) [member function] cls.add_method('SetDefaultTtl', 'void', [param('uint8_t', 'ttl')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDown(uint32_t i) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetForwarding(uint32_t i, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'i'), param('bool', 'val')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetMetric(uint32_t i, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'i'), param('uint16_t', 'metric')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetUp(uint32_t i) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4L3Protocol::SourceAddressSelection(uint32_t interface, ns3::Ipv4Address dest) [member function] cls.add_method('SourceAddressSelection', 'ns3::Ipv4Address', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'dest')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::PROT_NUMBER [variable] cls.add_static_attribute('PROT_NUMBER', 'uint16_t const', is_const=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetWeakEsModel() const [member function] cls.add_method('GetWeakEsModel', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetWeakEsModel(bool model) [member function] cls.add_method('SetWeakEsModel', 'void', [param('bool', 'model')], visibility='private', is_virtual=True) return def register_Ns3Ipv4MaskChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [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::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Mask const &', 'value')]) return def register_Ns3Ipv4MulticastRoute_methods(root_module, cls): ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute(ns3::Ipv4MulticastRoute const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4MulticastRoute const &', 'arg0')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute() [constructor] cls.add_constructor([]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetGroup() const [member function] cls.add_method('GetGroup', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetOrigin() const [member function] cls.add_method('GetOrigin', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): std::map<unsigned int, unsigned int, std::less<unsigned int>, std::allocator<std::pair<const unsigned int, unsigned int> > > ns3::Ipv4MulticastRoute::GetOutputTtlMap() const [member function] cls.add_method('GetOutputTtlMap', 'std::map< unsigned int, unsigned int >', [], is_const=True) ## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetParent() const [member function] cls.add_method('GetParent', 'uint32_t', [], is_const=True) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetGroup(ns3::Ipv4Address const group) [member function] cls.add_method('SetGroup', 'void', [param('ns3::Ipv4Address const', 'group')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOrigin(ns3::Ipv4Address const origin) [member function] cls.add_method('SetOrigin', 'void', [param('ns3::Ipv4Address const', 'origin')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOutputTtl(uint32_t oif, uint32_t ttl) [member function] cls.add_method('SetOutputTtl', 'void', [param('uint32_t', 'oif'), param('uint32_t', 'ttl')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetParent(uint32_t iif) [member function] cls.add_method('SetParent', 'void', [param('uint32_t', 'iif')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_INTERFACES [variable] cls.add_static_attribute('MAX_INTERFACES', 'uint32_t const', is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_TTL [variable] cls.add_static_attribute('MAX_TTL', 'uint32_t const', is_const=True) return def register_Ns3Ipv4Route_methods(root_module, cls): cls.add_output_stream_operator() ## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route(ns3::Ipv4Route const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4Route const &', 'arg0')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route() [constructor] cls.add_constructor([]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetGateway() const [member function] cls.add_method('GetGateway', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Route::GetOutputDevice() const [member function] cls.add_method('GetOutputDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetDestination(ns3::Ipv4Address dest) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'dest')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetGateway(ns3::Ipv4Address gw) [member function] cls.add_method('SetGateway', 'void', [param('ns3::Ipv4Address', 'gw')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetOutputDevice(ns3::Ptr<ns3::NetDevice> outputDevice) [member function] cls.add_method('SetOutputDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'outputDevice')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetSource(ns3::Ipv4Address src) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'src')]) return def register_Ns3Ipv4RoutingProtocol_methods(root_module, cls): ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol() [constructor] cls.add_constructor([]) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol(ns3::Ipv4RoutingProtocol const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4RoutingProtocol const &', 'arg0')]) ## ipv4-routing-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4RoutingProtocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): bool ns3::Ipv4RoutingProtocol::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Ipv4RoutingProtocol::UnicastForwardCallback ucb, ns3::Ipv4RoutingProtocol::MulticastForwardCallback mcb, ns3::Ipv4RoutingProtocol::LocalDeliverCallback lcb, ns3::Ipv4RoutingProtocol::ErrorCallback ecb) [member function] cls.add_method('RouteInput', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv4Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], is_pure_virtual=True, is_virtual=True) return def register_Ns3Ipv6AddressChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [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::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Prefix const &', 'value')]) return def register_Ns3LogNormalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::LogNormalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable::LogNormalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetMu() const [member function] cls.add_method('GetMu', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetSigma() const [member function] cls.add_method('GetSigma', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue(double mu, double sigma) [member function] cls.add_method('GetValue', 'double', [param('double', 'mu'), param('double', 'sigma')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger(uint32_t mu, uint32_t sigma) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mu'), param('uint32_t', 'sigma')]) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3Mac48AddressChecker_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [constructor] cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')]) return def register_Ns3Mac48AddressValue_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'value')]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [constructor] cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac48AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): bool ns3::Mac48AddressValue::DeserializeFromString(std::string value, ns3::Ptr<const ns3::AttributeChecker> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## mac48-address.h (module 'network'): ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Mac48Address', [], is_const=True) ## mac48-address.h (module 'network'): std::string ns3::Mac48AddressValue::SerializeToString(ns3::Ptr<const ns3::AttributeChecker> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): void ns3::Mac48AddressValue::Set(ns3::Mac48Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Mac48Address const &', 'value')]) return def register_Ns3NetDevice_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [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::NetDevice::PromiscReceiveCallback 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_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::NetDevice::ReceiveCallback 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_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_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [constructor] cls.add_constructor([param('ns3::NixVector const &', 'o')]) ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] cls.add_method('AddNeighborIndex', 'void', [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] cls.add_method('BitCount', 'uint32_t', [param('uint32_t', 'numberOfNeighbors')], is_const=True) ## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] cls.add_method('ExtractNeighborIndex', 'uint32_t', [param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] cls.add_method('GetRemainingBits', 'uint32_t', []) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3Node_methods(root_module, cls): ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [constructor] cls.add_constructor([param('ns3::Node const &', 'arg0')]) ## node.h (module 'network'): ns3::Node::Node() [constructor] cls.add_constructor([]) ## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor] cls.add_constructor([param('uint32_t', 'systemId')]) ## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('AddApplication', 'uint32_t', [param('ns3::Ptr< ns3::Application >', 'application')]) ## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddDevice', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function] cls.add_method('ChecksumEnabled', 'bool', [], is_static=True) ## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function] cls.add_method('GetApplication', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): ns3::Time ns3::Node::GetLocalTime() const [member function] cls.add_method('GetLocalTime', 'ns3::Time', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Node::DeviceAdditionListener 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::Node::ProtocolHandler 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::Node::DeviceAdditionListener 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::Node::ProtocolHandler handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3NormalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::INFINITE_VALUE [variable] cls.add_static_attribute('INFINITE_VALUE', 'double const', is_const=True) ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::NormalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::NormalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetVariance() const [member function] cls.add_method('GetVariance', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue(double mean, double variance, double bound=ns3::NormalRandomVariable::INFINITE_VALUE) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'variance'), param('double', 'bound', default_value='ns3::NormalRandomVariable::INFINITE_VALUE')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger(uint32_t mean, uint32_t variance, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'variance'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<const ns3::AttributeChecker> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<const ns3::AttributeChecker> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_Ns3OutputStreamWrapper_methods(root_module, cls): ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(ns3::OutputStreamWrapper const & arg0) [constructor] cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::ios_base::openmode filemode) [constructor] cls.add_constructor([param('std::string', 'filename'), param('std::ios_base::openmode', 'filemode')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor] cls.add_constructor([param('std::ostream *', 'os')]) ## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function] cls.add_method('GetStream', 'std::ostream *', []) return def register_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [constructor] cls.add_constructor([param('ns3::Packet const &', 'o')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] cls.add_constructor([param('uint32_t', 'size')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] cls.add_method('AddByteTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header')]) ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] cls.add_method('AddPacketTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer')]) ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] cls.add_method('EnablePrinting', 'void', [], is_static=True) ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] cls.add_method('FindFirstMatchingByteTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] cls.add_method('GetByteTagIterator', 'ns3::ByteTagIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function] cls.add_method('GetNixVector', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] cls.add_method('GetPacketTagIterator', 'ns3::PacketTagIterator', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function] cls.add_method('ReplacePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> nixVector) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'nixVector')]) ## packet.h (module 'network'): std::string ns3::Packet::ToString() const [member function] cls.add_method('ToString', 'std::string', [], is_const=True) return def register_Ns3ParetoRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ParetoRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable::ParetoRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetScale() const [member function] cls.add_method('GetScale', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetShape() const [member function] cls.add_method('GetShape', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue(double scale, double shape, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'scale'), param('double', 'shape'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger(uint32_t scale, uint32_t shape, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'scale'), param('uint32_t', 'shape'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3TimeValue_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] cls.add_constructor([]) ## 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::TimeValue::TimeValue(ns3::TimeValue const & arg0) [constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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::Address const & value) [constructor] cls.add_constructor([param('ns3::Address const &', 'value')]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [constructor] cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::Socket> arg0, ns3::Address const & arg1) [member operator] cls.add_method('operator()', 'bool', [param('ns3::Ptr< ns3::Socket >', 'arg0'), param('ns3::Address const &', 'arg1')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Ns3ObjectBase___star___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): ns3::ObjectBase * ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()() [member operator] cls.add_method('operator()', 'ns3::ObjectBase *', [], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Const_ns3Ipv4Header___amp___Ns3Ptr__lt__const_ns3Packet__gt___Ns3Ipv4L3ProtocolDropReason_Ns3Ptr__lt__ns3Ipv4__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr< ns3::Ipv4 >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ipv4Header const & arg0, ns3::Ptr<const ns3::Packet> arg1, ns3::Ipv4L3Protocol::DropReason arg2, ns3::Ptr<ns3::Ipv4> arg3, unsigned int arg4) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ipv4Header const &', 'arg0'), param('ns3::Ptr< ns3::Packet const >', 'arg1'), param('ns3::Ipv4L3Protocol::DropReason', 'arg2'), param('ns3::Ptr< ns3::Ipv4 >', 'arg3'), param('unsigned int', 'arg4')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Const_ns3Ipv4Header___amp___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ipv4Header const & arg0, ns3::Ptr<const ns3::Packet> arg1, unsigned int arg2) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ipv4Header const &', 'arg0'), param('ns3::Ptr< ns3::Packet const >', 'arg1'), param('unsigned int', 'arg2')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Const_ns3Ipv4Header___amp___Ns3SocketSocketErrno_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<const ns3::Packet> arg0, ns3::Ipv4Header const & arg1, ns3::Socket::SocketErrno arg2) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::Packet const >', 'arg0'), param('ns3::Ipv4Header const &', 'arg1'), param('ns3::Socket::SocketErrno', 'arg2')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Ns3Ptr__lt__ns3Ipv4__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Packet const >, ns3::Ptr< ns3::Ipv4 >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<const ns3::Packet> arg0, ns3::Ptr<ns3::Ipv4> arg1, unsigned int arg2) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::Packet const >', 'arg0'), param('ns3::Ptr< ns3::Ipv4 >', 'arg1'), param('unsigned int', 'arg2')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Ipv4Route__gt___Ns3Ptr__lt__const_ns3Packet__gt___Const_ns3Ipv4Header___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::Ipv4Route> arg0, ns3::Ptr<const ns3::Packet> arg1, ns3::Ipv4Header const & arg2) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::Ipv4Route >', 'arg0'), param('ns3::Ptr< ns3::Packet const >', 'arg1'), param('ns3::Ipv4Header const &', 'arg2')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Const_ns3Address___amp___Const_ns3Address___amp___Ns3NetDevicePacketType_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< 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 > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::NetDevice> arg0, ns3::Ptr<const ns3::Packet> arg1, short unsigned int arg2, ns3::Address const & arg3, ns3::Address const & arg4, ns3::NetDevice::PacketType arg5) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'arg0'), param('ns3::Ptr< ns3::Packet const >', 'arg1'), param('short unsigned int', 'arg2'), param('ns3::Address const &', 'arg3'), param('ns3::Address const &', 'arg4'), param('ns3::NetDevice::PacketType', 'arg5')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::NetDevice> arg0) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'arg0')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::Socket> arg0, ns3::Address const & arg1) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::Socket >', 'arg0'), param('ns3::Address const &', 'arg1')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::Socket> arg0) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::Socket >', 'arg0')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::Socket> arg0, unsigned int arg1) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::Socket >', 'arg0'), param('unsigned int', 'arg1')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3Ipv4ListRouting_methods(root_module, cls): ## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting::Ipv4ListRouting(ns3::Ipv4ListRouting const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4ListRouting const &', 'arg0')]) ## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting::Ipv4ListRouting() [constructor] cls.add_constructor([]) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::AddRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol, int16_t priority) [member function] cls.add_method('AddRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol'), param('int16_t', 'priority')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): uint32_t ns3::Ipv4ListRouting::GetNRoutingProtocols() const [member function] cls.add_method('GetNRoutingProtocols', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-list-routing.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4ListRouting::GetRoutingProtocol(uint32_t index, int16_t & priority) const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [param('uint32_t', 'index'), param('int16_t &', 'priority', direction=2)], is_const=True, is_virtual=True) ## ipv4-list-routing.h (module 'internet'): static ns3::TypeId ns3::Ipv4ListRouting::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')], is_const=True, is_virtual=True) ## ipv4-list-routing.h (module 'internet'): bool ns3::Ipv4ListRouting::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Ipv4RoutingProtocol::UnicastForwardCallback ucb, ns3::Ipv4RoutingProtocol::MulticastForwardCallback mcb, ns3::Ipv4RoutingProtocol::LocalDeliverCallback lcb, ns3::Ipv4RoutingProtocol::ErrorCallback ecb) [member function] cls.add_method('RouteInput', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4ListRouting::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv4Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3HashImplementation_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [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) [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) [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) [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) [constructor] cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')]) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor] cls.add_constructor([]) ## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3DsdvDsdvHeader_methods(root_module, cls): cls.add_output_stream_operator() ## dsdv-packet.h (module 'dsdv'): ns3::dsdv::DsdvHeader::DsdvHeader(ns3::dsdv::DsdvHeader const & arg0) [constructor] cls.add_constructor([param('ns3::dsdv::DsdvHeader const &', 'arg0')]) ## dsdv-packet.h (module 'dsdv'): ns3::dsdv::DsdvHeader::DsdvHeader(ns3::Ipv4Address dst=ns3::Ipv4Address(), uint32_t hopcount=0, uint32_t dstSeqNo=0) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'dst', default_value='ns3::Ipv4Address()'), param('uint32_t', 'hopcount', default_value='0'), param('uint32_t', 'dstSeqNo', default_value='0')]) ## dsdv-packet.h (module 'dsdv'): uint32_t ns3::dsdv::DsdvHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## dsdv-packet.h (module 'dsdv'): ns3::Ipv4Address ns3::dsdv::DsdvHeader::GetDst() const [member function] cls.add_method('GetDst', 'ns3::Ipv4Address', [], is_const=True) ## dsdv-packet.h (module 'dsdv'): uint32_t ns3::dsdv::DsdvHeader::GetDstSeqno() const [member function] cls.add_method('GetDstSeqno', 'uint32_t', [], is_const=True) ## dsdv-packet.h (module 'dsdv'): uint32_t ns3::dsdv::DsdvHeader::GetHopCount() const [member function] cls.add_method('GetHopCount', 'uint32_t', [], is_const=True) ## dsdv-packet.h (module 'dsdv'): ns3::TypeId ns3::dsdv::DsdvHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## dsdv-packet.h (module 'dsdv'): uint32_t ns3::dsdv::DsdvHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## dsdv-packet.h (module 'dsdv'): static ns3::TypeId ns3::dsdv::DsdvHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## dsdv-packet.h (module 'dsdv'): void ns3::dsdv::DsdvHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## dsdv-packet.h (module 'dsdv'): void ns3::dsdv::DsdvHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## dsdv-packet.h (module 'dsdv'): void ns3::dsdv::DsdvHeader::SetDst(ns3::Ipv4Address destination) [member function] cls.add_method('SetDst', 'void', [param('ns3::Ipv4Address', 'destination')]) ## dsdv-packet.h (module 'dsdv'): void ns3::dsdv::DsdvHeader::SetDstSeqno(uint32_t sequenceNumber) [member function] cls.add_method('SetDstSeqno', 'void', [param('uint32_t', 'sequenceNumber')]) ## dsdv-packet.h (module 'dsdv'): void ns3::dsdv::DsdvHeader::SetHopCount(uint32_t hopCount) [member function] cls.add_method('SetHopCount', 'void', [param('uint32_t', 'hopCount')]) return def register_Ns3DsdvPacketQueue_methods(root_module, cls): ## dsdv-packet-queue.h (module 'dsdv'): ns3::dsdv::PacketQueue::PacketQueue(ns3::dsdv::PacketQueue const & arg0) [constructor] cls.add_constructor([param('ns3::dsdv::PacketQueue const &', 'arg0')]) ## dsdv-packet-queue.h (module 'dsdv'): ns3::dsdv::PacketQueue::PacketQueue() [constructor] cls.add_constructor([]) ## dsdv-packet-queue.h (module 'dsdv'): bool ns3::dsdv::PacketQueue::Dequeue(ns3::Ipv4Address dst, ns3::dsdv::QueueEntry & entry) [member function] cls.add_method('Dequeue', 'bool', [param('ns3::Ipv4Address', 'dst'), param('ns3::dsdv::QueueEntry &', 'entry')]) ## dsdv-packet-queue.h (module 'dsdv'): void ns3::dsdv::PacketQueue::DropPacketWithDst(ns3::Ipv4Address dst) [member function] cls.add_method('DropPacketWithDst', 'void', [param('ns3::Ipv4Address', 'dst')]) ## dsdv-packet-queue.h (module 'dsdv'): bool ns3::dsdv::PacketQueue::Enqueue(ns3::dsdv::QueueEntry & entry) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::dsdv::QueueEntry &', 'entry')]) ## dsdv-packet-queue.h (module 'dsdv'): bool ns3::dsdv::PacketQueue::Find(ns3::Ipv4Address dst) [member function] cls.add_method('Find', 'bool', [param('ns3::Ipv4Address', 'dst')]) ## dsdv-packet-queue.h (module 'dsdv'): uint32_t ns3::dsdv::PacketQueue::GetCountForPacketsWithDst(ns3::Ipv4Address dst) [member function] cls.add_method('GetCountForPacketsWithDst', 'uint32_t', [param('ns3::Ipv4Address', 'dst')]) ## dsdv-packet-queue.h (module 'dsdv'): uint32_t ns3::dsdv::PacketQueue::GetMaxPacketsPerDst() const [member function] cls.add_method('GetMaxPacketsPerDst', 'uint32_t', [], is_const=True) ## dsdv-packet-queue.h (module 'dsdv'): uint32_t ns3::dsdv::PacketQueue::GetMaxQueueLen() const [member function] cls.add_method('GetMaxQueueLen', 'uint32_t', [], is_const=True) ## dsdv-packet-queue.h (module 'dsdv'): ns3::Time ns3::dsdv::PacketQueue::GetQueueTimeout() const [member function] cls.add_method('GetQueueTimeout', 'ns3::Time', [], is_const=True) ## dsdv-packet-queue.h (module 'dsdv'): uint32_t ns3::dsdv::PacketQueue::GetSize() [member function] cls.add_method('GetSize', 'uint32_t', []) ## dsdv-packet-queue.h (module 'dsdv'): void ns3::dsdv::PacketQueue::SetMaxPacketsPerDst(uint32_t len) [member function] cls.add_method('SetMaxPacketsPerDst', 'void', [param('uint32_t', 'len')]) ## dsdv-packet-queue.h (module 'dsdv'): void ns3::dsdv::PacketQueue::SetMaxQueueLen(uint32_t len) [member function] cls.add_method('SetMaxQueueLen', 'void', [param('uint32_t', 'len')]) ## dsdv-packet-queue.h (module 'dsdv'): void ns3::dsdv::PacketQueue::SetQueueTimeout(ns3::Time t) [member function] cls.add_method('SetQueueTimeout', 'void', [param('ns3::Time', 't')]) return def register_Ns3DsdvQueueEntry_methods(root_module, cls): cls.add_binary_comparison_operator('==') ## dsdv-packet-queue.h (module 'dsdv'): ns3::dsdv::QueueEntry::QueueEntry(ns3::dsdv::QueueEntry const & arg0) [constructor] cls.add_constructor([param('ns3::dsdv::QueueEntry const &', 'arg0')]) ## dsdv-packet-queue.h (module 'dsdv'): ns3::dsdv::QueueEntry::QueueEntry(ns3::Ptr<const ns3::Packet> pa=0, ns3::Ipv4Header const & h=ns3::Ipv4Header(), ns3::dsdv::QueueEntry::UnicastForwardCallback ucb=::ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>( ), ns3::dsdv::QueueEntry::ErrorCallback ecb=::ns3::Callback<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>( )) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Packet const >', 'pa', default_value='0'), param('ns3::Ipv4Header const &', 'h', default_value='ns3::Ipv4Header()'), param('ns3::dsdv::QueueEntry::UnicastForwardCallback', 'ucb', default_value='::ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>( )'), param('ns3::dsdv::QueueEntry::ErrorCallback', 'ecb', default_value='::ns3::Callback<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>( )')]) ## dsdv-packet-queue.h (module 'dsdv'): ns3::dsdv::QueueEntry::ErrorCallback ns3::dsdv::QueueEntry::GetErrorCallback() const [member function] cls.add_method('GetErrorCallback', 'ns3::dsdv::QueueEntry::ErrorCallback', [], is_const=True) ## dsdv-packet-queue.h (module 'dsdv'): ns3::Time ns3::dsdv::QueueEntry::GetExpireTime() const [member function] cls.add_method('GetExpireTime', 'ns3::Time', [], is_const=True) ## dsdv-packet-queue.h (module 'dsdv'): ns3::Ipv4Header ns3::dsdv::QueueEntry::GetIpv4Header() const [member function] cls.add_method('GetIpv4Header', 'ns3::Ipv4Header', [], is_const=True) ## dsdv-packet-queue.h (module 'dsdv'): ns3::Ptr<const ns3::Packet> ns3::dsdv::QueueEntry::GetPacket() const [member function] cls.add_method('GetPacket', 'ns3::Ptr< ns3::Packet const >', [], is_const=True) ## dsdv-packet-queue.h (module 'dsdv'): ns3::dsdv::QueueEntry::UnicastForwardCallback ns3::dsdv::QueueEntry::GetUnicastForwardCallback() const [member function] cls.add_method('GetUnicastForwardCallback', 'ns3::dsdv::QueueEntry::UnicastForwardCallback', [], is_const=True) ## dsdv-packet-queue.h (module 'dsdv'): void ns3::dsdv::QueueEntry::SetErrorCallback(ns3::dsdv::QueueEntry::ErrorCallback ecb) [member function] cls.add_method('SetErrorCallback', 'void', [param('ns3::Ipv4RoutingProtocol::ErrorCallback', 'ecb')]) ## dsdv-packet-queue.h (module 'dsdv'): void ns3::dsdv::QueueEntry::SetExpireTime(ns3::Time exp) [member function] cls.add_method('SetExpireTime', 'void', [param('ns3::Time', 'exp')]) ## dsdv-packet-queue.h (module 'dsdv'): void ns3::dsdv::QueueEntry::SetIpv4Header(ns3::Ipv4Header h) [member function] cls.add_method('SetIpv4Header', 'void', [param('ns3::Ipv4Header', 'h')]) ## dsdv-packet-queue.h (module 'dsdv'): void ns3::dsdv::QueueEntry::SetPacket(ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('SetPacket', 'void', [param('ns3::Ptr< ns3::Packet const >', 'p')]) ## dsdv-packet-queue.h (module 'dsdv'): void ns3::dsdv::QueueEntry::SetUnicastForwardCallback(ns3::dsdv::QueueEntry::UnicastForwardCallback ucb) [member function] cls.add_method('SetUnicastForwardCallback', 'void', [param('ns3::Ipv4RoutingProtocol::UnicastForwardCallback', 'ucb')]) return def register_Ns3DsdvRoutingProtocol_methods(root_module, cls): ## dsdv-routing-protocol.h (module 'dsdv'): ns3::dsdv::RoutingProtocol::RoutingProtocol(ns3::dsdv::RoutingProtocol const & arg0) [constructor] cls.add_constructor([param('ns3::dsdv::RoutingProtocol const &', 'arg0')]) ## dsdv-routing-protocol.h (module 'dsdv'): ns3::dsdv::RoutingProtocol::RoutingProtocol() [constructor] cls.add_constructor([]) ## dsdv-routing-protocol.h (module 'dsdv'): int64_t ns3::dsdv::RoutingProtocol::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## dsdv-routing-protocol.h (module 'dsdv'): bool ns3::dsdv::RoutingProtocol::GetEnableBufferFlag() const [member function] cls.add_method('GetEnableBufferFlag', 'bool', [], is_const=True) ## dsdv-routing-protocol.h (module 'dsdv'): bool ns3::dsdv::RoutingProtocol::GetEnableRAFlag() const [member function] cls.add_method('GetEnableRAFlag', 'bool', [], is_const=True) ## dsdv-routing-protocol.h (module 'dsdv'): static ns3::TypeId ns3::dsdv::RoutingProtocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## dsdv-routing-protocol.h (module 'dsdv'): bool ns3::dsdv::RoutingProtocol::GetWSTFlag() const [member function] cls.add_method('GetWSTFlag', 'bool', [], is_const=True) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], is_virtual=True) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], is_virtual=True) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')], is_const=True, is_virtual=True) ## dsdv-routing-protocol.h (module 'dsdv'): bool ns3::dsdv::RoutingProtocol::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Ipv4RoutingProtocol::UnicastForwardCallback ucb, ns3::Ipv4RoutingProtocol::MulticastForwardCallback mcb, ns3::Ipv4RoutingProtocol::LocalDeliverCallback lcb, ns3::Ipv4RoutingProtocol::ErrorCallback ecb) [member function] cls.add_method('RouteInput', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')], is_virtual=True) ## dsdv-routing-protocol.h (module 'dsdv'): ns3::Ptr<ns3::Ipv4Route> ns3::dsdv::RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv4Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], is_virtual=True) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::SetEnableBufferFlag(bool f) [member function] cls.add_method('SetEnableBufferFlag', 'void', [param('bool', 'f')]) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::SetEnableRAFlag(bool f) [member function] cls.add_method('SetEnableRAFlag', 'void', [param('bool', 'f')]) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], is_virtual=True) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::SetWSTFlag(bool f) [member function] cls.add_method('SetWSTFlag', 'void', [param('bool', 'f')]) ## dsdv-routing-protocol.h (module 'dsdv'): ns3::dsdv::RoutingProtocol::DSDV_PORT [variable] cls.add_static_attribute('DSDV_PORT', 'uint32_t const', is_const=True) return def register_Ns3DsdvRoutingTable_methods(root_module, cls): ## dsdv-rtable.h (module 'dsdv'): ns3::dsdv::RoutingTable::RoutingTable(ns3::dsdv::RoutingTable const & arg0) [constructor] cls.add_constructor([param('ns3::dsdv::RoutingTable const &', 'arg0')]) ## dsdv-rtable.h (module 'dsdv'): ns3::dsdv::RoutingTable::RoutingTable() [constructor] cls.add_constructor([]) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTable::AddIpv4Event(ns3::Ipv4Address address, ns3::EventId id) [member function] cls.add_method('AddIpv4Event', 'bool', [param('ns3::Ipv4Address', 'address'), param('ns3::EventId', 'id')]) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTable::AddRoute(ns3::dsdv::RoutingTableEntry & r) [member function] cls.add_method('AddRoute', 'bool', [param('ns3::dsdv::RoutingTableEntry &', 'r')]) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTable::AnyRunningEvent(ns3::Ipv4Address address) [member function] cls.add_method('AnyRunningEvent', 'bool', [param('ns3::Ipv4Address', 'address')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTable::Clear() [member function] cls.add_method('Clear', 'void', []) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTable::DeleteAllRoutesFromInterface(ns3::Ipv4InterfaceAddress iface) [member function] cls.add_method('DeleteAllRoutesFromInterface', 'void', [param('ns3::Ipv4InterfaceAddress', 'iface')]) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTable::DeleteIpv4Event(ns3::Ipv4Address address) [member function] cls.add_method('DeleteIpv4Event', 'bool', [param('ns3::Ipv4Address', 'address')]) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTable::DeleteRoute(ns3::Ipv4Address dst) [member function] cls.add_method('DeleteRoute', 'bool', [param('ns3::Ipv4Address', 'dst')]) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTable::ForceDeleteIpv4Event(ns3::Ipv4Address address) [member function] cls.add_method('ForceDeleteIpv4Event', 'bool', [param('ns3::Ipv4Address', 'address')]) ## dsdv-rtable.h (module 'dsdv'): ns3::EventId ns3::dsdv::RoutingTable::GetEventId(ns3::Ipv4Address address) [member function] cls.add_method('GetEventId', 'ns3::EventId', [param('ns3::Ipv4Address', 'address')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTable::GetListOfAllRoutes(std::map<ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry, std::less<ns3::Ipv4Address>, std::allocator<std::pair<const ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry> > > & allRoutes) [member function] cls.add_method('GetListOfAllRoutes', 'void', [param('std::map< ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry > &', 'allRoutes')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTable::GetListOfDestinationWithNextHop(ns3::Ipv4Address nxtHp, std::map<ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry, std::less<ns3::Ipv4Address>, std::allocator<std::pair<const ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry> > > & dstList) [member function] cls.add_method('GetListOfDestinationWithNextHop', 'void', [param('ns3::Ipv4Address', 'nxtHp'), param('std::map< ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry > &', 'dstList')]) ## dsdv-rtable.h (module 'dsdv'): ns3::Time ns3::dsdv::RoutingTable::Getholddowntime() const [member function] cls.add_method('Getholddowntime', 'ns3::Time', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTable::LookupRoute(ns3::Ipv4Address dst, ns3::dsdv::RoutingTableEntry & rt) [member function] cls.add_method('LookupRoute', 'bool', [param('ns3::Ipv4Address', 'dst'), param('ns3::dsdv::RoutingTableEntry &', 'rt')]) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTable::LookupRoute(ns3::Ipv4Address id, ns3::dsdv::RoutingTableEntry & rt, bool forRouteInput) [member function] cls.add_method('LookupRoute', 'bool', [param('ns3::Ipv4Address', 'id'), param('ns3::dsdv::RoutingTableEntry &', 'rt'), param('bool', 'forRouteInput')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTable::Print(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('Print', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_const=True) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTable::Purge(std::map<ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry, std::less<ns3::Ipv4Address>, std::allocator<std::pair<const ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry> > > & removedAddresses) [member function] cls.add_method('Purge', 'void', [param('std::map< ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry > &', 'removedAddresses')]) ## dsdv-rtable.h (module 'dsdv'): uint32_t ns3::dsdv::RoutingTable::RoutingTableSize() [member function] cls.add_method('RoutingTableSize', 'uint32_t', []) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTable::Setholddowntime(ns3::Time t) [member function] cls.add_method('Setholddowntime', 'void', [param('ns3::Time', 't')]) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTable::Update(ns3::dsdv::RoutingTableEntry & rt) [member function] cls.add_method('Update', 'bool', [param('ns3::dsdv::RoutingTableEntry &', 'rt')]) return def register_Ns3DsdvRoutingTableEntry_methods(root_module, cls): ## dsdv-rtable.h (module 'dsdv'): ns3::dsdv::RoutingTableEntry::RoutingTableEntry(ns3::dsdv::RoutingTableEntry const & arg0) [constructor] cls.add_constructor([param('ns3::dsdv::RoutingTableEntry const &', 'arg0')]) ## dsdv-rtable.h (module 'dsdv'): ns3::dsdv::RoutingTableEntry::RoutingTableEntry(ns3::Ptr<ns3::NetDevice> dev=0, ns3::Ipv4Address dst=ns3::Ipv4Address(), uint32_t seqNo=0, ns3::Ipv4InterfaceAddress iface=ns3::Ipv4InterfaceAddress(), uint32_t hops=0, ns3::Ipv4Address nextHop=ns3::Ipv4Address(), ns3::Time lifetime=ns3::Simulator::Now(), ns3::Time SettlingTime=ns3::Simulator::Now(), bool changedEntries=false) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev', default_value='0'), param('ns3::Ipv4Address', 'dst', default_value='ns3::Ipv4Address()'), param('uint32_t', 'seqNo', default_value='0'), param('ns3::Ipv4InterfaceAddress', 'iface', default_value='ns3::Ipv4InterfaceAddress()'), param('uint32_t', 'hops', default_value='0'), param('ns3::Ipv4Address', 'nextHop', default_value='ns3::Ipv4Address()'), param('ns3::Time', 'lifetime', default_value='ns3::Simulator::Now()'), param('ns3::Time', 'SettlingTime', default_value='ns3::Simulator::Now()'), param('bool', 'changedEntries', default_value='false')]) ## dsdv-rtable.h (module 'dsdv'): ns3::Ipv4Address ns3::dsdv::RoutingTableEntry::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTableEntry::GetEntriesChanged() const [member function] cls.add_method('GetEntriesChanged', 'bool', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): ns3::dsdv::RouteFlags ns3::dsdv::RoutingTableEntry::GetFlag() const [member function] cls.add_method('GetFlag', 'ns3::dsdv::RouteFlags', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): uint32_t ns3::dsdv::RoutingTableEntry::GetHop() const [member function] cls.add_method('GetHop', 'uint32_t', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): ns3::Ipv4InterfaceAddress ns3::dsdv::RoutingTableEntry::GetInterface() const [member function] cls.add_method('GetInterface', 'ns3::Ipv4InterfaceAddress', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): ns3::Time ns3::dsdv::RoutingTableEntry::GetLifeTime() const [member function] cls.add_method('GetLifeTime', 'ns3::Time', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): ns3::Ipv4Address ns3::dsdv::RoutingTableEntry::GetNextHop() const [member function] cls.add_method('GetNextHop', 'ns3::Ipv4Address', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): ns3::Ptr<ns3::NetDevice> ns3::dsdv::RoutingTableEntry::GetOutputDevice() const [member function] cls.add_method('GetOutputDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): ns3::Ptr<ns3::Ipv4Route> ns3::dsdv::RoutingTableEntry::GetRoute() const [member function] cls.add_method('GetRoute', 'ns3::Ptr< ns3::Ipv4Route >', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): uint32_t ns3::dsdv::RoutingTableEntry::GetSeqNo() const [member function] cls.add_method('GetSeqNo', 'uint32_t', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): ns3::Time ns3::dsdv::RoutingTableEntry::GetSettlingTime() const [member function] cls.add_method('GetSettlingTime', 'ns3::Time', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::Print(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('Print', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_const=True) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetEntriesChanged(bool entriesChanged) [member function] cls.add_method('SetEntriesChanged', 'void', [param('bool', 'entriesChanged')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetFlag(ns3::dsdv::RouteFlags flag) [member function] cls.add_method('SetFlag', 'void', [param('ns3::dsdv::RouteFlags', 'flag')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetHop(uint32_t hopCount) [member function] cls.add_method('SetHop', 'void', [param('uint32_t', 'hopCount')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetInterface(ns3::Ipv4InterfaceAddress iface) [member function] cls.add_method('SetInterface', 'void', [param('ns3::Ipv4InterfaceAddress', 'iface')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetLifeTime(ns3::Time lifeTime) [member function] cls.add_method('SetLifeTime', 'void', [param('ns3::Time', 'lifeTime')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetNextHop(ns3::Ipv4Address nextHop) [member function] cls.add_method('SetNextHop', 'void', [param('ns3::Ipv4Address', 'nextHop')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetOutputDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('SetOutputDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetRoute(ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('SetRoute', 'void', [param('ns3::Ptr< ns3::Ipv4Route >', 'route')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetSeqNo(uint32_t sequenceNumber) [member function] cls.add_method('SetSeqNo', 'void', [param('uint32_t', 'sequenceNumber')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetSettlingTime(ns3::Time settlingTime) [member function] cls.add_method('SetSettlingTime', 'void', [param('ns3::Time', 'settlingTime')]) return def register_functions(root_module): module = root_module register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_Hash(module.get_submodule('Hash'), root_module) register_functions_ns3_TracedValueCallback(module.get_submodule('TracedValueCallback'), root_module) register_functions_ns3_dsdv(module.get_submodule('dsdv'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_Hash(module, root_module): register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module) return def register_functions_ns3_Hash_Function(module, root_module): return def register_functions_ns3_TracedValueCallback(module, root_module): return def register_functions_ns3_dsdv(module, root_module): return def 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
dmlc/tvm
python/tvm/relay/op/vision/_vision.py
3
3411
# 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. # pylint: disable=invalid-name, unused-argument """Definition of vision ops""" from __future__ import absolute_import from tvm import topi from tvm.te.hybrid import script from tvm.runtime import convert from .. import op as reg from .. import strategy from ..op import OpPattern # multibox_prior reg.register_strategy("vision.multibox_prior", strategy.multibox_prior_strategy) reg.register_pattern("vision.multibox_prior", OpPattern.OPAQUE) # multibox_transform_loc reg.register_strategy("vision.multibox_transform_loc", strategy.multibox_transform_loc_strategy) reg.register_pattern("vision.multibox_transform_loc", OpPattern.OPAQUE) # Get counts of valid boxes reg.register_strategy("vision.get_valid_counts", strategy.get_valid_counts_strategy) reg.register_pattern("vision.get_valid_counts", OpPattern.OPAQUE) # non-maximum suppression reg.register_strategy("vision.non_max_suppression", strategy.nms_strategy) reg.register_pattern("vision.non_max_suppression", OpPattern.OPAQUE) @script def _get_valid_counts_shape_func(data_shape): valid_counts_shape = output_tensor((1,), "int64") out_tensor_shape = output_tensor((data_shape.shape[0],), "int64") out_indices_shape = output_tensor((2,), "int64") valid_counts_shape[0] = data_shape[0] for i in const_range(data_shape.shape[0]): out_tensor_shape[i] = data_shape[i] out_indices_shape[0] = data_shape[0] out_indices_shape[1] = data_shape[1] return valid_counts_shape, out_tensor_shape, out_indices_shape @reg.register_shape_func("vision.get_valid_counts", False) def get_valid_counts_shape_func(attrs, inputs, _): return _get_valid_counts_shape_func(inputs[0]) @script def _nms_shape_func(data_shape): out_shape = output_tensor((2,), "int64") count_shape = output_tensor((2,), "int64") out_shape[0] = data_shape[0] out_shape[1] = data_shape[1] count_shape[0] = data_shape[0] count_shape[1] = int64(1) return out_shape, count_shape @reg.register_shape_func("vision.non_max_suppression", False) def nms_shape_func(attrs, inputs, _): if attrs.return_indices: return _nms_shape_func(inputs[0]) return [topi.math.identity(inputs[0])] @script def _roi_align_shape_func(data_shape, rois_shape, pooled_size): out = output_tensor((4,), "int64") out[0] = rois_shape[0] out[1] = data_shape[1] out[2] = int64(pooled_size[0]) out[3] = int64(pooled_size[1]) return out @reg.register_shape_func("vision.roi_align", False) def roi_align_shape_func(attrs, inputs, _): return [_roi_align_shape_func(inputs[0], inputs[1], convert(attrs.pooled_size))]
apache-2.0
pspacek/freeipa
ipatests/test_xmlrpc/test_replace.py
3
4816
# Authors: # Rob Crittenden <rcritten@redhat.com> # # Copyright (C) 2011 Red Hat # see file 'COPYING' for use and warranty information # # 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/>. """ Test the modlist replace logic. Some attributes require a MOD_REPLACE while others are fine using ADD/DELETE. Note that member management in other tests also exercises the gen_modlist code. """ from ipatests.test_xmlrpc.xmlrpc_test import Declarative from ipatests.test_xmlrpc.test_user_plugin import get_user_result user1=u'tuser1' class test_replace(Declarative): cleanup_commands = [ ('user_del', [user1], {}), ] tests = [ dict( desc='Create %r with 2 e-mail accounts' % user1, command=( 'user_add', [user1], dict(givenname=u'Test', sn=u'User1', mail=[u'test1@example.com', u'test2@example.com']) ), expected=dict( value=user1, summary=u'Added user "tuser1"', result=get_user_result( user1, u'Test', u'User1', 'add', mail=[u'test1@example.com', u'test2@example.com'], ), ), ), dict( desc='Drop one e-mail account, add another to %r' % user1, command=( 'user_mod', [user1], dict(mail=[u'test1@example.com', u'test3@example.com']) ), expected=dict( result=get_user_result( user1, u'Test', u'User1', 'mod', mail=[u'test1@example.com', u'test3@example.com'], ), summary=u'Modified user "tuser1"', value=user1, ), ), dict( desc='Set mail to a new single value %r' % user1, command=( 'user_mod', [user1], dict(mail=u'test4@example.com') ), expected=dict( result=get_user_result( user1, u'Test', u'User1', 'mod', mail=[u'test4@example.com'], ), summary=u'Modified user "tuser1"', value=user1, ), ), dict( desc='Set mail to three new values %r' % user1, command=( 'user_mod', [user1], dict(mail=[u'test5@example.com', u'test6@example.com', u'test7@example.com']) ), expected=dict( result=get_user_result( user1, u'Test', u'User1', 'mod', mail=[u'test5@example.com', u'test6@example.com', u'test7@example.com'], ), summary=u'Modified user "tuser1"', value=user1, ), ), dict( desc='Remove all mail values %r' % user1, command=( 'user_mod', [user1], dict(mail=u'') ), expected=dict( result=get_user_result( user1, u'Test', u'User1', 'mod', omit=['mail'], ), summary=u'Modified user "tuser1"', value=user1, ), ), dict( desc='Ensure single-value mods work too, replace initials %r' % user1, command=( 'user_mod', [user1], dict(initials=u'ABC') ), expected=dict( result=get_user_result( user1, u'Test', u'User1', 'mod', initials=[u'ABC'], omit=['mail'], ), summary=u'Modified user "tuser1"', value=user1, ), ), dict( desc='Drop a single-value attribute %r' % user1, command=( 'user_mod', [user1], dict(initials=u'') ), expected=dict( result=get_user_result( user1, u'Test', u'User1', 'mod', omit=['mail'], ), summary=u'Modified user "tuser1"', value=user1, ), ), ]
gpl-3.0
kidburglar/youtube-dl
youtube_dl/extractor/rtl2.py
12
7153
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..aes import aes_cbc_decrypt from ..compat import ( compat_b64decode, compat_ord, compat_str, ) from ..utils import ( bytes_to_intlist, ExtractorError, intlist_to_bytes, int_or_none, strip_or_none, ) class RTL2IE(InfoExtractor): IE_NAME = 'rtl2' _VALID_URL = r'http?://(?:www\.)?rtl2\.de/[^?#]*?/(?P<id>[^?#/]*?)(?:$|/(?:$|[?#]))' _TESTS = [{ 'url': 'http://www.rtl2.de/sendung/grip-das-motormagazin/folge/folge-203-0', 'info_dict': { 'id': 'folge-203-0', 'ext': 'f4v', 'title': 'GRIP sucht den Sommerkönig', 'description': 'md5:e3adbb940fd3c6e76fa341b8748b562f' }, 'params': { # rtmp download 'skip_download': True, }, }, { 'url': 'http://www.rtl2.de/sendung/koeln-50667/video/5512-anna/21040-anna-erwischt-alex/', 'info_dict': { 'id': '21040-anna-erwischt-alex', 'ext': 'mp4', 'title': 'Anna erwischt Alex!', 'description': 'Anna nimmt ihrem Vater nicht ab, dass er nicht spielt. Und tatsächlich erwischt sie ihn auf frischer Tat.' }, 'params': { # rtmp download 'skip_download': True, }, }] def _real_extract(self, url): # Some rtl2 urls have no slash at the end, so append it. if not url.endswith('/'): url += '/' video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) mobj = re.search( r'<div[^>]+data-collection="(?P<vico_id>\d+)"[^>]+data-video="(?P<vivi_id>\d+)"', webpage) if mobj: vico_id = mobj.group('vico_id') vivi_id = mobj.group('vivi_id') else: vico_id = self._html_search_regex( r'vico_id\s*:\s*([0-9]+)', webpage, 'vico_id') vivi_id = self._html_search_regex( r'vivi_id\s*:\s*([0-9]+)', webpage, 'vivi_id') info = self._download_json( 'http://www.rtl2.de/sites/default/modules/rtl2/mediathek/php/get_video_jw.php', video_id, query={ 'vico_id': vico_id, 'vivi_id': vivi_id, }) video_info = info['video'] title = video_info['titel'] formats = [] rtmp_url = video_info.get('streamurl') if rtmp_url: rtmp_url = rtmp_url.replace('\\', '') stream_url = 'mp4:' + self._html_search_regex(r'/ondemand/(.+)', rtmp_url, 'stream URL') rtmp_conn = ['S:connect', 'O:1', 'NS:pageUrl:' + url, 'NB:fpad:0', 'NN:videoFunction:1', 'O:0'] formats.append({ 'format_id': 'rtmp', 'url': rtmp_url, 'play_path': stream_url, 'player_url': 'http://www.rtl2.de/flashplayer/vipo_player.swf', 'page_url': url, 'flash_version': 'LNX 11,2,202,429', 'rtmp_conn': rtmp_conn, 'no_resume': True, 'preference': 1, }) m3u8_url = video_info.get('streamurl_hls') if m3u8_url: formats.extend(self._extract_akamai_formats(m3u8_url, video_id)) self._sort_formats(formats) return { 'id': video_id, 'title': title, 'thumbnail': video_info.get('image'), 'description': video_info.get('beschreibung'), 'duration': int_or_none(video_info.get('duration')), 'formats': formats, } class RTL2YouBaseIE(InfoExtractor): _BACKWERK_BASE_URL = 'https://p-you-backwerk.rtl2apps.de/' class RTL2YouIE(RTL2YouBaseIE): IE_NAME = 'rtl2:you' _VALID_URL = r'http?://you\.rtl2\.de/(?:video/\d+/|youplayer/index\.html\?.*?\bvid=)(?P<id>\d+)' _TESTS = [{ 'url': 'http://you.rtl2.de/video/3002/15740/MJUNIK%20%E2%80%93%20Home%20of%20YOU/307-hirn-wo-bist-du', 'info_dict': { 'id': '15740', 'ext': 'mp4', 'title': 'MJUNIK – Home of YOU - #307 Hirn, wo bist du?!', 'description': 'md5:ddaa95c61b372b12b66e115b2772fe01', 'age_limit': 12, }, }, { 'url': 'http://you.rtl2.de/youplayer/index.html?vid=15712', 'only_matching': True, }] _AES_KEY = b'\xe9W\xe4.<*\xb8\x1a\xd2\xb6\x92\xf3C\xd3\xefL\x1b\x03*\xbbbH\xc0\x03\xffo\xc2\xf2(\xaa\xaa!' _GEO_COUNTRIES = ['DE'] def _real_extract(self, url): video_id = self._match_id(url) stream_data = self._download_json( self._BACKWERK_BASE_URL + 'stream/video/' + video_id, video_id) data, iv = compat_b64decode(stream_data['streamUrl']).decode().split(':') stream_url = intlist_to_bytes(aes_cbc_decrypt( bytes_to_intlist(compat_b64decode(data)), bytes_to_intlist(self._AES_KEY), bytes_to_intlist(compat_b64decode(iv)) )) if b'rtl2_you_video_not_found' in stream_url: raise ExtractorError('video not found', expected=True) formats = self._extract_m3u8_formats( stream_url[:-compat_ord(stream_url[-1])].decode(), video_id, 'mp4', 'm3u8_native') self._sort_formats(formats) video_data = self._download_json( self._BACKWERK_BASE_URL + 'video/' + video_id, video_id) series = video_data.get('formatTitle') title = episode = video_data.get('title') or series if series and series != title: title = '%s - %s' % (series, title) return { 'id': video_id, 'title': title, 'formats': formats, 'description': strip_or_none(video_data.get('description')), 'thumbnail': video_data.get('image'), 'duration': int_or_none(stream_data.get('duration') or video_data.get('duration'), 1000), 'series': series, 'episode': episode, 'age_limit': int_or_none(video_data.get('minimumAge')), } class RTL2YouSeriesIE(RTL2YouBaseIE): IE_NAME = 'rtl2:you:series' _VALID_URL = r'http?://you\.rtl2\.de/videos/(?P<id>\d+)' _TEST = { 'url': 'http://you.rtl2.de/videos/115/dragon-ball', 'info_dict': { 'id': '115', }, 'playlist_mincount': 5, } def _real_extract(self, url): series_id = self._match_id(url) stream_data = self._download_json( self._BACKWERK_BASE_URL + 'videos', series_id, query={ 'formatId': series_id, 'limit': 1000000000, }) entries = [] for video in stream_data.get('videos', []): video_id = compat_str(video['videoId']) if not video_id: continue entries.append(self.url_result( 'http://you.rtl2.de/video/%s/%s' % (series_id, video_id), 'RTL2You', video_id)) return self.playlist_result(entries, series_id)
unlicense
postlund/home-assistant
homeassistant/components/volkszaehler/sensor.py
19
4129
"""Support for consuming values for the Volkszaehler API.""" from datetime import timedelta import logging from volkszaehler import Volkszaehler from volkszaehler.exceptions import VolkszaehlerApiConnectionError import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_HOST, CONF_MONITORED_CONDITIONS, CONF_NAME, CONF_PORT, ENERGY_WATT_HOUR, POWER_WATT, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) CONF_UUID = "uuid" DEFAULT_HOST = "localhost" DEFAULT_NAME = "Volkszaehler" DEFAULT_PORT = 80 MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=1) SENSOR_TYPES = { "average": ["Average", POWER_WATT, "mdi:power-off"], "consumption": ["Consumption", ENERGY_WATT_HOUR, "mdi:power-plug"], "max": ["Max", POWER_WATT, "mdi:arrow-up"], "min": ["Min", POWER_WATT, "mdi:arrow-down"], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_UUID): cv.string, vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_MONITORED_CONDITIONS, default=["average"]): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ), } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Volkszaehler sensors.""" host = config[CONF_HOST] name = config[CONF_NAME] port = config[CONF_PORT] uuid = config[CONF_UUID] conditions = config[CONF_MONITORED_CONDITIONS] session = async_get_clientsession(hass) vz_api = VolkszaehlerData( Volkszaehler(hass.loop, session, uuid, host=host, port=port) ) await vz_api.async_update() if vz_api.api.data is None: raise PlatformNotReady dev = [] for condition in conditions: dev.append(VolkszaehlerSensor(vz_api, name, condition)) async_add_entities(dev, True) class VolkszaehlerSensor(Entity): """Implementation of a Volkszaehler sensor.""" def __init__(self, vz_api, name, sensor_type): """Initialize the Volkszaehler sensor.""" self.vz_api = vz_api self._name = name self.type = sensor_type self._state = None @property def name(self): """Return the name of the sensor.""" return "{} {}".format(self._name, SENSOR_TYPES[self.type][0]) @property def icon(self): """Icon to use in the frontend, if any.""" return SENSOR_TYPES[self.type][2] @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return SENSOR_TYPES[self.type][1] @property def available(self): """Could the device be accessed during the last update call.""" return self.vz_api.available @property def state(self): """Return the state of the resources.""" return self._state async def async_update(self): """Get the latest data from REST API.""" await self.vz_api.async_update() if self.vz_api.api.data is not None: self._state = round(getattr(self.vz_api.api, self.type), 2) class VolkszaehlerData: """The class for handling the data retrieval from the Volkszaehler API.""" def __init__(self, api): """Initialize the data object.""" self.api = api self.available = True @Throttle(MIN_TIME_BETWEEN_UPDATES) async def async_update(self): """Get the latest data from the Volkszaehler REST API.""" try: await self.api.get_data() self.available = True except VolkszaehlerApiConnectionError: _LOGGER.error("Unable to fetch data from the Volkszaehler API") self.available = False
apache-2.0
lucywyman/slides-ii
v/lib/python2.7/site-packages/pygments/styles/fruity.py
135
1298
# -*- coding: utf-8 -*- """ pygments.styles.fruity ~~~~~~~~~~~~~~~~~~~~~~ pygments version of my "fruity" vim theme. :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style import Style from pygments.token import Token, Comment, Name, Keyword, \ Generic, Number, String, Whitespace class FruityStyle(Style): """ Pygments version of the "native" vim theme. """ background_color = '#111111' highlight_color = '#333333' styles = { Whitespace: '#888888', Token: '#ffffff', Generic.Output: '#444444 bg:#222222', Keyword: '#fb660a bold', Keyword.Pseudo: 'nobold', Number: '#0086f7 bold', Name.Tag: '#fb660a bold', Name.Variable: '#fb660a', Comment: '#008800 bg:#0f140f italic', Name.Attribute: '#ff0086 bold', String: '#0086d2', Name.Function: '#ff0086 bold', Generic.Heading: '#ffffff bold', Keyword.Type: '#cdcaa9 bold', Generic.Subheading: '#ffffff bold', Name.Constant: '#0086d2', Comment.Preproc: '#ff0007 bold' }
apache-2.0
caslei/TfModels
textsum/data_convert_example.py
26
2271
"""Example of Converting TextSum model data. Usage: python data_convert_example.py --command binary_to_text --in_file data/data --out_file data/text_data python data_convert_example.py --command text_to_binary --in_file data/text_data --out_file data/binary_data python data_convert_example.py --command binary_to_text --in_file data/binary_data --out_file data/text_data2 diff data/text_data2 data/text_data """ import struct import sys import tensorflow as tf from tensorflow.core.example import example_pb2 FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string('command', 'binary_to_text', 'Either binary_to_text or text_to_binary.' 'Specify FLAGS.in_file accordingly.') tf.app.flags.DEFINE_string('in_file', '', 'path to file') tf.app.flags.DEFINE_string('out_file', '', 'path to file') def _binary_to_text(): reader = open(FLAGS.in_file, 'rb') writer = open(FLAGS.out_file, 'w') while True: len_bytes = reader.read(8) if not len_bytes: sys.stderr.write('Done reading\n') return str_len = struct.unpack('q', len_bytes)[0] tf_example_str = struct.unpack('%ds' % str_len, reader.read(str_len))[0] tf_example = example_pb2.Example.FromString(tf_example_str) examples = [] for key in tf_example.features.feature: examples.append('%s=%s' % (key, tf_example.features.feature[key].bytes_list.value[0])) writer.write('%s\n' % '\t'.join(examples)) reader.close() writer.close() def _text_to_binary(): inputs = open(FLAGS.in_file, 'r').readlines() writer = open(FLAGS.out_file, 'wb') for inp in inputs: tf_example = example_pb2.Example() for feature in inp.strip().split('\t'): (k, v) = feature.split('=') tf_example.features.feature[k].bytes_list.value.extend([v]) tf_example_str = tf_example.SerializeToString() str_len = len(tf_example_str) writer.write(struct.pack('q', str_len)) writer.write(struct.pack('%ds' % str_len, tf_example_str)) writer.close() def main(unused_argv): assert FLAGS.command and FLAGS.in_file and FLAGS.out_file if FLAGS.command == 'binary_to_text': _binary_to_text() elif FLAGS.command == 'text_to_binary': _text_to_binary() if __name__ == '__main__': tf.app.run()
apache-2.0
narry/odenos
src/main/python/org/o3project/odenos/core/component/network/packet/ofp_in_packet.py
6
2181
# -*- coding:utf-8 -*- # Copyright 2015 NEC Corporation. # # # # 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 copy import deepcopy from org.o3project.odenos.core.component.network.packet.in_packet import InPacket from org.o3project.odenos.core.component.network.flow.ofpflow.ofp_flow_match\ import OFPFlowMatch class OFPInPacket(InPacket): def __init__(self, id_, type_, attributes, node, port, header, data): super(OFPInPacket, self).__init__(id_, type_, attributes, node, port, header, data) @classmethod def create_from_packed(cls, packed): return cls(packed[cls.PACKET_ID], packed[cls.TYPE], packed[cls.ATTRIBUTES], packed[cls.NODE], packed[cls.PORT], OFPFlowMatch.create_from_packed(packed[cls.HEADER]), packed[cls.DATA]) def packed_object(self): object_ = deepcopy(self._body) object_[self.HEADER] = self.header.packed_object() return object_
apache-2.0
miroi/xcint
doc/conf.py
4
7747
# -*- coding: utf-8 -*- # # XCint documentation build configuration file, created by # sphinx-quickstart on Thu Jun 12 14:59:50 2014. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.mathjax', 'sphinx.ext.ifconfig'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'XCint' copyright = u'2014, Radovan Bast' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.0' # The full version, including alpha/beta/rc tags. release = '0.0.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'XCintdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'XCint.tex', u'XCint Documentation', u'Radovan Bast', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'xcint', u'XCint Documentation', [u'Radovan Bast'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'XCint', u'XCint Documentation', u'Radovan Bast', 'XCint', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote'
bsd-3-clause
thjashin/tensorflow
tensorflow/contrib/learn/python/learn/utils/input_fn_utils.py
69
4846
# 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. # ============================================================================== """Utilities for creating input_fns. Contents of this file are moved to tensorflow/python/estimator/export.py. InputFnOps is renamed to ServingInputReceiver. build_parsing_serving_input_fn is renamed to build_parsing_serving_input_receiver_fn. build_default_serving_input_fn is renamed to build_raw_serving_input_receiver_fn. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import array_ops from tensorflow.python.ops import parsing_ops class InputFnOps(collections.namedtuple('InputFnOps', ['features', 'labels', 'default_inputs'])): """A return type for an input_fn. This return type is currently only supported for serving input_fn. Training and eval input_fn should return a `(features, labels)` tuple. The expected return values are: features: A dict of string to `Tensor` or `SparseTensor`, specifying the features to be passed to the model. labels: A `Tensor`, `SparseTensor`, or a dict of string to `Tensor` or `SparseTensor`, specifying labels for training or eval. For serving, set `labels` to `None`. default_inputs: a dict of string to `Tensor` or `SparseTensor`, specifying the input placeholders (if any) that this input_fn expects to be fed. Typically, this is used by a serving input_fn, which expects to be fed serialized `tf.Example` protos. """ def build_parsing_serving_input_fn(feature_spec, default_batch_size=None): """Build an input_fn appropriate for serving, expecting fed tf.Examples. Creates an input_fn that expects a serialized tf.Example fed into a string placeholder. The function parses the tf.Example according to the provided feature_spec, and returns all parsed Tensors as features. This input_fn is for use at serving time, so the labels return value is always None. Args: feature_spec: a dict of string to `VarLenFeature`/`FixedLenFeature`. default_batch_size: the number of query examples expected per batch. Leave unset for variable batch size (recommended). Returns: An input_fn suitable for use in serving. """ def input_fn(): """An input_fn that expects a serialized tf.Example.""" serialized_tf_example = array_ops.placeholder(dtype=dtypes.string, shape=[default_batch_size], name='input_example_tensor') inputs = {'examples': serialized_tf_example} features = parsing_ops.parse_example(serialized_tf_example, feature_spec) labels = None # these are not known in serving! return InputFnOps(features, labels, inputs) return input_fn def build_default_serving_input_fn(features, default_batch_size=None): """Build an input_fn appropriate for serving, expecting feature Tensors. Creates an input_fn that expects all features to be fed directly. This input_fn is for use at serving time, so the labels return value is always None. Args: features: a dict of string to `Tensor`. default_batch_size: the number of query examples expected per batch. Leave unset for variable batch size (recommended). Returns: An input_fn suitable for use in serving. """ def input_fn(): """an input_fn that expects all features to be fed directly.""" features_placeholders = {} for name, t in features.items(): shape_list = t.get_shape().as_list() shape_list[0] = default_batch_size shape = tensor_shape.TensorShape(shape_list) features_placeholders[name] = array_ops.placeholder(dtype=t.dtype, shape=shape, name=t.name) labels = None # these are not known in serving! return InputFnOps(features_placeholders, labels, features_placeholders) return input_fn
apache-2.0
canavandl/bokeh
examples/plotting/file/hover.py
43
1384
from __future__ import division import itertools import numpy as np from six.moves import zip from collections import OrderedDict from bokeh.plotting import ColumnDataSource, figure, show, output_file from bokeh.models import HoverTool output_file("hover.html") TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,hover,previewsave" xx, yy = np.meshgrid(range(0,101,4), range(0,101,4)) x = xx.flatten() y = yy.flatten() N = len(x) inds = [str(i) for i in np.arange(N)] radii = np.random.random(size=N)*0.4 + 1.7 colors = [ "#%02x%02x%02x" % (r, g, 150) for r, g in zip(np.floor(50+2*x), np.floor(30+2*y)) ] foo = list(itertools.permutations("abcdef"))[:N] bar = np.random.normal(size=N) source = ColumnDataSource( data=dict( x=x, y=y, radius=radii, colors=colors, foo=foo, bar=bar, ) ) p = figure(title="Hoverful Scatter", tools=TOOLS) p.circle(x, y, radius=radii, source=source, fill_color=colors, fill_alpha=0.6, line_color=None) p.text(x, y, text=inds, alpha=0.5, text_font_size="5pt", text_baseline="middle", text_align="center") hover =p.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([ ("index", "$index"), ("(x,y)", "($x, $y)"), ("radius", "@radius"), ("fill color", "$color[hex, swatch]:fill_color"), ("foo", "@foo"), ("bar", "@bar"), ]) show(p) # open a browser
bsd-3-clause
cholarajaa/cold-temperature
hotorcold/reactor/views.py
1
1489
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse from rest_framework import status from rest_framework.response import Response from rest_framework import viewsets from rest_framework.decorators import api_view from reactor.models import Event from reactor.serializers import EventSerializer, EventsDumpSerializer from reactor.tasks import create_or_update_event_data class EventViewSet(viewsets.ViewSet): """ A viewset for viewing and editing Event instances. """ serializer_class = EventSerializer queryset = Event.objects.all() def create(self, request): data = { 'events_json': request.data } serializer = EventsDumpSerializer(data=data) if serializer.is_valid(): serializer.save() create_or_update_event_data.apply_async((request.data,)) return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def list(self, request): serializer = self.serializer_class(self.queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def destroy(self, request, pk=None): if pk: Event.objects.get(pk=pk).delete() return Response({"message": "Success"}, status=status.HTTP_200_OK) def index(request): return HttpResponse('Hello reactor!!!')
gpl-3.0
pauljohnleonard/pod-world
CI_2015/demos/brains/feedforwardbrain.py
1
6562
# converted to java and then to python by p.j.leonard # based on C++ code found at # http://www.codeproject.com/KB/recipes/BP.aspx?msg=2809798#xx2809798xx import math import random import copy import pickle """ multilayer neural network """ def sigmoid(x): if x < -100.0: # avoid math.exp(x) blowing up return 0.0 return 1.0 / (1.0 + math.exp(-x)) def atan(x): if x < -100.: return -1.0 if x > 100.: return 1.0 ee=math.exp(-x) return (1.0 -ee) / (1.0 + ee) def randomSeed(): """ Random number between -0.5 and 0.5 """ return 0.5 - random.random() class FeedForwardBrain: """ Basic feedforward neural net """ def __init__(self,size,func=None,weight=None): """ Create a multi layer network Number of nodes in each layer is define by size size[0] is the number of inputs size[n] number of neurons in layer n func is an array of activation functions if this is None the activation defaults to sigmoid. weight can be used to initialize the weights of the NN if weight is None random values are assigned to the weights. """ sz=size #// set no of layers and their sizes self.num_layer = len(sz) if func == None: func=[] func.append(None) for _ in range(self.num_layer): func.append(sigmoid) self.layer_size = [] # new int[num_layer]; self.func=func for i in range(self.num_layer): self.layer_size.append(sz[i]) #// allocate memory for output of each neuron self.out = [] # new float[num_layer][]; for i in range(self.num_layer): self.out.append([]); a=self.out[i] for _ in range(self.layer_size[i]): a.append(0.0) if weight == None: self.weight=[] self.weight.append([]) for i in range(1,self.num_layer): self.weight.append([]) a=self.weight[i] for j in range(self.layer_size[i]): a.append([]) r=a[j] for _ in range(self.layer_size[i - 1]): r.append(randomSeed()) r.append(randomSeed()) else: self.weight=weight def ffwd(self,x): """ input: x list of input values returns: list of output values. """ # assign content to input layer for layer in range(self.layer_size[0]): self.out[0][layer] = x[layer] # output_from_neuron(layer,j) Jth neuron in Ith Layer # assign output(activation) value # to each neuron using sigmoid func for layer in range(1,self.num_layer): # For each layer for j in range(self.layer_size[layer]): # For each neuron in current layer sum = 0.0; for k in range(self.layer_size[layer - 1]): # For input from each neuron in preceeding layer sum += self.out[layer - 1][k] * self.weight[layer][j][k]; # Apply weight to inputs and add to sum sum += self.weight[layer][j][self.layer_size[layer - 1]]; # Apply bias self.out[layer][j] = self.func[layer](sum); # Apply sigmoid function return self.out[self.num_layer - 1]; #------------------ More advanced functionality (you can ignore this) --------------------------------------------------- def resize_inputs(self,nIn): for _ in range(nIn-self.layer_size[0]): self.out[0].append(0.0) for a in self.weight[1]: wLast=a.pop() a.append(0.0) for _ in range(nIn-self.layer_size[0]-1): a.append(0.0) a.append(wLast) if self.layer_size[0]<nIn: self.layer_size[0]=nIn def clone(self): clone=FeedForwardBrain(self.layer_size,self.func,self.weight) return clone def mutate(self,amount): """ mutate *all* the weights by a random amount. param: amount: range of mutation (in the range +-amount/2) """ # for all layers with inputs for i in range(1,self.num_layer): a=self.weight[i] # for all neurons in the layer for j in range(self.layer_size[i]): r=a[j] for k in range(self.layer_size[i-1]+1): r[k]=r[k]+randomSeed()*amount def dist(self,brain): """ sqrt(sum of diff weights squared) :param brain: compare with """ sum=0.0 # for all layers with inputs for i in range(1,self.num_layer): a=self.weight[i] b=brain.weight[i] # for all neurons in the layer for j in range(self.layer_size[i]): ra=a[j] rb=b[j] for k in range(self.layer_size[i-1]+1): sum += (ra[k]-rb[k])**2 return math.sqrt(sum) def output(self): return self.out[self.num_layer - 1]; def input(self): return self.out[0]; # mean square error def mse(self,tgt): mse = 0.0; for i in range(self.layer_size[self.num_layer - 1]): mse += (tgt[i] - self.out[self.num_layer - 1][i]) * (tgt[i] - self.out[self.num_layer - 1][i]); return mse / 2.0; def random_mutate(self,amount): for i in range(1,self.num_layer): a=self.weight[i] for j in range(self.layer_size[i]): r=a[j] k=random.randint(0, self.layer_size[i-1]+1) z=random.randint(0, (self.layer_size[i-1]+1)) while k < z: r[k]=r[k]+randomSeed()*amount k=k+1
gpl-2.0
palas/otp
lib/asn1/test/asn1_SUITE_data/BitStr.py
97
1813
BitStr DEFINITIONS ::= BEGIN -- F.2.5.1 -- Use a bit string type to model binary data whose format and -- length are unspecified, -- or specified elsewhere, and whose length in bits is not necessarily -- a multiple of eight. -- EXAMPLE G3FacsimilePage ::= BIT STRING -- a sequence of bits conforming to Recommendation T.4. image G3FacsimilePage ::= '100110100100001110110'B trailer BIT STRING ::= '0123456789ABCDEF'H body1 G3FacsimilePage ::= '1101'B body2 G3FacsimilePage ::= '1101000'B -- F.2.5.2 -- Use a bit string type with a size constraint to model the -- values of a fixed sized bit field. -- EXAMPLE BitField ::= BIT STRING (SIZE (12)) map1 BitField ::= '100110100100'B map2 BitField ::= '9A4'H map3 BitField ::= '1001101001'B -- Illegal - violates size constraint -- F.2.5.3 -- Use a bit string type to model the values of a bit map, an -- ordered collection of logical variables -- indicating whether a particular condition holds for each of a -- correspondingly ordered collection of objects. DaysOfTheWeek ::= BIT STRING { sunday(0), monday (1), tuesday(2), wednesday(3), thursday(4), friday(5), saturday(6) } (SIZE (0..7)) sunnyDaysLastWeek1 DaysOfTheWeek ::= {sunday, monday, wednesday} sunnyDaysLastWeek2 DaysOfTheWeek ::= '1101'B sunnyDaysLastWeek3 DaysOfTheWeek ::= '1101000'B sunnyDaysLastWeek4 DaysOfTheWeek ::= '11010000'B -- Illegal - violates size constraint -- F.2.5.5 -- Use a bit string type with named bits to model the values of a -- collection of related logical variables. -- EXAMPLE PersonalStatus ::= BIT STRING {married(0), employed(1), veteran(2), collegeGraduate(3)} billClinton PersonalStatus ::= {married, employed, collegeGraduate} hillaryClinton PersonalStatus ::= '110100'B END
apache-2.0
wilvk/ansible
lib/ansible/modules/monitoring/zabbix/zabbix_host.py
5
37010
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013-2014, Epic Games, Inc. # 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: zabbix_host short_description: Zabbix host creates/updates/deletes description: - This module allows you to create, modify and delete Zabbix host entries and associated group and template data. version_added: "2.0" author: - "(@cove)" - "Tony Minfei Ding" - "Harrison Gu (@harrisongu)" - "Werner Dijkerman" - "Eike Frost (@eikef)" requirements: - "python >= 2.6" - "zabbix-api >= 0.5.3" options: host_name: description: - Name of the host in Zabbix. - host_name is the unique identifier used and cannot be updated using this module. required: true visible_name: description: - Visible name of the host in Zabbix. version_added: '2.3' description: description: - Description of the host in Zabbix. version_added: '2.5' host_groups: description: - List of host groups the host is part of. required: false link_templates: description: - List of templates linked to the host. default: None inventory_mode: description: - Configure the inventory mode. choices: ['automatic', 'manual', 'disabled'] version_added: '2.1' inventory_zabbix: description: - Add Facts for a zabbix inventory (e.g. Tag) (see example below). - Please review the interface documentation for more information on the supported properties - 'https://www.zabbix.com/documentation/3.2/manual/api/reference/host/object#host_inventory' version_added: '2.5' status: description: - Monitoring status of the host. choices: ['enabled', 'disabled'] default: 'enabled' state: description: - State of the host. - On C(present), it will create if host does not exist or update the host if the associated data is different. - On C(absent) will remove a host if it exists. choices: ['present', 'absent'] default: 'present' proxy: description: - The name of the Zabbix Proxy to be used default: None interfaces: description: - List of interfaces to be created for the host (see example below). - 'Available keys are: I(dns), I(ip), I(main), I(port), I(type), I(useip), and I(bulk).' - Please review the interface documentation for more information on the supported properties - 'https://www.zabbix.com/documentation/2.0/manual/appendix/api/hostinterface/definitions#host_interface' - If an interface definition is incomplete, this module will attempt to fill in sensible values. - I(type) can also be C(agent), C(snmp), C(ipmi), or C(jmx) instead of its numerical value. default: [] tls_connect: description: - Specifies what encryption to use for outgoing connections. - The tls_connect parameter accepts values of 1 to 7 - Possible values, 1 (no encryption), 2 (PSK), 4 (certificate). - Values can be combined. - Works only with >= Zabbix 3.0 default: 1 version_added: '2.5' tls_accept: description: - Specifies what types of connections are allowed for incoming connections. - The tls_accept parameter accepts values of 1 to 7 - Possible values, 1 (no encryption), 2 (PSK), 4 (certificate). - Values can be combined. - Works only with >= Zabbix 3.0 default: 1 version_added: '2.5' tls_psk_identity: description: - PSK value is a hard to guess string of hexadecimal digits. - It is a unique name by which this specific PSK is referred to by Zabbix components - Do not put sensitive information in PSK identity string, it is transmitted over the network unencrypted. - Works only with >= Zabbix 3.0 version_added: '2.5' tls_psk: description: - The preshared key, at least 32 hex digits. Required if either tls_connect or tls_accept has PSK enabled. - Works only with >= Zabbix 3.0 version_added: '2.5' tls_issuer: description: - Required certificate issuer. - Works only with >= Zabbix 3.0 version_added: '2.5' tls_subject: description: - Required certificate subject. - Works only with >= Zabbix 3.0 version_added: '2.5' ipmi_authtype: description: - IPMI authentication algorithm. - Please review the Host object documentation for more information on the supported properties - 'https://www.zabbix.com/documentation/3.4/manual/api/reference/host/object' - Possible values are, C(0) (none), C(1) (MD2), C(2) (MD5), C(4) (straight), C(5) (OEM), C(6) (RMCP+), with -1 being the API default. - Please note that the Zabbix API will treat absent settings as default when updating any of the I(ipmi_)-options; this means that if you attempt to set any of the four options individually, the rest will be reset to default values. version_added: '2.5' ipmi_privilege: description: - IPMI privilege level. - Please review the Host object documentation for more information on the supported properties - 'https://www.zabbix.com/documentation/3.4/manual/api/reference/host/object' - Possible values are C(1) (callback), C(2) (user), C(3) (operator), C(4) (admin), C(5) (OEM), with C(2) being the API default. - also see the last note in the I(ipmi_authtype) documentation version_added: '2.5' ipmi_username: description: - IPMI username. - also see the last note in the I(ipmi_authtype) documentation version_added: '2.5' ipmi_password: description: - IPMI password. - also see the last note in the I(ipmi_authtype) documentation version_added: '2.5' force: description: - Overwrite the host configuration, even if already present default: 'yes' choices: [ 'yes', 'no' ] version_added: '2.0' extends_documentation_fragment: - zabbix ''' EXAMPLES = ''' - name: Create a new host or update an existing host's info local_action: module: zabbix_host server_url: http://monitor.example.com login_user: username login_password: password host_name: ExampleHost visible_name: ExampleName description: My ExampleHost Description host_groups: - Example group1 - Example group2 link_templates: - Example template1 - Example template2 status: enabled state: present inventory_mode: manual inventory_zabbix: tag: "{{ your_tag }}" alias: "{{ your_alias }}" notes: "Special Informations: {{ your_informations | default('None') }}" location: "{{ your_location }}" site_rack: "{{ your_site_rack }}" os: "{{ your_os }}" hardware: "{{ your_hardware }}" ipmi_authtype: 2 ipmi_privilege: 4 ipmi_username: username ipmi_password: password interfaces: - type: 1 main: 1 useip: 1 ip: 10.xx.xx.xx dns: "" port: 10050 - type: 4 main: 1 useip: 1 ip: 10.xx.xx.xx dns: "" port: 12345 proxy: a.zabbix.proxy - name: Update an existing host's TLS settings local_action: module: zabbix_host server_url: http://monitor.example.com login_user: username login_password: password host_name: ExampleHost visible_name: ExampleName host_groups: - Example group1 tls_psk_identity: test tls_connect: 2 tls_psk: 123456789abcdef123456789abcdef12 ''' import copy try: from zabbix_api import ZabbixAPI, ZabbixAPISubClass # Extend the ZabbixAPI # Since the zabbix-api python module too old (version 1.0, no higher version so far), # it does not support the 'hostinterface' api calls, # so we have to inherit the ZabbixAPI class to add 'hostinterface' support. class ZabbixAPIExtends(ZabbixAPI): hostinterface = None def __init__(self, server, timeout, user, passwd, validate_certs, **kwargs): ZabbixAPI.__init__(self, server, timeout=timeout, user=user, passwd=passwd, validate_certs=validate_certs) self.hostinterface = ZabbixAPISubClass(self, dict({"prefix": "hostinterface"}, **kwargs)) HAS_ZABBIX_API = True except ImportError: HAS_ZABBIX_API = False from ansible.module_utils.basic import AnsibleModule class Host(object): def __init__(self, module, zbx): self._module = module self._zapi = zbx # exist host def is_host_exist(self, host_name): result = self._zapi.host.get({'filter': {'host': host_name}}) return result # check if host group exists def check_host_group_exist(self, group_names): for group_name in group_names: result = self._zapi.hostgroup.get({'filter': {'name': group_name}}) if not result: self._module.fail_json(msg="Hostgroup not found: %s" % group_name) return True def get_template_ids(self, template_list): template_ids = [] if template_list is None or len(template_list) == 0: return template_ids for template in template_list: template_list = self._zapi.template.get({'output': 'extend', 'filter': {'host': template}}) if len(template_list) < 1: self._module.fail_json(msg="Template not found: %s" % template) else: template_id = template_list[0]['templateid'] template_ids.append(template_id) return template_ids def add_host(self, host_name, group_ids, status, interfaces, proxy_id, visible_name, description, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password): try: if self._module.check_mode: self._module.exit_json(changed=True) parameters = {'host': host_name, 'interfaces': interfaces, 'groups': group_ids, 'status': status, 'tls_connect': tls_connect, 'tls_accept': tls_accept} if proxy_id: parameters['proxy_hostid'] = proxy_id if visible_name: parameters['name'] = visible_name if tls_psk_identity is not None: parameters['tls_psk_identity'] = tls_psk_identity if tls_psk is not None: parameters['tls_psk'] = tls_psk if tls_issuer is not None: parameters['tls_issuer'] = tls_issuer if tls_subject is not None: parameters['tls_subject'] = tls_subject if description: parameters['description'] = description if ipmi_authtype is not None: parameters['ipmi_authtype'] = ipmi_authtype if ipmi_privilege is not None: parameters['ipmi_privilege'] = ipmi_privilege if ipmi_username is not None: parameters['ipmi_username'] = ipmi_username if ipmi_password is not None: parameters['ipmi_password'] = ipmi_password host_list = self._zapi.host.create(parameters) if len(host_list) >= 1: return host_list['hostids'][0] except Exception as e: self._module.fail_json(msg="Failed to create host %s: %s" % (host_name, e)) def update_host(self, host_name, group_ids, status, host_id, interfaces, exist_interface_list, proxy_id, visible_name, description, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password): try: if self._module.check_mode: self._module.exit_json(changed=True) parameters = {'hostid': host_id, 'groups': group_ids, 'status': status, 'tls_connect': tls_connect, 'tls_accept': tls_accept} if proxy_id >= 0: parameters['proxy_hostid'] = proxy_id if visible_name: parameters['name'] = visible_name if tls_psk_identity: parameters['tls_psk_identity'] = tls_psk_identity if tls_psk: parameters['tls_psk'] = tls_psk if tls_issuer: parameters['tls_issuer'] = tls_issuer if tls_subject: parameters['tls_subject'] = tls_subject if description: parameters['description'] = description if ipmi_authtype: parameters['ipmi_authtype'] = ipmi_authtype if ipmi_privilege: parameters['ipmi_privilege'] = ipmi_privilege if ipmi_username: parameters['ipmi_username'] = ipmi_username if ipmi_password: parameters['ipmi_password'] = ipmi_password self._zapi.host.update(parameters) interface_list_copy = exist_interface_list if interfaces: for interface in interfaces: flag = False interface_str = interface for exist_interface in exist_interface_list: interface_type = int(interface['type']) exist_interface_type = int(exist_interface['type']) if interface_type == exist_interface_type: # update interface_str['interfaceid'] = exist_interface['interfaceid'] self._zapi.hostinterface.update(interface_str) flag = True interface_list_copy.remove(exist_interface) break if not flag: # add interface_str['hostid'] = host_id self._zapi.hostinterface.create(interface_str) # remove remove_interface_ids = [] for remove_interface in interface_list_copy: interface_id = remove_interface['interfaceid'] remove_interface_ids.append(interface_id) if len(remove_interface_ids) > 0: self._zapi.hostinterface.delete(remove_interface_ids) except Exception as e: self._module.fail_json(msg="Failed to update host %s: %s" % (host_name, e)) def delete_host(self, host_id, host_name): try: if self._module.check_mode: self._module.exit_json(changed=True) self._zapi.host.delete([host_id]) except Exception as e: self._module.fail_json(msg="Failed to delete host %s: %s" % (host_name, e)) # get host by host name def get_host_by_host_name(self, host_name): host_list = self._zapi.host.get({'output': 'extend', 'selectInventory': 'extend', 'filter': {'host': [host_name]}}) if len(host_list) < 1: self._module.fail_json(msg="Host not found: %s" % host_name) else: return host_list[0] # get proxyid by proxy name def get_proxyid_by_proxy_name(self, proxy_name): proxy_list = self._zapi.proxy.get({'output': 'extend', 'filter': {'host': [proxy_name]}}) if len(proxy_list) < 1: self._module.fail_json(msg="Proxy not found: %s" % proxy_name) else: return proxy_list[0]['proxyid'] # get group ids by group names def get_group_ids_by_group_names(self, group_names): group_ids = [] if self.check_host_group_exist(group_names): group_list = self._zapi.hostgroup.get({'output': 'extend', 'filter': {'name': group_names}}) for group in group_list: group_id = group['groupid'] group_ids.append({'groupid': group_id}) return group_ids # get host templates by host id def get_host_templates_by_host_id(self, host_id): template_ids = [] template_list = self._zapi.template.get({'output': 'extend', 'hostids': host_id}) for template in template_list: template_ids.append(template['templateid']) return template_ids # get host groups by host id def get_host_groups_by_host_id(self, host_id): exist_host_groups = [] host_groups_list = self._zapi.hostgroup.get({'output': 'extend', 'hostids': host_id}) if len(host_groups_list) >= 1: for host_groups_name in host_groups_list: exist_host_groups.append(host_groups_name['name']) return exist_host_groups # check the exist_interfaces whether it equals the interfaces or not def check_interface_properties(self, exist_interface_list, interfaces): interfaces_port_list = [] if interfaces is not None: if len(interfaces) >= 1: for interface in interfaces: interfaces_port_list.append(int(interface['port'])) exist_interface_ports = [] if len(exist_interface_list) >= 1: for exist_interface in exist_interface_list: exist_interface_ports.append(int(exist_interface['port'])) if set(interfaces_port_list) != set(exist_interface_ports): return True for exist_interface in exist_interface_list: exit_interface_port = int(exist_interface['port']) for interface in interfaces: interface_port = int(interface['port']) if interface_port == exit_interface_port: for key in interface.keys(): if str(exist_interface[key]) != str(interface[key]): return True return False # get the status of host by host def get_host_status_by_host(self, host): return host['status'] # check all the properties before link or clear template def check_all_properties(self, host_id, host_groups, status, interfaces, template_ids, exist_interfaces, host, proxy_id, visible_name, description, host_name, inventory_mode, inventory_zabbix, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, tls_connect, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password): # get the existing host's groups exist_host_groups = self.get_host_groups_by_host_id(host_id) if set(host_groups) != set(exist_host_groups): return True # get the existing status exist_status = self.get_host_status_by_host(host) if int(status) != int(exist_status): return True # check the exist_interfaces whether it equals the interfaces or not if self.check_interface_properties(exist_interfaces, interfaces): return True # get the existing templates exist_template_ids = self.get_host_templates_by_host_id(host_id) if set(list(template_ids)) != set(exist_template_ids): return True if int(host['proxy_hostid']) != int(proxy_id): return True # Check whether the visible_name has changed; Zabbix defaults to the technical hostname if not set. if visible_name: if host['name'] != visible_name and host['name'] != host_name: return True # Only compare description if it is given as a module parameter if description: if host['description'] != description: return True if inventory_mode: if host['inventory']: if int(host['inventory']['inventory_mode']) != self.inventory_mode_numeric(inventory_mode): return True elif inventory_mode != 'disabled': return True if inventory_zabbix: proposed_inventory = copy.deepcopy(host['inventory']) proposed_inventory.update(inventory_zabbix) if proposed_inventory != host['inventory']: return True if tls_accept is not None: if int(host['tls_accept']) != tls_accept: return True if tls_psk_identity is not None: if host['tls_psk_identity'] != tls_psk_identity: return True if tls_psk is not None: if host['tls_psk'] != tls_psk: return True if tls_issuer is not None: if host['tls_issuer'] != tls_issuer: return True if tls_subject is not None: if host['tls_subject'] != tls_subject: return True if tls_connect is not None: if int(host['tls_connect']) != tls_connect: return True if ipmi_authtype is not None: if int(host['ipmi_authtype']) != ipmi_authtype: return True if ipmi_privilege is not None: if int(host['ipmi_privilege']) != ipmi_privilege: return True if ipmi_username is not None: if host['ipmi_username'] != ipmi_username: return True if ipmi_password is not None: if host['ipmi_password'] != ipmi_password: return True return False # link or clear template of the host def link_or_clear_template(self, host_id, template_id_list, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password): # get host's exist template ids exist_template_id_list = self.get_host_templates_by_host_id(host_id) exist_template_ids = set(exist_template_id_list) template_ids = set(template_id_list) template_id_list = list(template_ids) # get unlink and clear templates templates_clear = exist_template_ids.difference(template_ids) templates_clear_list = list(templates_clear) request_str = {'hostid': host_id, 'templates': template_id_list, 'templates_clear': templates_clear_list, 'tls_connect': tls_connect, 'tls_accept': tls_accept, 'ipmi_authtype': ipmi_authtype, 'ipmi_privilege': ipmi_privilege, 'ipmi_username': ipmi_username, 'ipmi_password': ipmi_password} if tls_psk_identity is not None: request_str['tls_psk_identity'] = tls_psk_identity if tls_psk is not None: request_str['tls_psk'] = tls_psk if tls_issuer is not None: request_str['tls_issuer'] = tls_issuer if tls_subject is not None: request_str['tls_subject'] = tls_subject try: if self._module.check_mode: self._module.exit_json(changed=True) self._zapi.host.update(request_str) except Exception as e: self._module.fail_json(msg="Failed to link template to host: %s" % e) def inventory_mode_numeric(self, inventory_mode): if inventory_mode == "automatic": return int(1) elif inventory_mode == "manual": return int(0) elif inventory_mode == "disabled": return int(-1) return inventory_mode # Update the host inventory_mode def update_inventory_mode(self, host_id, inventory_mode): # nothing was set, do nothing if not inventory_mode: return inventory_mode = self.inventory_mode_numeric(inventory_mode) # watch for - https://support.zabbix.com/browse/ZBX-6033 request_str = {'hostid': host_id, 'inventory_mode': inventory_mode} try: if self._module.check_mode: self._module.exit_json(changed=True) self._zapi.host.update(request_str) except Exception as e: self._module.fail_json(msg="Failed to set inventory_mode to host: %s" % e) def update_inventory_zabbix(self, host_id, inventory): if not inventory: return request_str = {'hostid': host_id, 'inventory': inventory} try: if self._module.check_mode: self._module.exit_json(changed=True) self._zapi.host.update(request_str) except Exception as e: self._module.fail_json(msg="Failed to set inventory to host: %s" % e) def main(): module = AnsibleModule( argument_spec=dict( server_url=dict(type='str', required=True, aliases=['url']), login_user=dict(type='str', required=True), login_password=dict(type='str', required=True, no_log=True), host_name=dict(type='str', required=True), http_login_user=dict(type='str', required=False, default=None), http_login_password=dict(type='str', required=False, default=None, no_log=True), validate_certs=dict(type='bool', required=False, default=True), host_groups=dict(type='list', required=False), link_templates=dict(type='list', required=False), status=dict(default="enabled", choices=['enabled', 'disabled']), state=dict(default="present", choices=['present', 'absent']), inventory_mode=dict(required=False, choices=['automatic', 'manual', 'disabled']), ipmi_authtype=dict(type='int', default=None), ipmi_privilege=dict(type='int', default=None), ipmi_username=dict(type='str', required=False, default=None), ipmi_password=dict(type='str', required=False, default=None, no_log=True), tls_connect=dict(type='int', default=1), tls_accept=dict(type='int', default=1), tls_psk_identity=dict(type='str', required=False), tls_psk=dict(type='str', required=False), tls_issuer=dict(type='str', required=False), tls_subject=dict(type='str', required=False), inventory_zabbix=dict(required=False, type='dict'), timeout=dict(type='int', default=10), interfaces=dict(type='list', required=False), force=dict(type='bool', default=True), proxy=dict(type='str', required=False), visible_name=dict(type='str', required=False), description=dict(type='str', required=False) ), supports_check_mode=True ) if not HAS_ZABBIX_API: module.fail_json(msg="Missing required zabbix-api module (check docs or install with: pip install zabbix-api)") server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] http_login_user = module.params['http_login_user'] http_login_password = module.params['http_login_password'] validate_certs = module.params['validate_certs'] host_name = module.params['host_name'] visible_name = module.params['visible_name'] description = module.params['description'] host_groups = module.params['host_groups'] link_templates = module.params['link_templates'] inventory_mode = module.params['inventory_mode'] ipmi_authtype = module.params['ipmi_authtype'] ipmi_privilege = module.params['ipmi_privilege'] ipmi_username = module.params['ipmi_username'] ipmi_password = module.params['ipmi_password'] tls_connect = module.params['tls_connect'] tls_accept = module.params['tls_accept'] tls_psk_identity = module.params['tls_psk_identity'] tls_psk = module.params['tls_psk'] tls_issuer = module.params['tls_issuer'] tls_subject = module.params['tls_subject'] inventory_zabbix = module.params['inventory_zabbix'] status = module.params['status'] state = module.params['state'] timeout = module.params['timeout'] interfaces = module.params['interfaces'] force = module.params['force'] proxy = module.params['proxy'] # convert enabled to 0; disabled to 1 status = 1 if status == "disabled" else 0 zbx = None # login to zabbix try: zbx = ZabbixAPIExtends(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password, validate_certs=validate_certs) zbx.login(login_user, login_password) except Exception as e: module.fail_json(msg="Failed to connect to Zabbix server: %s" % e) host = Host(module, zbx) template_ids = [] if link_templates: template_ids = host.get_template_ids(link_templates) group_ids = [] if host_groups: group_ids = host.get_group_ids_by_group_names(host_groups) ip = "" if interfaces: # ensure interfaces are well-formed for interface in interfaces: if 'type' not in interface: module.fail_json(msg="(interface) type needs to be specified for interface '%s'." % interface) interfacetypes = {'agent': 1, 'snmp': 2, 'ipmi': 3, 'jmx': 4} if interface['type'] in interfacetypes.keys(): interface['type'] = interfacetypes[interface['type']] if interface['type'] < 1 or interface['type'] > 4: module.fail_json(msg="Interface type can only be 1-4 for interface '%s'." % interface) if 'useip' not in interface: interface['useip'] = 0 if 'dns' not in interface: if interface['useip'] == 0: module.fail_json(msg="dns needs to be set if useip is 0 on interface '%s'." % interface) interface['dns'] = '' if 'ip' not in interface: if interface['useip'] == 1: module.fail_json(msg="ip needs to be set if useip is 1 on interface '%s'." % interface) interface['ip'] = '' if 'main' not in interface: interface['main'] = 0 if 'port' not in interface: if interface['type'] == 1: interface['port'] = "10050" elif interface['type'] == 2: interface['port'] = "161" elif interface['type'] == 3: interface['port'] = "623" elif interface['type'] == 4: interface['port'] = "12345" if interface['type'] == 1: ip = interface['ip'] # Use proxy specified, or set to 0 if proxy: proxy_id = host.get_proxyid_by_proxy_name(proxy) else: proxy_id = 0 # check if host exist is_host_exist = host.is_host_exist(host_name) if is_host_exist: # get host id by host name zabbix_host_obj = host.get_host_by_host_name(host_name) host_id = zabbix_host_obj['hostid'] # If proxy is not specified as a module parameter, use the existing setting if proxy is None: proxy_id = zabbix_host_obj['proxy_hostid'] if state == "absent": # remove host host.delete_host(host_id, host_name) module.exit_json(changed=True, result="Successfully delete host %s" % host_name) else: if not host_groups: # if host_groups have not been specified when updating an existing host, just # get the group_ids from the existing host without updating them. host_groups = host.get_host_groups_by_host_id(host_id) group_ids = host.get_group_ids_by_group_names(host_groups) # get existing host's interfaces exist_interfaces = host._zapi.hostinterface.get({'output': 'extend', 'hostids': host_id}) # if no interfaces were specified with the module, start with an empty list if not interfaces: interfaces = [] # When force=no is specified, append existing interfaces to interfaces to update. When # no interfaces have been specified, copy existing interfaces as specified from the API. # Do the same with templates and host groups. if not force or not interfaces: for interface in copy.deepcopy(exist_interfaces): # remove values not used during hostinterface.add/update calls for key in interface.keys(): if key in ['interfaceid', 'hostid', 'bulk']: interface.pop(key, None) for index in interface.keys(): if index in ['useip', 'main', 'type', 'port']: interface[index] = int(interface[index]) if interface not in interfaces: interfaces.append(interface) if not force or link_templates is None: template_ids = list(set(template_ids + host.get_host_templates_by_host_id(host_id))) if not force: for group_id in host.get_group_ids_by_group_names(host.get_host_groups_by_host_id(host_id)): if group_id not in group_ids: group_ids.append(group_id) # update host if host.check_all_properties(host_id, host_groups, status, interfaces, template_ids, exist_interfaces, zabbix_host_obj, proxy_id, visible_name, description, host_name, inventory_mode, inventory_zabbix, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, tls_connect, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password): host.link_or_clear_template(host_id, template_ids, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password) host.update_host(host_name, group_ids, status, host_id, interfaces, exist_interfaces, proxy_id, visible_name, description, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password) host.update_inventory_mode(host_id, inventory_mode) host.update_inventory_zabbix(host_id, inventory_zabbix) module.exit_json(changed=True, result="Successfully update host %s (%s) and linked with template '%s'" % (host_name, ip, link_templates)) else: module.exit_json(changed=False) else: if state == "absent": # the host is already deleted. module.exit_json(changed=False) if not group_ids: module.fail_json(msg="Specify at least one group for creating host '%s'." % host_name) if not interfaces or (interfaces and len(interfaces) == 0): module.fail_json(msg="Specify at least one interface for creating host '%s'." % host_name) # create host host_id = host.add_host(host_name, group_ids, status, interfaces, proxy_id, visible_name, description, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password) host.link_or_clear_template(host_id, template_ids, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password) host.update_inventory_mode(host_id, inventory_mode) host.update_inventory_zabbix(host_id, inventory_zabbix) module.exit_json(changed=True, result="Successfully added host %s (%s) and linked with template '%s'" % ( host_name, ip, link_templates)) if __name__ == '__main__': main()
gpl-3.0
nestukh/trash-cli
unit_tests/test_trashdir.py
2
2738
# Copyright (C) 2011 Andrea Francia Trivolzio(PV) Italy from nose.tools import assert_equals from trashcli.trash import TrashDir from trashcli.trash import TrashDirectory class TestTrashDir: def test_path(self): trash_dir = TrashDirectory('/Trash-501', '/') assert_equals('/Trash-501', trash_dir.path) class TestTrashDir_finding_orphans: def test(self): self.fs.create_fake_file('/info/foo.trashinfo') self.find_orphan() assert_equals([], self.orphan_found) def test2(self): self.fs.create_fake_file('/files/foo') self.find_orphan() assert_equals(['/files/foo'], self.orphan_found) def setUp(self): self.orphan_found=[] self.fs = FakeFileSystem() self.trashdir=TrashDir(self.fs) self.trashdir.open('/', None) def find_orphan(self): self.trashdir.each_orphan(self.orphan_found.append) class FakeFileSystem: def __init__(self): self.files={} self.dirs={} def contents_of(self, path): return self.files[path] def exists(self, path): return path in self.files def entries_if_dir_exists(self, path): return self.dirs.get(path, []) def create_fake_file(self, path, contents=''): import os self.files[path] = contents self.create_fake_dir(os.path.dirname(path), os.path.basename(path)) def create_fake_dir(self, dir_path, *dir_entries): self.dirs[dir_path] = dir_entries class TestFakeFileSystem: def setUp(self): self.fs = FakeFileSystem() def test_you_can_read_from_files(self): self.fs.create_fake_file('/path/to/file', "file contents") assert_equals('file contents', self.fs.contents_of('/path/to/file')) def test_when_creating_a_fake_file_it_creates_also_the_dir(self): self.fs.create_fake_file('/dir/file') assert_equals(set(('file',)), set(self.fs.entries_if_dir_exists('/dir'))) def test_you_can_create_multiple_fake_file(self): self.fs.create_fake_file('/path/to/file1', "one") self.fs.create_fake_file('/path/to/file2', "two") assert_equals('one', self.fs.contents_of('/path/to/file1')) assert_equals('two', self.fs.contents_of('/path/to/file2')) def test_no_file_exists_at_beginning(self): assert not self.fs.exists('/filename') def test_after_a_creation_the_file_exists(self): self.fs.create_fake_file('/filename') assert self.fs.exists('/filename') def test_create_fake_dir(self): self.fs.create_fake_dir('/etc', 'passwd', 'shadow', 'hosts') assert_equals(set(['passwd', 'shadow', 'hosts']), set(self.fs.entries_if_dir_exists('/etc')))
gpl-2.0
yuanming-hu/taichi
tests/python/test_ndrange.py
1
4333
import numpy as np import taichi as ti @ti.all_archs def test_1d(): x = ti.field(ti.f32, shape=(16)) @ti.kernel def func(): for i in ti.ndrange((4, 10)): x[i] = i func() for i in range(16): if 4 <= i < 10: assert x[i] == i else: assert x[i] == 0 @ti.all_archs def test_2d(): x = ti.field(ti.f32, shape=(16, 32)) t = 8 @ti.kernel def func(): for i, j in ti.ndrange((4, 10), (3, t)): val = i + j * 10 x[i, j] = val func() for i in range(16): for j in range(32): if 4 <= i < 10 and 3 <= j < 8: assert x[i, j] == i + j * 10 else: assert x[i, j] == 0 @ti.all_archs def test_3d(): x = ti.field(ti.f32, shape=(16, 32, 64)) @ti.kernel def func(): for i, j, k in ti.ndrange((4, 10), (3, 8), 17): x[i, j, k] = i + j * 10 + k * 100 func() for i in range(16): for j in range(32): for k in range(64): if 4 <= i < 10 and 3 <= j < 8 and k < 17: assert x[i, j, k] == i + j * 10 + k * 100 else: assert x[i, j, k] == 0 @ti.all_archs def test_static_grouped(): x = ti.field(ti.f32, shape=(16, 32, 64)) @ti.kernel def func(): for I in ti.static(ti.grouped(ti.ndrange((4, 5), (3, 5), 5))): x[I] = I[0] + I[1] * 10 + I[2] * 100 func() for i in range(16): for j in range(32): for k in range(64): if 4 <= i < 5 and 3 <= j < 5 and k < 5: assert x[i, j, k] == i + j * 10 + k * 100 else: assert x[i, j, k] == 0 @ti.all_archs def test_static_grouped_static(): x = ti.Matrix.field(2, 3, dtype=ti.f32, shape=(16, 4)) @ti.kernel def func(): for i, j in ti.ndrange(16, 4): for I in ti.static(ti.grouped(ti.ndrange(2, 3))): x[i, j][I] = I[0] + I[1] * 10 + i + j * 4 func() for i in range(16): for j in range(4): for k in range(2): for l in range(3): assert x[i, j][k, l] == k + l * 10 + i + j * 4 @ti.all_archs def test_field_init_eye(): # https://github.com/taichi-dev/taichi/issues/1824 n = 32 A = ti.field(ti.f32, (n, n)) @ti.kernel def init(): for i, j in ti.ndrange(n, n): if i == j: A[i, j] = 1 init() assert np.allclose(A.to_numpy(), np.eye(n, dtype=np.float32)) @ti.all_archs def test_ndrange_index_floordiv(): # https://github.com/taichi-dev/taichi/issues/1829 n = 10 A = ti.field(ti.f32, (n, n)) @ti.kernel def init(): for i, j in ti.ndrange(n, n): if i // 2 == 0: A[i, j] = i init() for i in range(n): for j in range(n): if i // 2 == 0: assert A[i, j] == i else: assert A[i, j] == 0 @ti.test() def test_nested_ndrange(): # https://github.com/taichi-dev/taichi/issues/1829 n = 2 A = ti.field(ti.i32, (n, n, n, n)) @ti.kernel def init(): for i, j in ti.ndrange(n, n): for k, l in ti.ndrange(n, n): r = i * n**3 + j * n**2 + k * n + l A[i, j, k, l] = r init() for i in range(n): for j in range(n): for k in range(n): for l in range(n): r = i * n**3 + j * n**2 + k * n + l assert A[i, j, k, l] == r @ti.test(ti.cpu) def test_ndrange_ast_transform(): n, u, v = 4, 3, 2 a = ti.field(ti.i32, ()) b = ti.field(ti.i32, ()) A = ti.field(ti.i32, (n, n)) @ti.kernel def func(): # `__getitem__ cannot be called from Python-scope` will be raised if # `a[None]` is not transformed to `ti.subscript(a, None)` in ti.ndrange: for i, j in ti.ndrange(a[None], b[None]): r = i * n + j + 1 A[i, j] = r a[None] = u b[None] = v func() for i in range(n): for j in range(n): if i < u and j < v: r = i * n + j + 1 else: r = 0 assert A[i, j] == r
mit
jkyeung/XlsxWriter
xlsxwriter/test/comparison/test_chart_display_units06.py
1
1414
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org # from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None filename = 'chart_display_units06.xlsx' test_dir = 'xlsxwriter/test/comparison/' self.got_filename = test_dir + '_test_' + filename self.exp_filename = test_dir + 'xlsx_files/' + filename self.ignore_files = [] self.ignore_elements = {} def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({'type': 'column'}) chart.axis_ids = [93548544, 93550464] data = [ [10000000, 20000000, 30000000, 20000000, 10000000], ] worksheet.write_column(0, 0, data[0]) chart.add_series({'values': '=Sheet1!$A$1:$A$5'}) chart.set_y_axis({'display_units': 'millions', 'display_units_visible': 0}) worksheet.insert_chart('E9', chart) workbook.close() self.assertExcelEqual()
bsd-2-clause
KDE/kcm-userconfig
models.py
1
10076
#!/usr/bin/python # -*- coding: utf-8 -*- ############################################################################# ## ## Copyright 2009 Yuriy Kozlov <yuriy-kozlov@kubuntu.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 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, see <http://www.gnu.org/licenses/>. ## ############################################################################# # Qt imports from PyQt4.QtGui import * from PyQt4.QtCore import * # KDE imports from PyKDE4.kdecore import * from PyKDE4.kdeui import KIconLoader import locale class UCAbstractItemModel(QAbstractItemModel): """ Item model for tree views in userconfig. Common elements for users and groups. """ column_data = [] def __init__(self, parent, items): QAbstractItemModel.__init__(self, parent) self.items = items def columnCount(self, parent=None): return len(self.column_data) def rowCount(self, parent = QModelIndex()): return len(self.items) def index(self, row, column, parent=QModelIndex()): return self.createIndex(row, column) def parent(self, index): return QModelIndex() def hasChildren(self, parent): if parent.row() > 0: return False else: return True def data(self, idx, role): obj = self.objData(idx) if obj is None: return QVariant() if role == Qt.DisplayRole: col = idx.column() return self._data(obj, col) elif role == Qt.EditRole: return QVariant(obj.getID()) elif role == Qt.DecorationRole: col = idx.column() return self._icon_data(obj, col) else: return QVariant() def _data(self, obj, col): if self.column_data[col]["data_method_name"]: data_func = getattr(obj, self.column_data[col]["data_method_name"]) return QVariant(data_func()) else: return QVariant() def _icon_data(self, obj, col): return QVariant() def objData(self, idx): if not idx.isValid(): return None row = idx.row() if row >= self.rowCount(): return None obj = self.items[row] return obj def headerData(self, section, orientation, role): col = section if orientation == Qt.Horizontal and role == Qt.DisplayRole: return QVariant(self.column_data[col]["header"]) return QVariant() def setItems(self, items): self.items = items self.emit(SIGNAL("modelReset()")) def indexFromID(self, ID): for i, obj in enumerate(self.items): if obj.getID() == ID: return self.index(i, 0) return QModelIndex() def indexFromSystemName(self, name): for i, obj in enumerate(self.items): if obj.getSystemName() == name: return self.index(i, 0) return QModelIndex() def selectionFromID(self, ID): for i, obj in enumerate(self.items): if obj.getID() == ID: return QItemSelection(self.index(i, 0), self.index(i, self.columnCount() - 1)) return QItemSelection() class UserModel(UCAbstractItemModel): """ Item model for tree views in userconfig. Elements specific to users. """ column_data = [ {"data_method_name" : "getRealName", "header" : i18n("Real Name") }, {"data_method_name" : "getSystemName", "header" : i18n("Username") }, {"data_method_name" : "", "header" : "" }, ] def _icon_data(self, obj, col): if col == 2 and obj.isLocked(): #print "object locked" #return QVariant("blah") return QVariant(KIconLoader.global_() .loadIcon('object-locked', KIconLoader.Small)) else: return QVariant() class GroupModel(UCAbstractItemModel): """ Item model for tree views in userconfig. Elements specific to groups. """ column_data = [ {"data_method_name" : "getSystemName", "header" : i18n("Group Name") }, {"data_method_name" : "getID", "header" : i18n("GID") }, ] class FilterSystemAcctsProxyModel(QSortFilterProxyModel): """ Proxy model to filter out system accounts from a group or user model """ def filterAcceptsRow(self, source_row, source_parent=QModelIndex()): sourceIndex = self.sourceModel().index(source_row, 0, source_parent) obj = self.sourceModel().objData(sourceIndex) return not obj.isSystemAccount() class GroupListModel(UCAbstractItemModel): """ Item model for list views in userconfig. Allows groups to be checked. """ def __init__(self, parent, items, userobj): UCAbstractItemModel.__init__(self, parent, items) self.userobj = userobj def setUser(self, userobj): self.userobj = userobj self.emit(SIGNAL("modelReset()")) def _primaryGroupRow(self): if self.userobj is not None: for i, group in enumerate(self.items): if group is self.userobj.getPrimaryGroup(): return i return None def flags(self, idx): if idx.isValid() and idx.row() == self._primaryGroupRow(): return Qt.ItemFlag(Qt.ItemIsEnabled) else: return Qt.ItemFlag(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) def columnCount(self, parent=None): return 1 def index(self, row, column, parent=QModelIndex()): return self.createIndex(row, 0) def data(self, idx, role): obj = self.objData(idx) if obj is None: return QVariant() if role == Qt.DisplayRole: return QVariant(obj.getGroupname()) elif role == Qt.EditRole: return QVariant(obj.getID()) elif role == Qt.CheckStateRole: # No checkbox for the primary group (nevermind, looks ugly) #if idx.row() == self._primaryGroupRow(): #return QVariant() check = Qt.Unchecked if obj in self.userobj.getGroups(): check = Qt.Checked return QVariant(check) else: return QVariant() def setData(self, idx, val, role): obj = self.objData(idx) if obj is None: return False if role == Qt.CheckStateRole: if obj is self.userobj.getPrimaryGroup(): return False if val.toInt()[0] == Qt.Checked: self.userobj.addToGroup(obj) else: self.userobj.removeFromGroup(obj) # dataChanged doesn't seem to get the other view to repaint right # away, so modelReset will have to do. Should be fine for # this size data set. #self.emit(SIGNAL("dataChanged(QModelIndex&,QModelIndex&)"), idx, idx) self.emit(SIGNAL("modelReset()")) return True else: return False def headerData(self, section, orientation, role): return QVariant() class SimpleGroupListProxyModel(QSortFilterProxyModel): """ Group list model without checkboxes """ def flags(self, idx=None): return Qt.ItemFlag(Qt.ItemIsEnabled | Qt.ItemIsSelectable) def data(self, idx, role): if role == Qt.CheckStateRole: return QVariant() elif role == Qt.EditRole: # Needed for combo box return QSortFilterProxyModel.data(self, idx, Qt.DisplayRole) else: return QSortFilterProxyModel.data(self, idx, role) class PrivilegeListProxyModel(QSortFilterProxyModel): """ Proxy model to show just groups with known privilege descriptions and show those descriptions instead of the group names. """ privilege_names = { "plugdev" : i18n("Access external storage devices automatically"), "admin" : i18n("Administer the system"), "adm" : i18n("Access system logs"), "ltsp" : i18n("Allow use of FUSE filesystems like LTSP thin " + "client block devices"), "dialout" : i18n("Connect to the Internet using a modem"), "syslog" : i18n("Monitor system logs"), "fax" : i18n("Send and receive faxes"), "cdrom" : i18n("Use CD-ROM and DVD drives"), "floppy" : i18n("Use floppy drives"), "modem" : i18n("Use modems"), "scanner" : i18n("Use scanners"), } def filterAcceptsRow(self, source_row, source_parent=QModelIndex()): sourceIndex = self.sourceModel().index(source_row, 0, source_parent) group_name = self.sourceModel().data(sourceIndex, Qt.DisplayRole)\ .toString() return str(group_name) in self.privilege_names def data(self, idx, role): data = QSortFilterProxyModel.data(self, idx, role) if data.isValid() and role == Qt.DisplayRole: data = self.privilege_names[str(data.toString())] return QVariant(data) else: return data
gpl-2.0
decode-dev/shodan-python
shodan/client.py
3
15861
# -*- coding: utf-8 -*- """ shodan.client ~~~~~~~~~~~~~ This module implements the Shodan API. :copyright: (c) 2014-2015 by John Matherly """ import requests import simplejson import time import shodan.exception as exception import shodan.helpers as helpers import shodan.stream as stream # Try to disable the SSL warnings in urllib3 since not everybody can install # C extensions. If you're able to install C extensions you can try to run: # # pip install requests[security] # # Which will download libraries that offer more full-featured SSL classes try: requests.packages.urllib3.disable_warnings() except: pass class Shodan: """Wrapper around the Shodan REST and Streaming APIs :param key: The Shodan API key that can be obtained from your account page (https://account.shodan.io) :type key: str :ivar exploits: An instance of `shodan.Shodan.Exploits` that provides access to the Exploits REST API. :ivar stream: An instance of `shodan.Shodan.Stream` that provides access to the Streaming API. """ class Tools: def __init__(self, parent): self.parent = parent def myip(self): """Get your current IP address as seen from the Internet. :returns: str -- your IP address """ return self.parent._request('/tools/myip', {}) class Exploits: def __init__(self, parent): self.parent = parent def search(self, query, page=1, facets=None): """Search the entire Shodan Exploits archive using the same query syntax as the website. :param query: The exploit search query; same syntax as website. :type query: str :param facets: A list of strings or tuples to get summary information on. :type facets: str :param page: The page number to access. :type page: int :returns: dict -- a dictionary containing the results of the search. """ query_args = { 'query': query, 'page': page, } if facets: facet_str = helpers.create_facet_string(facets) query_args['facets'] = facet_str return self.parent._request('/api/search', query_args, service='exploits') def count(self, query, facets=None): """Search the entire Shodan Exploits archive but only return the total # of results, not the actual exploits. :param query: The exploit search query; same syntax as website. :type query: str :param facets: A list of strings or tuples to get summary information on. :type facets: str :returns: dict -- a dictionary containing the results of the search. """ query_args = { 'query': query, } if facets: facet_str = helpers.create_facet_string(facets) query_args['facets'] = facet_str return self.parent._request('/api/count', query_args, service='exploits') def __init__(self, key): """Initializes the API object. :param key: The Shodan API key. :type key: str """ self.api_key = key self.base_url = 'https://api.shodan.io' self.base_exploits_url = 'https://exploits.shodan.io' self.exploits = self.Exploits(self) self.tools = self.Tools(self) self.stream = stream.Stream(key) def _request(self, function, params, service='shodan', method='get'): """General-purpose function to create web requests to SHODAN. Arguments: function -- name of the function you want to execute params -- dictionary of parameters for the function Returns A dictionary containing the function's results. """ # Add the API key parameter automatically params['key'] = self.api_key # Determine the base_url based on which service we're interacting with base_url = { 'shodan': self.base_url, 'exploits': self.base_exploits_url, }.get(service, 'shodan') # Send the request try: if method.lower() == 'post': data = requests.post(base_url + function, params) else: data = requests.get(base_url + function, params=params) except: raise exception.APIError('Unable to connect to Shodan') # Check that the API key wasn't rejected if data.status_code == 401: try: raise exception.APIError(data.json()['error']) except: pass raise exception.APIError('Invalid API key') # Parse the text into JSON try: data = data.json() except: raise exception.APIError('Unable to parse JSON response') # Raise an exception if an error occurred if type(data) == dict and data.get('error', None): raise exception.APIError(data['error']) # Return the data return data def count(self, query, facets=None): """Returns the total number of search results for the query. :param query: Search query; identical syntax to the website :type query: str :param facets: (optional) A list of properties to get summary information on :type facets: str :returns: A dictionary with 1 main property: total. If facets have been provided then another property called "facets" will be available at the top-level of the dictionary. Visit the website for more detailed information. """ query_args = { 'query': query, } if facets: facet_str = helpers.create_facet_string(facets) query_args['facets'] = facet_str return self._request('/shodan/host/count', query_args) def host(self, ip, history=False): """Get all available information on an IP. :param ip: IP of the computer :type ip: str :param history: (optional) True if you want to grab the historical (non-current) banners for the host, False otherwise. :type history: bool """ params = {} if history: params['history'] = history return self._request('/shodan/host/%s' % ip, params) def info(self): """Returns information about the current API key, such as a list of add-ons and other features that are enabled for the current user's API plan. """ return self._request('/api-info', {}) def ports(self): """Get a list of ports that Shodan crawls :returns: An array containing the ports that Shodan crawls for. """ return self._request('/shodan/ports', {}) def protocols(self): """Get a list of protocols that the Shodan on-demand scanning API supports. :returns: A dictionary containing the protocol name and description. """ return self._request('/shodan/protocols', {}) def scan(self, ips): """Scan a network using Shodan :param ips: A list of IPs or netblocks in CIDR notation :type ips: str :returns: A dictionary with a unique ID to check on the scan progress, the number of IPs that will be crawled and how many scan credits are left. """ if isinstance(ips, basestring): ips = [ips] params = { 'ips': ','.join(ips), } return self._request('/shodan/scan', params, method='post') def scan_internet(self, port, protocol): """Scan a network using Shodan :param port: The port that should get scanned. :type port: int :param port: The name of the protocol as returned by the protocols() method. :type port: str :returns: A dictionary with a unique ID to check on the scan progress. """ params = { 'port': port, 'protocol': protocol, } return self._request('/shodan/scan/internet', params, method='post') def scan_status(self, scan_id): """Get the status information about a previously submitted scan. :param id: The unique ID for the scan that was submitted :type id: str :returns: A dictionary with general information about the scan, including its status in getting processed. """ return self._request('/shodan/scan/%s' % scan_id, {}) def search(self, query, page=1, limit=None, offset=None, facets=None, minify=True): """Search the SHODAN database. :param query: Search query; identical syntax to the website :type query: str :param page: (optional) Page number of the search results :type page: int :param limit: (optional) Number of results to return :type limit: int :param offset: (optional) Search offset to begin getting results from :type offset: int :param facets: (optional) A list of properties to get summary information on :type facets: str :param minify: (optional) Whether to minify the banner and only return the important data :type minify: bool :returns: A dictionary with 2 main items: matches and total. If facets have been provided then another property called "facets" will be available at the top-level of the dictionary. Visit the website for more detailed information. """ args = { 'query': query, 'minify': minify, } if limit: args['limit'] = limit if offset: args['offset'] = offset else: args['page'] = page if facets: facet_str = helpers.create_facet_string(facets) args['facets'] = facet_str return self._request('/shodan/host/search', args) def search_cursor(self, query, minify=True, retries=5): """Search the SHODAN database. This method returns an iterator that can directly be in a loop. Use it when you want to loop over all of the results of a search query. But this method doesn't return a "matches" array or the "total" information. And it also can't be used with facets, it's only use is to iterate over results more easily. :param query: Search query; identical syntax to the website :type query: str :param minify: (optional) Whether to minify the banner and only return the important data :type minify: bool :param retries: (optional) How often to retry the search in case it times out :type minify: int :returns: A search cursor that can be used as an iterator/ generator. """ args = { 'query': query, 'minify': minify, } page = 1 tries = 0 while page == 1 or results['matches']: try: results = self.search(query, minify=minify, page=page) for banner in results['matches']: try: yield banner except GeneratorExit: return # exit out of the function page += 1 tries = 0 except: # We've retried several times but it keeps failing, so lets error out if tries >= retries: break tries += 1 time.sleep(1.0) # wait 1 second if the search errored out for some reason def search_tokens(self, query): """Returns information about the search query itself (filters used etc.) :param query: Search query; identical syntax to the website :type query: str :returns: A dictionary with 4 main properties: filters, errors, attributes and string. """ query_args = { 'query': query, } return self._request('/shodan/host/search/tokens', query_args) def services(self): """Get a list of services that Shodan crawls :returns: A dictionary containing the ports/ services that Shodan crawls for. The key is the port number and the value is the name of the service. """ return self._request('/shodan/services', {}) def queries(self, page=1, sort='timestamp', order='desc'): """List the search queries that have been shared by other users. :param page: Page number to iterate over results; each page contains 10 items :type page: int :param sort: Sort the list based on a property. Possible values are: votes, timestamp :type sort: str :param order: Whether to sort the list in ascending or descending order. Possible values are: asc, desc :type order: str :returns: A list of saved search queries (dictionaries). """ args = { 'page': page, 'sort': sort, 'order': order, } return self._request('/shodan/query', args) def queries_search(self, query, page=1): """Search the directory of saved search queries in Shodan. :param query: The search string to look for in the search query :type query: str :param page: Page number to iterate over results; each page contains 10 items :type page: int :returns: A list of saved search queries (dictionaries). """ args = { 'page': page, 'query': query, } return self._request('/shodan/query/search', args) def queries_tags(self, size=10): """Search the directory of saved search queries in Shodan. :param query: The number of tags to return :type page: int :returns: A list of tags. """ args = { 'size': size, } return self._request('/shodan/query/tags', args) def create_alert(self, name, ip, expires=0): """Search the directory of saved search queries in Shodan. :param query: The number of tags to return :type page: int :returns: A list of tags. """ data = { 'name': name, 'filters': { 'ip': ip, }, 'expires': expires, } response = helpers.api_request(self.api_key, '/shodan/alert', data=data, params={}, method='post') return response def alerts(self, aid=None, include_expired=True): """List all of the active alerts that the user created.""" if aid: func = '/shodan/alert/%s/info' % aid else: func = '/shodan/alert/info' response = helpers.api_request(self.api_key, func, params={ 'include_expired': include_expired, }) return response def delete_alert(self, aid): """Delete the alert with the given ID.""" func = '/shodan/alert/%s' % aid response = helpers.api_request(self.api_key, func, params={}, method='delete') return response
mit
CongSmile/tp-qemu
qemu/tests/smartcard_setup.py
9
2568
""" smartcard_setup.py - Used as a setup test for smartcard tests. Before doing a remote viewer connection there is some setup required for smartcard tests: On the client, certs that will be put into the smartcard will need to be generated. """ import logging from autotest.client.shared import error from virttest import utils_misc from virttest import utils_spice def run(test, params, env): """ Simple setup test to create certs on the client to be passed to VM's smartcard. :param test: QEMU test object. :param params: Dictionary with the test parameters. :param env: Dictionary with test environment. """ # Get necessary params cert_list = params.get("gencerts").split(",") cert_db = params.get("certdb") self_sign = params.get("self_sign") cert_trustargs = params.get("trustargs") logging.debug("Cert List:") for cert in cert_list: logging.debug(cert) logging.debug(cert_trustargs) logging.debug("CN=" + cert) logging.debug(cert_db) client_vm = env.get_vm(params["client_vm"]) client_vm.verify_alive() client_session = client_vm.wait_for_login( timeout=int(params.get("login_timeout", 360)), username="root", password="123456") for vm in params.get("vms").split(): utils_spice.clear_interface(env.get_vm(vm), int(params.get("login_timeout", "360"))) # generate a random string, used to create a random key for the certs randomstring = utils_misc.generate_random_string(2048) cmd = "echo '" + randomstring + "' > /tmp/randomtext.txt" output = client_session.cmd(cmd) #output2 = client_session.cmd("cat /tmp/randomtext.txt") utils_spice.wait_timeout(5) # for each cert listed by the test, create it on the client for cert in cert_list: cmd = "certutil " if self_sign: cmd += " -x " cmd += "-t '" + cert_trustargs + "' -S -s " + "'CN=" + cert cmd += "' -n '" + cert + "' -d " + cert_db cmd += " -z " + "/tmp/randomtext.txt" logging.debug(cmd) output = client_session.cmd(cmd) logging.debug("Cert Created: " + output) cmd = "certutil -L -d " + cert_db output = client_session.cmd(cmd) logging.info("Listing all certs on the client: " + output) # Verify that all the certs have been generated on the client for cert in cert_list: if not(cert in output): raise error.TestFail("Certificate %s not found" % cert) client_session.close()
gpl-2.0
jbruestle/aggregate_btree
python/bar.py
1
1368
import stat_tree tree = stat_tree.StatsTree('/tmp/thetree') tree.write(0, ['foobar'], {'a': 0.1, 'c': 1, 'b': 1}) tree.write(1, ['foobar'], {'a': 0.1, 'c': 1, 'b': 2}) tree.write(2, ['foobar'], {'a': 0.1, 'c': 100, 'b': 3}) tree.write(3, ['foobar'], {'a': 0.1, 'c': 1, 'b': 4}) tree.write(0.0, ['tag1'], {'m1':500, 'm2':200}) tree.write(0.0, ['tag2'], {'m1':400, 'm3':300}) tree.write(1.0, ['tag1'], {'m1':300, 'm2':200}) tree.write(1.0, ['tag2'], {'m1':200, 'm3':300}) tree.write(2.0, ['tag1'], {'m1':100, 'm2':200}) tree.write(2.0, ['tag2'], {'m1':100, 'm3':200}) tree.write(3.0, ['tag1'], {'m1':200, 'm2':500}) tree.write(3.0, ['tag2'], {'m1':300, 'm3':200}) tree.write(4.0, ['tag1'], {'m1':400, 'm2':700}) tree.write(4.0, ['tag2'], {'m1':500, 'm3':300}) tree.write(5.0, ['tag1'], {'m1':600, 'm2':200}) tree.write(5.0, ['tag2'], {'m1':700, 'm3':100}) tree.write(0, ['foobar'], {'a': 0.1, 'c': 1, 'b': 1}) tree.write(1, ['foobar'], {'a': 0.1, 'c': 1, 'b': 2}) tree.write(2, ['foobar'], {'a': 0.1, 'c': 100, 'b': 3}) tree.write(3, ['foobar'], {'a': 0.1, 'c': 1, 'b': 4}) print "Getting tags" print tree.tags() print "all measures:", tree.measures() print "tag1 measures:", tree.measures('tag1') print "tag2 measures:", tree.measures('tag2') print "tag3 measures:", tree.measures('tag3') print "tag1 info", tree.metrics('tag1', ['m1:cnt', 'm1:avg'], 0.0, 2.0, 5)
agpl-3.0
splunk/splunk-webframework
contrib/django/django/utils/dateparse.py
229
2817
"""Functions to parse datetime objects.""" # We're using regular expressions rather than time.strptime because: # - They provide both validation and parsing. # - They're more flexible for datetimes. # - The date/datetime/time constructors produce friendlier error messages. import datetime import re from django.utils import six from django.utils.timezone import utc from django.utils.tzinfo import FixedOffset date_re = re.compile( r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$' ) time_re = re.compile( r'(?P<hour>\d{1,2}):(?P<minute>\d{1,2})' r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?' ) datetime_re = re.compile( r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})' r'[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})' r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?' r'(?P<tzinfo>Z|[+-]\d{2}:?\d{2})?$' ) def parse_date(value): """Parses a string and return a datetime.date. Raises ValueError if the input is well formatted but not a valid date. Returns None if the input isn't well formatted. """ match = date_re.match(value) if match: kw = dict((k, int(v)) for k, v in six.iteritems(match.groupdict())) return datetime.date(**kw) def parse_time(value): """Parses a string and return a datetime.time. This function doesn't support time zone offsets. Raises ValueError if the input is well formatted but not a valid time. Returns None if the input isn't well formatted, in particular if it contains an offset. """ match = time_re.match(value) if match: kw = match.groupdict() if kw['microsecond']: kw['microsecond'] = kw['microsecond'].ljust(6, '0') kw = dict((k, int(v)) for k, v in six.iteritems(kw) if v is not None) return datetime.time(**kw) def parse_datetime(value): """Parses a string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses an instance of FixedOffset as tzinfo. Raises ValueError if the input is well formatted but not a valid datetime. Returns None if the input isn't well formatted. """ match = datetime_re.match(value) if match: kw = match.groupdict() if kw['microsecond']: kw['microsecond'] = kw['microsecond'].ljust(6, '0') tzinfo = kw.pop('tzinfo') if tzinfo == 'Z': tzinfo = utc elif tzinfo is not None: offset = 60 * int(tzinfo[1:3]) + int(tzinfo[-2:]) if tzinfo[0] == '-': offset = -offset tzinfo = FixedOffset(offset) kw = dict((k, int(v)) for k, v in six.iteritems(kw) if v is not None) kw['tzinfo'] = tzinfo return datetime.datetime(**kw)
apache-2.0
BaladiDogGames/baladidoggames.github.io
mingw/bin/lib/msilib/text.py
159
9313
import msilib,os;dirname=os.path.dirname(__file__) ActionText = [ (u'InstallValidate', u'Validating install', None), (u'InstallFiles', u'Copying new files', u'File: [1], Directory: [9], Size: [6]'), (u'InstallAdminPackage', u'Copying network install files', u'File: [1], Directory: [9], Size: [6]'), (u'FileCost', u'Computing space requirements', None), (u'CostInitialize', u'Computing space requirements', None), (u'CostFinalize', u'Computing space requirements', None), (u'CreateShortcuts', u'Creating shortcuts', u'Shortcut: [1]'), (u'PublishComponents', u'Publishing Qualified Components', u'Component ID: [1], Qualifier: [2]'), (u'PublishFeatures', u'Publishing Product Features', u'Feature: [1]'), (u'PublishProduct', u'Publishing product information', None), (u'RegisterClassInfo', u'Registering Class servers', u'Class Id: [1]'), (u'RegisterExtensionInfo', u'Registering extension servers', u'Extension: [1]'), (u'RegisterMIMEInfo', u'Registering MIME info', u'MIME Content Type: [1], Extension: [2]'), (u'RegisterProgIdInfo', u'Registering program identifiers', u'ProgId: [1]'), (u'AllocateRegistrySpace', u'Allocating registry space', u'Free space: [1]'), (u'AppSearch', u'Searching for installed applications', u'Property: [1], Signature: [2]'), (u'BindImage', u'Binding executables', u'File: [1]'), (u'CCPSearch', u'Searching for qualifying products', None), (u'CreateFolders', u'Creating folders', u'Folder: [1]'), (u'DeleteServices', u'Deleting services', u'Service: [1]'), (u'DuplicateFiles', u'Creating duplicate files', u'File: [1], Directory: [9], Size: [6]'), (u'FindRelatedProducts', u'Searching for related applications', u'Found application: [1]'), (u'InstallODBC', u'Installing ODBC components', None), (u'InstallServices', u'Installing new services', u'Service: [2]'), (u'LaunchConditions', u'Evaluating launch conditions', None), (u'MigrateFeatureStates', u'Migrating feature states from related applications', u'Application: [1]'), (u'MoveFiles', u'Moving files', u'File: [1], Directory: [9], Size: [6]'), (u'PatchFiles', u'Patching files', u'File: [1], Directory: [2], Size: [3]'), (u'ProcessComponents', u'Updating component registration', None), (u'RegisterComPlus', u'Registering COM+ Applications and Components', u'AppId: [1]{{, AppType: [2], Users: [3], RSN: [4]}}'), (u'RegisterFonts', u'Registering fonts', u'Font: [1]'), (u'RegisterProduct', u'Registering product', u'[1]'), (u'RegisterTypeLibraries', u'Registering type libraries', u'LibID: [1]'), (u'RegisterUser', u'Registering user', u'[1]'), (u'RemoveDuplicateFiles', u'Removing duplicated files', u'File: [1], Directory: [9]'), (u'RemoveEnvironmentStrings', u'Updating environment strings', u'Name: [1], Value: [2], Action [3]'), (u'RemoveExistingProducts', u'Removing applications', u'Application: [1], Command line: [2]'), (u'RemoveFiles', u'Removing files', u'File: [1], Directory: [9]'), (u'RemoveFolders', u'Removing folders', u'Folder: [1]'), (u'RemoveIniValues', u'Removing INI files entries', u'File: [1], Section: [2], Key: [3], Value: [4]'), (u'RemoveODBC', u'Removing ODBC components', None), (u'RemoveRegistryValues', u'Removing system registry values', u'Key: [1], Name: [2]'), (u'RemoveShortcuts', u'Removing shortcuts', u'Shortcut: [1]'), (u'RMCCPSearch', u'Searching for qualifying products', None), (u'SelfRegModules', u'Registering modules', u'File: [1], Folder: [2]'), (u'SelfUnregModules', u'Unregistering modules', u'File: [1], Folder: [2]'), (u'SetODBCFolders', u'Initializing ODBC directories', None), (u'StartServices', u'Starting services', u'Service: [1]'), (u'StopServices', u'Stopping services', u'Service: [1]'), (u'UnpublishComponents', u'Unpublishing Qualified Components', u'Component ID: [1], Qualifier: [2]'), (u'UnpublishFeatures', u'Unpublishing Product Features', u'Feature: [1]'), (u'UnregisterClassInfo', u'Unregister Class servers', u'Class Id: [1]'), (u'UnregisterComPlus', u'Unregistering COM+ Applications and Components', u'AppId: [1]{{, AppType: [2]}}'), (u'UnregisterExtensionInfo', u'Unregistering extension servers', u'Extension: [1]'), (u'UnregisterFonts', u'Unregistering fonts', u'Font: [1]'), (u'UnregisterMIMEInfo', u'Unregistering MIME info', u'MIME Content Type: [1], Extension: [2]'), (u'UnregisterProgIdInfo', u'Unregistering program identifiers', u'ProgId: [1]'), (u'UnregisterTypeLibraries', u'Unregistering type libraries', u'LibID: [1]'), (u'WriteEnvironmentStrings', u'Updating environment strings', u'Name: [1], Value: [2], Action [3]'), (u'WriteIniValues', u'Writing INI files values', u'File: [1], Section: [2], Key: [3], Value: [4]'), (u'WriteRegistryValues', u'Writing system registry values', u'Key: [1], Name: [2], Value: [3]'), (u'Advertise', u'Advertising application', None), (u'GenerateScript', u'Generating script operations for action:', u'[1]'), (u'InstallSFPCatalogFile', u'Installing system catalog', u'File: [1], Dependencies: [2]'), (u'MsiPublishAssemblies', u'Publishing assembly information', u'Application Context:[1], Assembly Name:[2]'), (u'MsiUnpublishAssemblies', u'Unpublishing assembly information', u'Application Context:[1], Assembly Name:[2]'), (u'Rollback', u'Rolling back action:', u'[1]'), (u'RollbackCleanup', u'Removing backup files', u'File: [1]'), (u'UnmoveFiles', u'Removing moved files', u'File: [1], Directory: [9]'), (u'UnpublishProduct', u'Unpublishing product information', None), ] UIText = [ (u'AbsentPath', None), (u'bytes', u'bytes'), (u'GB', u'GB'), (u'KB', u'KB'), (u'MB', u'MB'), (u'MenuAbsent', u'Entire feature will be unavailable'), (u'MenuAdvertise', u'Feature will be installed when required'), (u'MenuAllCD', u'Entire feature will be installed to run from CD'), (u'MenuAllLocal', u'Entire feature will be installed on local hard drive'), (u'MenuAllNetwork', u'Entire feature will be installed to run from network'), (u'MenuCD', u'Will be installed to run from CD'), (u'MenuLocal', u'Will be installed on local hard drive'), (u'MenuNetwork', u'Will be installed to run from network'), (u'ScriptInProgress', u'Gathering required information...'), (u'SelAbsentAbsent', u'This feature will remain uninstalled'), (u'SelAbsentAdvertise', u'This feature will be set to be installed when required'), (u'SelAbsentCD', u'This feature will be installed to run from CD'), (u'SelAbsentLocal', u'This feature will be installed on the local hard drive'), (u'SelAbsentNetwork', u'This feature will be installed to run from the network'), (u'SelAdvertiseAbsent', u'This feature will become unavailable'), (u'SelAdvertiseAdvertise', u'Will be installed when required'), (u'SelAdvertiseCD', u'This feature will be available to run from CD'), (u'SelAdvertiseLocal', u'This feature will be installed on your local hard drive'), (u'SelAdvertiseNetwork', u'This feature will be available to run from the network'), (u'SelCDAbsent', u"This feature will be uninstalled completely, you won't be able to run it from CD"), (u'SelCDAdvertise', u'This feature will change from run from CD state to set to be installed when required'), (u'SelCDCD', u'This feature will remain to be run from CD'), (u'SelCDLocal', u'This feature will change from run from CD state to be installed on the local hard drive'), (u'SelChildCostNeg', u'This feature frees up [1] on your hard drive.'), (u'SelChildCostPos', u'This feature requires [1] on your hard drive.'), (u'SelCostPending', u'Compiling cost for this feature...'), (u'SelLocalAbsent', u'This feature will be completely removed'), (u'SelLocalAdvertise', u'This feature will be removed from your local hard drive, but will be set to be installed when required'), (u'SelLocalCD', u'This feature will be removed from your local hard drive, but will be still available to run from CD'), (u'SelLocalLocal', u'This feature will remain on you local hard drive'), (u'SelLocalNetwork', u'This feature will be removed from your local hard drive, but will be still available to run from the network'), (u'SelNetworkAbsent', u"This feature will be uninstalled completely, you won't be able to run it from the network"), (u'SelNetworkAdvertise', u'This feature will change from run from network state to set to be installed when required'), (u'SelNetworkLocal', u'This feature will change from run from network state to be installed on the local hard drive'), (u'SelNetworkNetwork', u'This feature will remain to be run from the network'), (u'SelParentCostNegNeg', u'This feature frees up [1] on your hard drive. It has [2] of [3] subfeatures selected. The subfeatures free up [4] on your hard drive.'), (u'SelParentCostNegPos', u'This feature frees up [1] on your hard drive. It has [2] of [3] subfeatures selected. The subfeatures require [4] on your hard drive.'), (u'SelParentCostPosNeg', u'This feature requires [1] on your hard drive. It has [2] of [3] subfeatures selected. The subfeatures free up [4] on your hard drive.'), (u'SelParentCostPosPos', u'This feature requires [1] on your hard drive. It has [2] of [3] subfeatures selected. The subfeatures require [4] on your hard drive.'), (u'TimeRemaining', u'Time remaining: {[1] minutes }{[2] seconds}'), (u'VolumeCostAvailable', u'Available'), (u'VolumeCostDifference', u'Difference'), (u'VolumeCostRequired', u'Required'), (u'VolumeCostSize', u'Disk Size'), (u'VolumeCostVolume', u'Volume'), ] tables=['ActionText', 'UIText']
mit
JonathanStein/odoo
addons/account_test/report/account_test_report.py
194
3819
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # $Id$ # # 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/>. # ############################################################################## import datetime import time from openerp.osv import osv from openerp.tools.translate import _ from openerp.report import report_sxw from openerp.tools.safe_eval import safe_eval as eval # # Use period and Journal for selection or resources # class report_assert_account(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(report_assert_account, self).__init__(cr, uid, name, context=context) self.localcontext.update( { 'time': time, 'datetime': datetime, 'execute_code': self.execute_code, }) def execute_code(self, code_exec): def reconciled_inv(): """ returns the list of invoices that are set as reconciled = True """ return self.pool.get('account.invoice').search(self.cr, self.uid, [('reconciled','=',True)]) def order_columns(item, cols=None): """ This function is used to display a dictionary as a string, with its columns in the order chosen. :param item: dict :param cols: list of field names :returns: a list of tuples (fieldname: value) in a similar way that would dict.items() do except that the returned values are following the order given by cols :rtype: [(key, value)] """ if cols is None: cols = item.keys() return [(col, item.get(col)) for col in cols if col in item.keys()] localdict = { 'cr': self.cr, 'uid': self.uid, 'reconciled_inv': reconciled_inv, #specific function used in different tests 'result': None, #used to store the result of the test 'column_order': None, #used to choose the display order of columns (in case you are returning a list of dict) } eval(code_exec, localdict, mode="exec", nocopy=True) result = localdict['result'] column_order = localdict.get('column_order', None) if not isinstance(result, (tuple, list, set)): result = [result] if not result: result = [_('The test was passed successfully')] else: def _format(item): if isinstance(item, dict): return ', '.join(["%s: %s" % (tup[0], tup[1]) for tup in order_columns(item, column_order)]) else: return item result = [_(_format(rec)) for rec in result] return result class report_accounttest(osv.AbstractModel): _name = 'report.account_test.report_accounttest' _inherit = 'report.abstract_report' _template = 'account_test.report_accounttest' _wrapped_report_class = report_assert_account # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
awangga/tweepy
tests/test_rate_limit.py
47
5416
import unittest import os from tweepy import API, Cursor from tweepy.error import TweepError import six if six.PY3: import unittest else: import unittest2 as unittest from .config import create_auth testratelimit = 'TEST_RATE_LIMIT' in os.environ @unittest.skipIf(not testratelimit, "skipping rate limiting test since testratelimit is not specified") class TweepyRateLimitTests(unittest.TestCase): def setUp(self): self.api = API(create_auth()) self.api.retry_count = 2 self.api.retry_delay = 5 self.api.retry_errors = set([401, 404, 503]) self.api.wait_on_rate_limit = True def testratelimit(self): # should cause the api to sleep test_user_ids = [123796151, 263168076, 990027860, 901955678, 214630268, 18305040, 36126818, 312483939, 426975332, 469837158, 1104126054, 1342066705, 281632872, 608977002, 242901099, 846643308, 1166401645, 153886833, 95314037, 314458230, 149856382, 287916159, 472506496, 267180736, 251764866, 351035524, 997113991, 445915272, 57335947, 251043981, 95051918, 200761489, 48341139, 972660884, 422330517, 326429297, 864927896, 94183577, 95887514, 220807325, 194330782, 58796741, 1039212709, 1017192614, 625828008, 66539548, 320566383, 309829806, 571383983, 382694863, 439140530, 93977882, 277651636, 19984414, 502004733, 1093673143, 60014776, 469849460, 937107642, 155516395, 1272979644, 617433802, 102212981, 301228831, 805784562, 427799926, 322298054, 162197537, 554001783, 89252046, 536789199, 177807568, 805044434, 495541739, 392904916, 154656981, 291266775, 865454102, 475846642, 56910044, 55834550, 177389790, 339841061, 319614526, 954529597, 595960038, 501301480, 15679722, 938090731, 495829228, 325034224, 1041031410, 18882803, 161080540, 456245496, 636854521, 811974907, 222085372, 222306563, 422846724, 281616645, 223641862, 705786134, 1038901512, 174211339, 426795277, 370259272, 34759594, 366410456, 320577812, 757211413, 483238166, 222624369, 29425605, 456455726, 408723740, 1274608346, 295837985, 273490210, 232497444, 726843685, 465232166, 18850087, 22503721, 259629354, 414250375, 1259941938, 777167150, 1080552157, 1271036282, 1000551816, 109443357, 345781858, 45113654, 406536508, 253801866, 98836799, 395469120, 252920129, 604660035, 69124420, 283459909, 482261729, 377767308, 565240139, 191788429, 102048080, 330054371, 527868245, 177044049, 1250978114, 424042840, 15810905, 389030234, 69324415, 15638877, 159080798, 378708319, 549183840, 1034658145, 629924195, 969130340, 1143593845, 188129639, 535863656, 552452458, 1325277547, 756236624, 48421608, 178495858, 566206836, 378519925, 22678249, 377659768, 102326650, 76783997, 440716178, 49062271, 26296705, 1328036587, 289644932, 305767830, 437305735, 124821901, 591735533, 155140501, 1099612568, 631398810, 469295515, 131350941, 325804447, 529801632, 977197808, 232613818, 614777251, 229261732, 255533478, 256942503, 169583016, 237860252, 29257799, 276668845, 871571886, 398162507, 451954078, 526016951, 285655480, 1281827257, 340042172, 146653629, 61055423, 33407417, 95582321, 237420995, 310960580, 1222064886, 16490950, 60924360, 81928649, 374424010, 45703629, 817455571, 336077264, 400268024, 1203200467, 457105876, 232309205, 45838026, 91972056, 226927065, 82125276, 760131962, 1032274398, 562552291, 155155166, 146464315, 864864355, 128655844, 589747622, 293290470, 192004584, 19100402, 133931498, 19775979, 446374381, 1175241198, 20128240, 332395944, 74575955, 247407092, 427794934, 329823657, 405742072, 497475320, 997384698, 147718652, 757768705, 96757163, 289874437, 29892071, 568541704, 297039276, 356590090, 502055438, 291826323, 238944785, 71483924, 50031538, 863355416, 120273668, 224403994, 14880858, 1241506364, 848962080, 57898416, 599695908, 1222132262, 54045447, 907207212, 851412402, 454418991, 231844616, 618447410, 602997300, 447685173, 19681556, 22233657, 509901138, 184705596, 307624714, 553017923, 1249878596, 33727045, 419873350, 789307489, 287531592, 399163977, 1069425228, 920789582, 136891149, 134857296, 358558478, 436855382, 963011161, 195764827, 548872797, 1058980446, 442376799, 578216544, 527147110, 122077799, 1004773993, 420332138, 514994279, 61530732, 133462802, 19513966, 1286972018, 786121332, 265863798, 221258362, 42656382, 43631231, 198264256, 944382595, 37387030, 260948614, 314406408, 296512982, 92830743, 24519306, 21070476, 454107789, 331006606, 939713168, 256197265, 30065299, 74774188, 1332842606, 289424023, 526992024, 429933209, 116384410, 762143389, 308093598, 421208736, 454943394, 66026267, 158851748, 257550092, 70697073, 903627432, 290669225, 121168557, 92994330, 67642033, 635183794, 499303091, 421205146, 1252648171, 375268025, 16281866, 211960508, 267179466, 129016511, 157172416, 373370004, 167781059, 43624522] for user_id in test_user_ids: try: self.api.user_timeline(user_id=user_id, count=1, include_rts=True) except TweepError as e: # continue if we're not autherized to access the user's timeline or she doesn't exist anymore if e.response is not None and e.response.status in set([401, 404]): continue raise e if __name__ == '__main__': oauth_consumer_key = os.environ.get('CONSUMER_KEY', '') if testratelimit: unittest.TextTestRunner().run(unittest.loader.makeSuite(TweepyRateLimitTests)) else: unittest.main()
mit
RuudBurger/CouchPotatoServer
couchpotato/core/_base/clientscript.py
37
1500
import os from couchpotato.core.event import addEvent from couchpotato.core.helpers.variable import tryInt from couchpotato.core.logger import CPLog from couchpotato.core.plugins.base import Plugin from couchpotato.environment import Env log = CPLog(__name__) autoload = 'ClientScript' class ClientScript(Plugin): paths = { 'style': [ 'style/combined.min.css', ], 'script': [ 'scripts/combined.vendor.min.js', 'scripts/combined.base.min.js', 'scripts/combined.plugins.min.js', ], } def __init__(self): addEvent('clientscript.get_styles', self.getStyles) addEvent('clientscript.get_scripts', self.getScripts) self.makeRelative() def makeRelative(self): for static_type in self.paths: updates_paths = [] for rel_path in self.paths.get(static_type): file_path = os.path.join(Env.get('app_dir'), 'couchpotato', 'static', rel_path) core_url = 'static/%s?%d' % (rel_path, tryInt(os.path.getmtime(file_path))) updates_paths.append(core_url) self.paths[static_type] = updates_paths def getStyles(self, *args, **kwargs): return self.get('style', *args, **kwargs) def getScripts(self, *args, **kwargs): return self.get('script', *args, **kwargs) def get(self, type): if type in self.paths: return self.paths[type] return []
gpl-3.0
bencorbett90/Graph
graph/datastream.py
1
5964
import numpy as np from PyQt4 import QtCore, QtGui import h5py from utils import * class DataStream(): def __init__(self, path, dataPath): """Initializes a HDF5 DataStream. PATH is the path to the .hdf5 file, and DATAPATH is the path within the file to the specific dataset. """ self.filePath = path self.dataPath = dataPath # Dictionary of the overall dataset attributes. self.attrs = {} # Dictionary of arg/val names to a dict of arg/val attributes, # the arg/val dataset path, and the dataset shape. # if a val also has dimScales which is a list of args names. self.args = {} self.vals = {} self.get_attrs() self.name = self.attrs['Name'] def get_attrs(self): """Load all of the attributes of the dataset into SELF.ATTRS and all of the arg/val attributes into SELF.ARGS/SELF.VALS as well as the shape of the arg/val, the path to the arg/val and for vals the associated dimension scales.""" f = h5py.File(self.filePath, 'r') for name, value in f[self.dataPath].attrs.iteritems(): self.attrs[str(name)] = value for dsetName, dset in f[self.dataPath].iteritems(): givenName = dset.attrs['Name'] if dsetName[0:11] == 'Independent': if givenName not in self.args.iterkeys(): dsetName = givenName self.args[str(dsetName)] = {} attrDict = self.args[dsetName] elif dsetName[0:9] == 'Dependent': if givenName not in self.vals.iterkeys(): dsetName = givenName self.vals[str(dsetName)] = {} attrDict = self.vals[dsetName] else: continue # Adding the dataset attributes for name, value in dset.attrs.iteritems(): attrDict[str(name)] = value # Adding the datset path and shape. attrDict['path'] = dset.name attrDict['shape'] = dset.shape # Taking care of dimension scales if the dataset # is an independent variable. Only use the first dim scale. for valDict in self.vals.itervalues(): dset = f[valDict['path']] dimScales = [] for i in range(len(dset.dims)): dimPath = dset.dims[i][0].name dimScales += [self._get_arg_name_from_path(dimPath)] valDict['dimScales'] = dimScales f.close() def get_vals(self, minDim): """Return a list of val names of vals of dimension greater than or equal to MINDIM.""" valNames = [] for valName, valDict in self.vals.iteritems(): if len(valDict['shape']) >= minDim: valNames += [valName] return valNames def _get_arg_name_from_path(self, path): """Given an argument path, return the name used as the given argumnet's key in SELF.ARGS""" for k, v in self.args.iteritems(): if v['path'] == path: return k def load_arg(self, argName, s=None): """Return the argument ARGNAME[s]""" f = h5py.File(self.filePath, 'r') path = self.args[argName]['path'] if s is None: data = f[path][:] else: data = f[path][s] f.close() return data def load_val(self, valName, s=None): f = h5py.File(self.filePath, 'r') path = self.vals[valName]['path'] if s is None: data = f[path][..., :] else: data = f[path][s] f.close() return data def gen_slice(self, valName, sliceDict): """Generate a slice into val VALNAME using the dictionary SLICEDICT which is a dictionary from the names of the axis to the desired axis slice.""" argNames = self.get_args_to_val(valName) s = [] for argName in argNames: argSlice = sliceDict[argName] if isinstance(argSlice, tuple): argSlice = slice(*argSlice) s += [argSlice] return tuple(s) def get_args_to_val(self, valName): """Return the name of all the arguments to the value VALNAME.""" return self.vals[valName]['dimScales'] def get_val_shape(self, valName): return self.vals[valName]['shape'] def get_arg_shape(self, argName): """Return the shape of arg ARGNAME. Return the first item of shape, since args are 1D.""" return self.args[argName]['shape'][0] def addToTab(self, tab): """Add SELF to QTreeWidget TAB.TREE_DATA""" tree = tab.tree_data nameDict = tab.dataStreams if self.name in nameDict.keys(): if nameDict[self.name] != self: baseName = self.name + '({})' self.name = uniqueName(baseName, 1, nameDict.keys()) dsTW = QtGui.QTreeWidgetItem([self.name]) for valName, valDict in self.vals.iteritems(): valTW = QtGui.QTreeWidgetItem() valTW.setText(0, valName) valTW.setText(1, str(valDict['shape'])) dsTW.addChild(valTW) #setting fields for action upon right click valTW.isClickable = True valTW.dataType = 'val' valTW.ds = self for argName in self.get_args_to_val(valName): argDict = self.args[argName] argTW = QtGui.QTreeWidgetItem() argTW.setText(0, argName) argTW.setText(1, str(argDict['shape'])) valTW.addChild(argTW) #setting fields for action upon right click argTW.isClickable = True argTW.dataType = 'arg' argTW.valName = valName argTW.ds = self tree.addTopLevelItem(dsTW)
gpl-2.0
ak2703/edx-platform
lms/djangoapps/commerce/tests/test_views.py
85
4208
""" Tests for commerce views. """ import json from uuid import uuid4 from nose.plugins.attrib import attr import ddt from django.conf import settings from django.core.urlresolvers import reverse from django.test import TestCase import mock from student.tests.factories import UserFactory class UserMixin(object): """ Mixin for tests involving users. """ def setUp(self): super(UserMixin, self).setUp() self.user = UserFactory() def _login(self): """ Log into LMS. """ self.client.login(username=self.user.username, password='test') @attr('shard_1') @ddt.ddt class ReceiptViewTests(UserMixin, TestCase): """ Tests for the receipt view. """ def test_login_required(self): """ The view should redirect to the login page if the user is not logged in. """ self.client.logout() response = self.client.post(reverse('commerce:checkout_receipt')) self.assertEqual(response.status_code, 302) def post_to_receipt_page(self, post_data): """ DRY helper """ response = self.client.post(reverse('commerce:checkout_receipt'), params={'basket_id': 1}, data=post_data) self.assertEqual(response.status_code, 200) return response @ddt.data('decision', 'reason_code', 'signed_field_names', None) def test_is_cybersource(self, post_key): """ Ensure the view uses three specific POST keys to detect a request initiated by Cybersource. """ self._login() post_data = {'decision': 'REJECT', 'reason_code': '200', 'signed_field_names': 'dummy'} if post_key is not None: # a key will be missing; we will not expect the receipt page to handle a cybersource decision del post_data[post_key] expected_pattern = r"<title>(\s+)Receipt" else: expected_pattern = r"<title>(\s+)Payment Failed" response = self.post_to_receipt_page(post_data) self.assertRegexpMatches(response.content, expected_pattern) @ddt.data('ACCEPT', 'REJECT', 'ERROR') def test_cybersource_decision(self, decision): """ Ensure the view renders a page appropriately depending on the Cybersource decision. """ self._login() post_data = {'decision': decision, 'reason_code': '200', 'signed_field_names': 'dummy'} expected_pattern = r"<title>(\s+)Receipt" if decision == 'ACCEPT' else r"<title>(\s+)Payment Failed" response = self.post_to_receipt_page(post_data) self.assertRegexpMatches(response.content, expected_pattern) @ddt.data(True, False) @mock.patch('commerce.views.is_user_payment_error') def test_cybersource_message(self, is_user_message_expected, mock_is_user_payment_error): """ Ensure that the page displays the right message for the reason_code (it may be a user error message or a system error message). """ mock_is_user_payment_error.return_value = is_user_message_expected self._login() response = self.post_to_receipt_page({'decision': 'REJECT', 'reason_code': '99', 'signed_field_names': 'dummy'}) self.assertTrue(mock_is_user_payment_error.called) self.assertTrue(mock_is_user_payment_error.call_args[0][0], '99') user_message = "There was a problem with this transaction" system_message = "A system error occurred while processing your payment" self.assertRegexpMatches(response.content, user_message if is_user_message_expected else system_message) self.assertNotRegexpMatches(response.content, user_message if not is_user_message_expected else system_message) @mock.patch.dict(settings.FEATURES, {"IS_EDX_DOMAIN": True}) def test_hide_nav_header(self): self._login() post_data = {'decision': 'ACCEPT', 'reason_code': '200', 'signed_field_names': 'dummy'} response = self.post_to_receipt_page(post_data) # Verify that the header navigation links are hidden for the edx.org version self.assertNotContains(response, "How it Works") self.assertNotContains(response, "Find courses") self.assertNotContains(response, "Schools & Partners")
agpl-3.0
mjtamlyn/django
tests/admin_ordering/tests.py
37
6637
from django.contrib import admin from django.contrib.admin.options import ModelAdmin from django.contrib.auth.models import User from django.test import RequestFactory, TestCase from .models import ( Band, DynOrderingBandAdmin, Song, SongInlineDefaultOrdering, SongInlineNewOrdering, ) class MockRequest: pass class MockSuperUser: def has_perm(self, perm): return True def has_module_perms(self, module): return True request = MockRequest() request.user = MockSuperUser() site = admin.AdminSite() class TestAdminOrdering(TestCase): """ Let's make sure that ModelAdmin.get_queryset uses the ordering we define in ModelAdmin rather that ordering defined in the model's inner Meta class. """ def setUp(self): self.request_factory = RequestFactory() Band.objects.bulk_create([ Band(name='Aerosmith', bio='', rank=3), Band(name='Radiohead', bio='', rank=1), Band(name='Van Halen', bio='', rank=2), ]) def test_default_ordering(self): """ The default ordering should be by name, as specified in the inner Meta class. """ ma = ModelAdmin(Band, site) names = [b.name for b in ma.get_queryset(request)] self.assertEqual(['Aerosmith', 'Radiohead', 'Van Halen'], names) def test_specified_ordering(self): """ Let's use a custom ModelAdmin that changes the ordering, and make sure it actually changes. """ class BandAdmin(ModelAdmin): ordering = ('rank',) # default ordering is ('name',) ma = BandAdmin(Band, site) names = [b.name for b in ma.get_queryset(request)] self.assertEqual(['Radiohead', 'Van Halen', 'Aerosmith'], names) def test_dynamic_ordering(self): """ Let's use a custom ModelAdmin that changes the ordering dynamically. """ super_user = User.objects.create(username='admin', is_superuser=True) other_user = User.objects.create(username='other') request = self.request_factory.get('/') request.user = super_user ma = DynOrderingBandAdmin(Band, site) names = [b.name for b in ma.get_queryset(request)] self.assertEqual(['Radiohead', 'Van Halen', 'Aerosmith'], names) request.user = other_user names = [b.name for b in ma.get_queryset(request)] self.assertEqual(['Aerosmith', 'Radiohead', 'Van Halen'], names) class TestInlineModelAdminOrdering(TestCase): """ Let's make sure that InlineModelAdmin.get_queryset uses the ordering we define in InlineModelAdmin. """ def setUp(self): self.band = Band.objects.create(name='Aerosmith', bio='', rank=3) Song.objects.bulk_create([ Song(band=self.band, name='Pink', duration=235), Song(band=self.band, name='Dude (Looks Like a Lady)', duration=264), Song(band=self.band, name='Jaded', duration=214), ]) def test_default_ordering(self): """ The default ordering should be by name, as specified in the inner Meta class. """ inline = SongInlineDefaultOrdering(self.band, site) names = [s.name for s in inline.get_queryset(request)] self.assertEqual(['Dude (Looks Like a Lady)', 'Jaded', 'Pink'], names) def test_specified_ordering(self): """ Let's check with ordering set to something different than the default. """ inline = SongInlineNewOrdering(self.band, site) names = [s.name for s in inline.get_queryset(request)] self.assertEqual(['Jaded', 'Pink', 'Dude (Looks Like a Lady)'], names) class TestRelatedFieldsAdminOrdering(TestCase): def setUp(self): self.b1 = Band.objects.create(name='Pink Floyd', bio='', rank=1) self.b2 = Band.objects.create(name='Foo Fighters', bio='', rank=5) # we need to register a custom ModelAdmin (instead of just using # ModelAdmin) because the field creator tries to find the ModelAdmin # for the related model class SongAdmin(admin.ModelAdmin): pass site.register(Song, SongAdmin) def tearDown(self): site.unregister(Song) if Band in site._registry: site.unregister(Band) def check_ordering_of_field_choices(self, correct_ordering): fk_field = site._registry[Song].formfield_for_foreignkey(Song.band.field, request=None) m2m_field = site._registry[Song].formfield_for_manytomany(Song.other_interpreters.field, request=None) self.assertEqual(list(fk_field.queryset), correct_ordering) self.assertEqual(list(m2m_field.queryset), correct_ordering) def test_no_admin_fallback_to_model_ordering(self): # should be ordered by name (as defined by the model) self.check_ordering_of_field_choices([self.b2, self.b1]) def test_admin_with_no_ordering_fallback_to_model_ordering(self): class NoOrderingBandAdmin(admin.ModelAdmin): pass site.register(Band, NoOrderingBandAdmin) # should be ordered by name (as defined by the model) self.check_ordering_of_field_choices([self.b2, self.b1]) def test_admin_ordering_beats_model_ordering(self): class StaticOrderingBandAdmin(admin.ModelAdmin): ordering = ('rank',) site.register(Band, StaticOrderingBandAdmin) # should be ordered by rank (defined by the ModelAdmin) self.check_ordering_of_field_choices([self.b1, self.b2]) def test_custom_queryset_still_wins(self): """Custom queryset has still precedence (#21405)""" class SongAdmin(admin.ModelAdmin): # Exclude one of the two Bands from the querysets def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'band': kwargs["queryset"] = Band.objects.filter(rank__gt=2) return super().formfield_for_foreignkey(db_field, request, **kwargs) def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == 'other_interpreters': kwargs["queryset"] = Band.objects.filter(rank__gt=2) return super().formfield_for_foreignkey(db_field, request, **kwargs) class StaticOrderingBandAdmin(admin.ModelAdmin): ordering = ('rank',) site.unregister(Song) site.register(Song, SongAdmin) site.register(Band, StaticOrderingBandAdmin) self.check_ordering_of_field_choices([self.b2])
bsd-3-clause
c3pko/GovScrape
dynamic_scraper/spiders/checker_test.py
4
4107
from scrapy import log, signals from scrapy.exceptions import CloseSpider from scrapy.http import Request from scrapy.xlib.pydispatch import dispatcher from dynamic_scraper.spiders.django_base_spider import DjangoBaseSpider from dynamic_scraper.models import Scraper class CheckerTest(DjangoBaseSpider): name = 'checker_test' command = 'scrapy crawl checker_test -a id=SCRAPER_ID' def __init__(self, *args, **kwargs): self._set_ref_object(Scraper, **kwargs) self._set_config(**kwargs) if self.ref_object.checker_type == 'N': msg = "No checker defined for scraper!" log.msg(msg, log.ERROR) raise CloseSpider(msg) idf_elems = self.ref_object.get_id_field_elems() if not (len(idf_elems) == 1 and idf_elems[0].scraped_obj_attr.attr_type == 'U'): msg = 'Checkers can only be used for scraped object classed defined with a single DETAIL_PAGE_URL type id field!' log.msg(msg, log.ERROR) raise CloseSpider(msg) if self.ref_object.checker_type == '4': if not self.ref_object.checker_ref_url: msg = "Please provide a reference url for your 404 checker (Command: %s)." % (self.command) log.msg(msg, log.ERROR) raise CloseSpider(msg) if self.ref_object.checker_type == 'X': if not self.ref_object.checker_x_path or not self.ref_object.checker_ref_url: msg = "Please provide the necessary x_path fields for your 404_OR_X_PATH checker (Command: %s)." % (self.command) log.msg(msg, log.ERROR) raise CloseSpider(msg) self.start_urls.append(self.ref_object.checker_ref_url) dispatcher.connect(self.response_received, signal=signals.response_received) def _set_config(self, **kwargs): log_msg = "" super(CheckerTest, self)._set_config(log_msg, **kwargs) def spider_closed(self): pass def start_requests(self): for url in self.start_urls: meta = {} if self.ref_object.detail_page_content_type == 'H' and self.ref_object.render_javascript: meta['splash'] = { 'endpoint': 'render.html', 'args': self.conf['SPLASH_ARGS'].copy() } yield Request(url, self.parse, meta=meta) def response_received(self, **kwargs): if kwargs['response'].status == 404: if self.ref_object.checker_type == '4': self.log("Checker configuration working (ref url request returning 404).", log.INFO) if self.ref_object.checker_type == 'X': self.log('A request of your ref url is returning 404. Your x_path can not be applied!', log.WARNING) else: if self.ref_object.checker_type == '4': self.log('Ref url request not returning 404!', log.WARNING) def parse(self, response): if self.ref_object.checker_type == '4': return try: test_select = response.xpath(self.ref_object.checker_x_path).extract() except ValueError: self.log('Invalid checker x_path!', log.ERROR) return if len(test_select) == 0: self.log("Checker configuration not working (no elements found for xpath on reference url page)!", log.ERROR) else: if self.ref_object.checker_x_path_result == '': self.log("Checker configuration working (elements for x_path found on reference url page (no x_path result defined)).", log.INFO) else: if test_select[0] != self.ref_object.checker_x_path_result: self.log("Checker configuration not working (expected x_path result not found on reference url page)!", log.ERROR) else: self.log("Checker configuration working (expected x_path result found on reference url page).", log.INFO)
bsd-3-clause
zappyk-github/zappyk-python
src/src_zappyk/queryExecWebZI/setup.py
1
3114
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'zappyk' import os, sys from lib_zappyk import _setup from QueryExecWebZI.xlsX2splits_sheets import _project, _description, _version #CZ#project = 'QueryExecWebZI' #CZ#name = __import__(project).get_project() #CZ#description = __import__(project).get_description() #CZ#version = __import__(project).get_version() name = _project description = _description version = _version author = _setup.AUTHOR author_email = _setup.AUTHOR_EMAIL license = _setup.LICENSE url = _setup.URL keywords = _setup._keywords([author]) path_execute = [name] name_execute = 'sql2exec-web-zi.py' path_img_ico = ['images'] name_img_ico = 'gear.ico' file_execute = os.path.join(os.path.join(*path_execute), name_execute) file_img_ico = os.path.join(os.path.join(*path_img_ico), name_img_ico) pkgs_exclude = ['tkinter', 'PyQt4'] #pkgs_include= _setup._find_packages('.', pkgs_exclude) pkgs_include = _setup._find_packages(exclude=pkgs_exclude) #file_include = ['%s-launch.bat' % project] file_include = ['%s-launch.bat' % _project] build_exe = None build_exe = _setup._build_exe(None, name, version) ############################################################################### (base, exte) = _setup._setup_Executable_base_exte() executables = _setup._setup_Executable(file_execute ,base=base ,icon=file_img_ico ,appendScriptToExe=False ,appendScriptToLibrary=False ,copyDependentFiles=True ,targetName=name+exte ) ''' options = { 'build_exe': { 'create_shared_zip': False, 'compressed': True, 'packages': pkgs_include, 'excludes': pkgs_exclude, 'include_files': file_include, 'includes': [ 'testfreeze_1', 'testfreeze_2' ], 'path': sys.path + ['modules'] } } ''' buildOptions = dict(create_shared_zip=False ,compressed=True ,packages=pkgs_include ,excludes=pkgs_exclude ,include_files=file_include # ,namespace_packages=[name] # ,path=sys.path+['/path/more/modules'] ,build_exe=build_exe ) setupOptions = dict(name=name ,version=version ,url=url ,author=author ,author_email=author_email ,description=description ,license=license ,keywords=keywords ,executables=[executables] ,options=dict(build_exe=buildOptions) # ,packages=pkgs_include # ,include_package_data=True # ,scripts=[file_execute] # ,zip_safe=True ) _setup._setup(**setupOptions) ############################################################################### sys.exit(0)
gpl-2.0
roboogle/gtkmvc3
gtkmvco/gtkmvc3/support/utils.py
1
5390
# Author: Roberto Cavada <roboogle@gmail.com> # # Copyright (C) 2007-2015 by Roberto Cavada # # gtkmvc3 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # gtkmvc3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110, USA. # # For more information on gtkmvc3 see <https://github.com/roboogle/gtkmvc3> # or email to the author Roberto Cavada <roboogle@gmail.com>. # Please report bugs to <https://github.com/roboogle/gtkmvc3/issues> # or to <roboogle@gmail.com>. import inspect import os import types def getmembers(_object, _predicate): """This is an implementation of inspect.getmembers, as in some versions of python it may be buggy. See issue at http://bugs.python.org/issue1785""" # This should be: #return inspect.getmembers(_object, _predicate) # ... and it is re-implemented as: observers = [] for key in dir(_object): try: m = getattr(_object, key) except AttributeError: continue if _predicate(m): observers.append((key, m)) pass return observers def cast_value(val, totype): """ Take a value and return it in a different type. If not possible raise :exc:`TypeError`. *val* an arbitrary object. *totype* a class, e.g. :class:`str`. .. note:: Casting the empty string to a numeric type returns zero. """ t = type(val) if issubclass(t, totype): return val # no cast needed if issubclass(totype, bytes): return bytes(val) if issubclass(totype, str): return str(val) if issubclass(totype, bool): if issubclass(t, str): _v = val.lower() if _v in ("true", "yes", "y"): return True if _v in ("false", "no", "n"): return False raise TypeError("Not able to cast value: " + str(val) + " with " + str(t) + " to " + str(totype)) if (issubclass(totype, (int, float)) and issubclass(t, (bytes, str, int, float))): if val: return totype(float(val)) else: return totype(0) raise TypeError("Not able to cast value:" + str(val) + " with " + str(t) + " to " + str(totype)) # ====================================================================== # This is taken from python 2.6 (os.path.relpath is supported in 2.6) # # Copyright (c) 2001 Python Software Foundation; All Rights Reserved # This code about relpath is covered by the Python Software Foundation # (PSF) Agreement. See http://docs.python.org/license.html for details. # ====================================================================== def __posix_relpath(path, start=os.curdir): """Return a relative version of a path""" if not path: raise ValueError("no path specified") start_list = os.path.abspath(start).split(os.sep) path_list = os.path.abspath(path).split(os.sep) # Work out how much of the filepath is shared by start and path. i = len(os.path.commonprefix([start_list, path_list])) rel_list = [os.pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return os.curdir return os.path.join(*rel_list) # This is taken from python 2.6 (os.path.relpath is supported in 2.6) # This is for windows def __nt_relpath(path, start=os.curdir): """Return a relative version of a path""" if not path: raise ValueError("no path specified") start_list = os.path.abspath(start).split(os.sep) path_list = os.path.abspath(path).split(os.sep) if start_list[0].lower() != path_list[0].lower(): unc_path, rest = os.path.splitunc(path) unc_start, rest = os.path.splitunc(start) if bool(unc_path) ^ bool(unc_start): raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)" \ % (path, start)) else: raise ValueError("path is on drive %s, start on drive %s" \ % (path_list[0], start_list[0])) # Work out how much of the filepath is shared by start and path. for i in range(min(len(start_list), len(path_list))): if start_list[i].lower() != path_list[i].lower(): break else: i += 1 pass rel_list = [os.pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return os.curdir return os.path.join(*rel_list) try: import os.path.relpath relpath = os.path.relpath except ImportError: if os.name == 'nt': relpath = __nt_relpath else: relpath = __posix_relpath pass pass # ====================================================================== # End of code covered by PSF License Agreement # ======================================================================
lgpl-2.1
firmlyjin/brython
www/gallery/sudoku.py
16
1493
# Boris Borcic 2006 # Quick and concise Python 2.5 sudoku solver # # Adapted for Brython by Pierre Quentel # load pre-computed tables import json data = json.loads(open('sudoku.json').read()) w2q = data['w2q'] q2w = data['q2w'] w2q2w = data['w2q2w'] class Completed(Exception) : pass def sudoku99(problem) : givens = list(9*j+int(k)-1 for j,k in enumerate(problem[:81]) if '0'<k) try : search(givens,[9]*len(q2w),set(),set()) except Completed as ws : return ''.join(str(w%9+1) for w in sorted(ws.args[0])) def search(w0s,q2nw,takens,ws) : while 1 : i = 0 while w0s: w0 = w0s.pop() takens.add(w0) ws.add(w0) for q in w2q[w0] : q2nw[q]+=100 for w in set(w2q2w[w0]) - takens : takens.add(w) for q in w2q[w] : n = q2nw[q] = q2nw[q]-1 if n<2 : w0s.append((set(q2w[q])-takens).pop()) if len(ws)>80 : raise Completed(ws) w1,w0 = set(q2w[q2nw.index(2)])-takens try : search([w1],q2nw[:],takens.copy(),ws.copy()) except KeyError : w0s.append(w0) if __name__=='__main__': #print(sudoku99('530070000600195000098000060800060003400803001700020006060000280000419005000080079')) data = '004050003'+'906400000'+'130006000'+'020310000'+'090000080'+'000047050'+\ '000070038'+'000002709'+'600090100' print(sudoku99(data))
bsd-3-clause
teriyakichild/ansible-modules-extras
cloud/cloudstack/cs_network.py
33
17539
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2015, René Moser <mail@renemoser.net> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' --- module: cs_network short_description: Manages networks on Apache CloudStack based clouds. description: - Create, update, restart and delete networks. version_added: '2.0' author: "René Moser (@resmo)" options: name: description: - Name (case sensitive) of the network. required: true display_text: description: - Display text of the network. - If not specified, C(name) will be used as C(display_text). required: false default: null network_offering: description: - Name of the offering for the network. - Required if C(state=present). required: false default: null start_ip: description: - The beginning IPv4 address of the network belongs to. - Only considered on create. required: false default: null end_ip: description: - The ending IPv4 address of the network belongs to. - If not specified, value of C(start_ip) is used. - Only considered on create. required: false default: null gateway: description: - The gateway of the network. - Required for shared networks and isolated networks when it belongs to VPC. - Only considered on create. required: false default: null netmask: description: - The netmask of the network. - Required for shared networks and isolated networks when it belongs to VPC. - Only considered on create. required: false default: null start_ipv6: description: - The beginning IPv6 address of the network belongs to. - Only considered on create. required: false default: null end_ipv6: description: - The ending IPv6 address of the network belongs to. - If not specified, value of C(start_ipv6) is used. - Only considered on create. required: false default: null cidr_ipv6: description: - CIDR of IPv6 network, must be at least /64. - Only considered on create. required: false default: null gateway_ipv6: description: - The gateway of the IPv6 network. - Required for shared networks. - Only considered on create. required: false default: null vlan: description: - The ID or VID of the network. required: false default: null vpc: description: - The ID or VID of the network. required: false default: null isolated_pvlan: description: - The isolated private vlan for this network. required: false default: null clean_up: description: - Cleanup old network elements. - Only considered on C(state=restarted). required: false default: false acl_type: description: - Access control type. - Only considered on create. required: false default: account choices: [ 'account', 'domain' ] network_domain: description: - The network domain. required: false default: null state: description: - State of the network. required: false default: present choices: [ 'present', 'absent', 'restarted' ] zone: description: - Name of the zone in which the network should be deployed. - If not set, default zone is used. required: false default: null project: description: - Name of the project the network to be deployed in. required: false default: null domain: description: - Domain the network is related to. required: false default: null account: description: - Account the network is related to. required: false default: null poll_async: description: - Poll async jobs until job has finished. required: false default: true extends_documentation_fragment: cloudstack ''' EXAMPLES = ''' # create a network - local_action: module: cs_network name: my network zone: gva-01 network_offering: DefaultIsolatedNetworkOfferingWithSourceNatService network_domain: example.com # update a network - local_action: module: cs_network name: my network display_text: network of domain example.local network_domain: example.local # restart a network with clean up - local_action: module: cs_network name: my network clean_up: yes state: restared # remove a network - local_action: module: cs_network name: my network state: absent ''' RETURN = ''' --- id: description: UUID of the network. returned: success type: string sample: 04589590-ac63-4ffc-93f5-b698b8ac38b6 name: description: Name of the network. returned: success type: string sample: web project display_text: description: Display text of the network. returned: success type: string sample: web project dns1: description: IP address of the 1st nameserver. returned: success type: string sample: 1.2.3.4 dns2: description: IP address of the 2nd nameserver. returned: success type: string sample: 1.2.3.4 cidr: description: IPv4 network CIDR. returned: success type: string sample: 10.101.64.0/24 gateway: description: IPv4 gateway. returned: success type: string sample: 10.101.64.1 netmask: description: IPv4 netmask. returned: success type: string sample: 255.255.255.0 cidr_ipv6: description: IPv6 network CIDR. returned: success type: string sample: 2001:db8::/64 gateway_ipv6: description: IPv6 gateway. returned: success type: string sample: 2001:db8::1 state: description: State of the network. returned: success type: string sample: Implemented zone: description: Name of zone. returned: success type: string sample: ch-gva-2 domain: description: Domain the network is related to. returned: success type: string sample: ROOT account: description: Account the network is related to. returned: success type: string sample: example account project: description: Name of project. returned: success type: string sample: Production tags: description: List of resource tags associated with the network. returned: success type: dict sample: '[ { "key": "foo", "value": "bar" } ]' acl_type: description: Access type of the network (Domain, Account). returned: success type: string sample: Account broadcast_domain_type: description: Broadcast domain type of the network. returned: success type: string sample: Vlan type: description: Type of the network. returned: success type: string sample: Isolated traffic_type: description: Traffic type of the network. returned: success type: string sample: Guest state: description: State of the network (Allocated, Implemented, Setup). returned: success type: string sample: Allocated is_persistent: description: Whether the network is persistent or not. returned: success type: boolean sample: false network_domain: description: The network domain returned: success type: string sample: example.local network_offering: description: The network offering name. returned: success type: string sample: DefaultIsolatedNetworkOfferingWithSourceNatService ''' try: from cs import CloudStack, CloudStackException, read_config has_lib_cs = True except ImportError: has_lib_cs = False # import cloudstack common from ansible.module_utils.cloudstack import * class AnsibleCloudStackNetwork(AnsibleCloudStack): def __init__(self, module): super(AnsibleCloudStackNetwork, self).__init__(module) self.returns = { 'networkdomain': 'network domain', 'networkofferingname': 'network_offering', 'ispersistent': 'is_persistent', 'acltype': 'acl_type', 'type': 'type', 'traffictype': 'traffic_type', 'ip6gateway': 'gateway_ipv6', 'ip6cidr': 'cidr_ipv6', 'gateway': 'gateway', 'cidr': 'cidr', 'netmask': 'netmask', 'broadcastdomaintype': 'broadcast_domain_type', 'dns1': 'dns1', 'dns2': 'dns2', } self.network = None def get_vpc(self, key=None): vpc = self.module.params.get('vpc') if not vpc: return None args = {} args['account'] = self.get_account(key='name') args['domainid'] = self.get_domain(key='id') args['projectid'] = self.get_project(key='id') args['zoneid'] = self.get_zone(key='id') vpcs = self.cs.listVPCs(**args) if vpcs: for v in vpcs['vpc']: if vpc in [ v['name'], v['displaytext'], v['id'] ]: return self._get_by_key(key, v) self.module.fail_json(msg="VPC '%s' not found" % vpc) def get_network_offering(self, key=None): network_offering = self.module.params.get('network_offering') if not network_offering: self.module.fail_json(msg="missing required arguments: network_offering") args = {} args['zoneid'] = self.get_zone(key='id') network_offerings = self.cs.listNetworkOfferings(**args) if network_offerings: for no in network_offerings['networkoffering']: if network_offering in [ no['name'], no['displaytext'], no['id'] ]: return self._get_by_key(key, no) self.module.fail_json(msg="Network offering '%s' not found" % network_offering) def _get_args(self): args = {} args['name'] = self.module.params.get('name') args['displaytext'] = self.get_or_fallback('display_text', 'name') args['networkdomain'] = self.module.params.get('network_domain') args['networkofferingid'] = self.get_network_offering(key='id') return args def get_network(self): if not self.network: network = self.module.params.get('name') args = {} args['zoneid'] = self.get_zone(key='id') args['projectid'] = self.get_project(key='id') args['account'] = self.get_account(key='name') args['domainid'] = self.get_domain(key='id') networks = self.cs.listNetworks(**args) if networks: for n in networks['network']: if network in [ n['name'], n['displaytext'], n['id']]: self.network = n break return self.network def present_network(self): network = self.get_network() if not network: network = self.create_network(network) else: network = self.update_network(network) return network def update_network(self, network): args = self._get_args() args['id'] = network['id'] if self._has_changed(args, network): self.result['changed'] = True if not self.module.check_mode: network = self.cs.updateNetwork(**args) if 'errortext' in network: self.module.fail_json(msg="Failed: '%s'" % network['errortext']) poll_async = self.module.params.get('poll_async') if network and poll_async: network = self._poll_job(network, 'network') return network def create_network(self, network): self.result['changed'] = True args = self._get_args() args['acltype'] = self.module.params.get('acl_type') args['zoneid'] = self.get_zone(key='id') args['projectid'] = self.get_project(key='id') args['account'] = self.get_account(key='name') args['domainid'] = self.get_domain(key='id') args['startip'] = self.module.params.get('start_ip') args['endip'] = self.get_or_fallback('end_ip', 'start_ip') args['netmask'] = self.module.params.get('netmask') args['gateway'] = self.module.params.get('gateway') args['startipv6'] = self.module.params.get('start_ipv6') args['endipv6'] = self.get_or_fallback('end_ipv6', 'start_ipv6') args['ip6cidr'] = self.module.params.get('cidr_ipv6') args['ip6gateway'] = self.module.params.get('gateway_ipv6') args['vlan'] = self.module.params.get('vlan') args['isolatedpvlan'] = self.module.params.get('isolated_pvlan') args['subdomainaccess'] = self.module.params.get('subdomain_access') args['vpcid'] = self.get_vpc(key='id') if not self.module.check_mode: res = self.cs.createNetwork(**args) if 'errortext' in res: self.module.fail_json(msg="Failed: '%s'" % res['errortext']) network = res['network'] return network def restart_network(self): network = self.get_network() if not network: self.module.fail_json(msg="No network named '%s' found." % self.module.params('name')) # Restarting only available for these states if network['state'].lower() in [ 'implemented', 'setup' ]: self.result['changed'] = True args = {} args['id'] = network['id'] args['cleanup'] = self.module.params.get('clean_up') if not self.module.check_mode: network = self.cs.restartNetwork(**args) if 'errortext' in network: self.module.fail_json(msg="Failed: '%s'" % network['errortext']) poll_async = self.module.params.get('poll_async') if network and poll_async: network = self._poll_job(network, 'network') return network def absent_network(self): network = self.get_network() if network: self.result['changed'] = True args = {} args['id'] = network['id'] if not self.module.check_mode: res = self.cs.deleteNetwork(**args) if 'errortext' in res: self.module.fail_json(msg="Failed: '%s'" % res['errortext']) poll_async = self.module.params.get('poll_async') if res and poll_async: res = self._poll_job(res, 'network') return network def main(): argument_spec = cs_argument_spec() argument_spec.update(dict( name = dict(required=True), display_text = dict(default=None), network_offering = dict(default=None), zone = dict(default=None), start_ip = dict(default=None), end_ip = dict(default=None), gateway = dict(default=None), netmask = dict(default=None), start_ipv6 = dict(default=None), end_ipv6 = dict(default=None), cidr_ipv6 = dict(default=None), gateway_ipv6 = dict(default=None), vlan = dict(default=None), vpc = dict(default=None), isolated_pvlan = dict(default=None), clean_up = dict(type='bool', default=False), network_domain = dict(default=None), state = dict(choices=['present', 'absent', 'restarted' ], default='present'), acl_type = dict(choices=['account', 'domain'], default='account'), project = dict(default=None), domain = dict(default=None), account = dict(default=None), poll_async = dict(type='bool', default=True), )) required_together = cs_required_together() required_together.extend([ ['start_ip', 'netmask', 'gateway'], ['start_ipv6', 'cidr_ipv6', 'gateway_ipv6'], ]) module = AnsibleModule( argument_spec=argument_spec, required_together=required_together, supports_check_mode=True ) if not has_lib_cs: module.fail_json(msg="python library cs required: pip install cs") try: acs_network = AnsibleCloudStackNetwork(module) state = module.params.get('state') if state in ['absent']: network = acs_network.absent_network() elif state in ['restarted']: network = acs_network.restart_network() else: network = acs_network.present_network() result = acs_network.get_result(network) except CloudStackException as e: module.fail_json(msg='CloudStackException: %s' % str(e)) module.exit_json(**result) # import module snippets from ansible.module_utils.basic import * if __name__ == '__main__': main()
gpl-3.0
alexgibson/bedrock
lib/fluent_migrations/firefox/new.py
6
12542
from __future__ import absolute_import import fluent.syntax.ast as FTL from fluent.migrate.helpers import transforms_from from fluent.migrate.helpers import VARIABLE_REFERENCE, TERM_REFERENCE from fluent.migrate import REPLACE, COPY trailhead = "firefox/new/trailhead.lang" def migrate(ctx): """Migrate bedrock/firefox/templates/firefox/new/trailhead/base.html, part {index}.""" ctx.add_transforms( "firefox/new/download.ftl", "firefox/new/download.ftl", [ FTL.Message( id=FTL.Identifier("firefox-new-download-firefox"), value=REPLACE( "firefox/new/trailhead.lang", "Download Firefox", { "Firefox": TERM_REFERENCE("brand-name-firefox"), } ) ), FTL.Message( id=FTL.Identifier("firefox-new-download-mozilla-firefox"), value=REPLACE( "firefox/new/trailhead.lang", "Download Mozilla Firefox, a free Web browser. Firefox is created by a global non-profit dedicated to putting individuals in control online. Get Firefox for Windows, macOS, Linux, Android and iOS today!", { "Mozilla": TERM_REFERENCE("brand-name-mozilla"), "Firefox": TERM_REFERENCE("brand-name-firefox"), "Windows": TERM_REFERENCE("brand-name-windows"), "macOS": TERM_REFERENCE("brand-name-mac"), "Linux": TERM_REFERENCE("brand-name-linux"), "Android": TERM_REFERENCE("brand-name-android"), "iOS": TERM_REFERENCE("brand-name-ios"), } ) ), FTL.Message( id=FTL.Identifier("firefox-new-download-the-fastest-firefox"), value=REPLACE( "firefox/new/trailhead.lang", "Download the fastest Firefox ever", { "Firefox": TERM_REFERENCE("brand-name-firefox"), } ) ), FTL.Message( id=FTL.Identifier("firefox-new-faster-page-loading-less-memory"), value=REPLACE( "firefox/new/trailhead.lang", "Faster page loading, less memory usage and packed with features, the new Firefox is here.", { "Firefox": TERM_REFERENCE("brand-name-firefox"), } ) ), FTL.Message( id=FTL.Identifier("firefox-new-automatic-privacy-is-here"), value=REPLACE( "firefox/new/trailhead.lang", "Automatic privacy is here. Download Firefox to block over 2000 trackers.", { "Firefox": TERM_REFERENCE("brand-name-firefox"), } ) ), FTL.Message( id=FTL.Identifier("firefox-new-get-the-latest-firefox"), value=REPLACE( "firefox/new/trailhead.lang", "Get the latest Firefox browser.", { "Firefox": TERM_REFERENCE("brand-name-firefox"), } ) ), FTL.Message( id=FTL.Identifier("firefox-new-firefox-shows-you-how-many"), value=REPLACE( "firefox/new/trailhead.lang", "Firefox shows you how many data-collecting trackers are blocked with <strong>Enhanced Tracking Protection</strong>.", { "Firefox": TERM_REFERENCE("brand-name-firefox"), } ) ), FTL.Message( id=FTL.Identifier("firefox-new-firefox-lockwise-makes-secure"), value=REPLACE( "firefox/new/trailhead.lang", "<strong>Firefox Lockwise</strong> makes the passwords you save in Firefox secure and available on all your devices.", { "Firefox": TERM_REFERENCE("brand-name-firefox"), "Firefox Lockwise": TERM_REFERENCE("brand-name-firefox-lockwise"), } ) ), FTL.Message( id=FTL.Identifier("firefox-new-firefox-monitor-alerts"), value=REPLACE( "firefox/new/trailhead.lang", "<strong>Firefox Monitor</strong> alerts you if we know your information is a part of another company’s data breach.", { "Firefox Monitor": TERM_REFERENCE("brand-name-firefox-monitor"), } ) ), FTL.Message( id=FTL.Identifier("firefox-new-join-firefox"), value=REPLACE( "firefox/new/trailhead.lang", "Join Firefox", { "Firefox": TERM_REFERENCE("brand-name-firefox"), } ) ), FTL.Message( id=FTL.Identifier("firefox-new-firefox-lockwise-makes"), value=REPLACE( "firefox/new/trailhead.lang", "<strong>Firefox Lockwise</strong> makes the passwords you save in Firefox available on all your devices.", { "Firefox": TERM_REFERENCE("brand-name-firefox"), "Firefox Lockwise": TERM_REFERENCE("brand-name-firefox-lockwise"), } ) ), FTL.Message( id=FTL.Identifier("firefox-new-download-firefox-for-windows"), value=REPLACE( "firefox/new/trailhead.lang", "Download Firefox <br>for Windows", { "Firefox": TERM_REFERENCE("brand-name-firefox"), "Windows": TERM_REFERENCE("brand-name-windows"), } ) ), FTL.Message( id=FTL.Identifier("firefox-new-download-firefox-for-macos"), value=REPLACE( "firefox/new/trailhead.lang", "Download Firefox <br>for macOS", { "Firefox": TERM_REFERENCE("brand-name-firefox"), "macOS": TERM_REFERENCE("brand-name-mac"), } ) ), FTL.Message( id=FTL.Identifier("firefox-new-download-firefox-for-linux"), value=REPLACE( "firefox/new/trailhead.lang", "Download Firefox <br>for Linux", { "Firefox": TERM_REFERENCE("brand-name-firefox"), "Linux": TERM_REFERENCE("brand-name-linux"), } ) ), FTL.Message( id=FTL.Identifier("firefox-new-youve-already-got-the-browser"), value=REPLACE( "firefox/new/trailhead.lang", "You’ve already got the browser. Now get even more from Firefox.", { "Firefox": TERM_REFERENCE("brand-name-firefox"), } ) ), FTL.Message( id=FTL.Identifier("firefox-new-watch-for-hackers-with"), value=REPLACE( "firefox/new/trailhead.lang", "Watch for hackers with Firefox Monitor, protect passwords with Firefox Lockwise, and more.", { "Firefox Monitor": TERM_REFERENCE("brand-name-firefox-monitor"), "Firefox Lockwise": TERM_REFERENCE("brand-name-firefox-lockwise"), } ) ), FTL.Message( id=FTL.Identifier("firefox-new-get-more-from-firefox"), value=REPLACE( "firefox/new/trailhead.lang", "Get More From Firefox", { "Firefox": TERM_REFERENCE("brand-name-firefox"), } ) ), ] ) ctx.add_transforms( "firefox/new/download.ftl", "firefox/new/download.ftl", transforms_from(""" firefox-new-free-web-browser = {COPY(trailhead, "Free Web Browser",)} firefox-new-and-start-getting-the-respect = {COPY(trailhead, "And start getting the respect you deserve with our family of privacy-first products.",)} firefox-new-advanced-install-options = {COPY(trailhead, "Advanced install options & other platforms",)} firefox-new-download-in-another-language = {COPY(trailhead, "Download in another language",)} firefox-new-fix-a-problem = {COPY(trailhead, "Fix a problem",)} firefox-new-need-help = {COPY(trailhead, "Need help?",)} firefox-new-see-whats-being-blocked = {COPY(trailhead, "See what’s being blocked",)} firefox-new-make-your-passwords-portable = {COPY(trailhead, "Make your passwords portable",)} firefox-new-watch-for-data-breaches = {COPY(trailhead, "Watch for data breaches",)} firefox-new-connect-to-a-whole-family = {COPY(trailhead, "Connect to a whole family of respectful products, plus all the knowledge you need to protect yourself online.",)} firefox-new-passwords-made-portable = {COPY(trailhead, "Passwords made portable",)} firefox-new-protect-your-privacy = {COPY(trailhead, "Protect your privacy",)} firefox-new-private-browsing-clears = {COPY(trailhead, "<strong>Private Browsing</strong> clears your history to keep it secret from anyone who uses your computer.",)} firefox-new-advanced-install-options-heading = {COPY(trailhead, "Advanced Install Options & Other Platforms",)} firefox-new-just-download-the-browser = {COPY(trailhead, "Just Download The Browser",)} """, trailhead=trailhead) ) ctx.add_transforms( "firefox/new/download.ftl", "firefox/new/download.ftl", [ FTL.Message( id=FTL.Identifier("firefox-new-youre-using-an-insecure-outdated"), value=REPLACE( trailhead, "You’re using an insecure, outdated operating system <a href=\"%(url)s\">no longer supported by Firefox</a>.", { "%%": "%", "%(url)s": VARIABLE_REFERENCE("url"), "Firefox": TERM_REFERENCE("brand-name-firefox"), } ) ), FTL.Message( id=FTL.Identifier("firefox-new-your-firefox-new-should-begin"), value=REPLACE( trailhead, "Your download should begin automatically. Didn’t work? <a id=\"%(id)s\" href=\"%(fallback_url)s\">Try downloading again</a>.", { "%%": "%", "%(id)s": VARIABLE_REFERENCE("id"), "%(fallback_url)s": VARIABLE_REFERENCE("fallback_url"), } ) ), FTL.Message( id=FTL.Identifier("firefox-new-firefox-is-more-than-a-browser"), value=REPLACE( trailhead, "Firefox is more than a browser.", { "Firefox": TERM_REFERENCE("brand-name-firefox"), } ) ), ] + transforms_from(""" firefox-new-its-privacy-and-peace-of = {COPY(trailhead, "It’s <strong>privacy and peace of mind</strong> on mobile, too.",)} firefox-new-its-a-family-of-products = {COPY(trailhead, "It’s a <strong>family of products</strong> that treat your personal data with respect.",)} firefox-new-its-everything-you-need-to = {COPY(trailhead, "It’s everything you need to know about <strong>staying safe online</strong>.",)} firefox-new-its-a-community-that-believes = {COPY(trailhead, "It’s <strong>a community</strong> that believes tech can do better.",)} """, trailhead=trailhead) )
mpl-2.0
sdague/home-assistant
homeassistant/components/aqualogic/sensor.py
9
3466
"""Support for AquaLogic sensors.""" import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_MONITORED_CONDITIONS, PERCENTAGE, POWER_WATT, TEMP_CELSIUS, TEMP_FAHRENHEIT, ) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from . import DOMAIN, UPDATE_TOPIC TEMP_UNITS = [TEMP_CELSIUS, TEMP_FAHRENHEIT] PERCENT_UNITS = [PERCENTAGE, PERCENTAGE] SALT_UNITS = ["g/L", "PPM"] WATT_UNITS = [POWER_WATT, POWER_WATT] NO_UNITS = [None, None] # sensor_type [ description, unit, icon ] # sensor_type corresponds to property names in aqualogic.core.AquaLogic SENSOR_TYPES = { "air_temp": ["Air Temperature", TEMP_UNITS, "mdi:thermometer"], "pool_temp": ["Pool Temperature", TEMP_UNITS, "mdi:oil-temperature"], "spa_temp": ["Spa Temperature", TEMP_UNITS, "mdi:oil-temperature"], "pool_chlorinator": ["Pool Chlorinator", PERCENT_UNITS, "mdi:gauge"], "spa_chlorinator": ["Spa Chlorinator", PERCENT_UNITS, "mdi:gauge"], "salt_level": ["Salt Level", SALT_UNITS, "mdi:gauge"], "pump_speed": ["Pump Speed", PERCENT_UNITS, "mdi:speedometer"], "pump_power": ["Pump Power", WATT_UNITS, "mdi:gauge"], "status": ["Status", NO_UNITS, "mdi:alert"], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MONITORED_CONDITIONS, default=list(SENSOR_TYPES)): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ) } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the sensor platform.""" sensors = [] processor = hass.data[DOMAIN] for sensor_type in config[CONF_MONITORED_CONDITIONS]: sensors.append(AquaLogicSensor(processor, sensor_type)) async_add_entities(sensors) class AquaLogicSensor(Entity): """Sensor implementation for the AquaLogic component.""" def __init__(self, processor, sensor_type): """Initialize sensor.""" self._processor = processor self._type = sensor_type self._state = None @property def state(self): """Return the state of the sensor.""" return self._state @property def name(self): """Return the name of the sensor.""" return f"AquaLogic {SENSOR_TYPES[self._type][0]}" @property def unit_of_measurement(self): """Return the unit of measurement the value is expressed in.""" panel = self._processor.panel if panel is None: return None if panel.is_metric: return SENSOR_TYPES[self._type][1][0] return SENSOR_TYPES[self._type][1][1] @property def should_poll(self): """Return the polling state.""" return False @property def icon(self): """Icon to use in the frontend, if any.""" return SENSOR_TYPES[self._type][2] async def async_added_to_hass(self): """Register callbacks.""" self.async_on_remove( self.hass.helpers.dispatcher.async_dispatcher_connect( UPDATE_TOPIC, self.async_update_callback ) ) @callback def async_update_callback(self): """Update callback.""" panel = self._processor.panel if panel is not None: self._state = getattr(panel, self._type) self.async_write_ha_state()
apache-2.0
turon/openthread
tests/scripts/thread-cert/test_coaps.py
1
3715
#!/usr/bin/env python # # Copyright (c) 2018, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # import unittest import config import node LEADER = 1 ROUTER = 2 class TestCoaps(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} for i in range(1, 3): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) self.nodes[LEADER].set_mode('rsdn') self.nodes[LEADER].add_whitelist(self.nodes[ROUTER].get_addr64()) self.nodes[LEADER].enable_whitelist() self.nodes[ROUTER].set_panid(0xface) self.nodes[ROUTER].set_mode('rsdn') self.nodes[ROUTER].add_whitelist(self.nodes[LEADER].get_addr64()) self.nodes[ROUTER].enable_whitelist() self.nodes[ROUTER].set_router_selection_jitter(1) def tearDown(self): for n in list(self.nodes.values()): n.stop() n.destroy() self.simulator.stop() def test(self): self.nodes[LEADER].start() self.simulator.go(5) self.assertEqual(self.nodes[LEADER].get_state(), 'leader') self.nodes[ROUTER].start() self.simulator.go(5) self.assertEqual(self.nodes[ROUTER].get_state(), 'router') mleid = self.nodes[LEADER].get_ip6_address(config.ADDRESS_TYPE.ML_EID) self.nodes[LEADER].coaps_start_psk('psk', 'pskIdentity') self.nodes[LEADER].coaps_set_resource_path('test') self.nodes[ROUTER].coaps_start_psk('psk', 'pskIdentity') self.nodes[ROUTER].coaps_connect(mleid) self.nodes[ROUTER].coaps_get() self.nodes[ROUTER].coaps_disconnect() self.nodes[ROUTER].coaps_stop() self.nodes[LEADER].coaps_stop() self.nodes[LEADER].coaps_start_x509() # self.nodes[LEADER].coaps_set_resource_path('test') self.nodes[ROUTER].coaps_start_x509() self.nodes[ROUTER].coaps_connect(mleid) self.nodes[ROUTER].coaps_get() self.nodes[ROUTER].coaps_disconnect() self.nodes[ROUTER].coaps_stop() self.nodes[LEADER].coaps_stop() if __name__ == '__main__': unittest.main()
bsd-3-clause
Joshuaalbert/IonoTomo
src/ionotomo/tomography/model.py
1
2831
import tensorflow as tf import numpy as np from ionotomo.settings import TFSettings from ionotomo import * from ionotomo.ionosphere.iri import a_priori_model import astropy.coordinates as ac import astropy.units as au import astropy.time as at def calc_rays_and_initial_model(antennas,directions,times,zmax=1000.,res_n=201,spacing=10.,phase_center=None,array_center=None): """Create straight line rays from given antennas, directions and times. antennas : astropy.coordinates.ITRS convertible The antenna locations """ res_n = (res_n >> 1)*2 + 1 fixtime = times[0] if phase_center is None: phase_center = ac.SkyCoord(np.mean(directions.ra.deg)*au.deg, np.mean(directions.dec.deg)*au.deg,frame='icrs') if array_center is None: array_center = ac.SkyCoord(np.mean(antennas.x.to(au.m).value)*au.m, np.mean(antennas.y.to(au.m).value)*au.m, np.mean(antennas.z.to(au.m).value)*au.m,frame='itrs') rays = np.zeros((len(antennas),len(times),len(directions),3,res_n),dtype=float) factor = np.linspace(0,1,res_n)[None,None,:] for j in range(len(times)): uvw = Pointing(location = array_center.earth_location,obstime = times[j], fixtime=fixtime, phase = phase_center) ants_uvw = antennas.transform_to(uvw).cartesian.xyz.to(au.km).value.T dirs_uvw = directions.transform_to(uvw).cartesian.xyz.value.T t = factor*((zmax - ants_uvw[:,2,None,None])/dirs_uvw[None,:,2,None]) rays[:,j,:,0,:] = ants_uvw[:,0][:,None,None] + dirs_uvw[None,:,0,None]*t rays[:,j,:,1,:] = ants_uvw[:,1][:,None,None] + dirs_uvw[None,:,1,None]*t rays[:,j,:,2,:] = ants_uvw[:,2][:,None,None] + dirs_uvw[None,:,2,None]*t xmax = np.max(rays[:,:,:,0,:]) ymax = np.max(rays[:,:,:,1,:]) zmax = np.max(rays[:,:,:,2,:]) xmin = np.min(rays[:,:,:,0,:]) ymin = np.min(rays[:,:,:,1,:]) zmin = np.min(rays[:,:,:,2,:]) xvec = np.arange(xmin-spacing*3,xmax+spacing*3,spacing) yvec = np.arange(ymin-spacing*3,ymax+spacing*3,spacing) zvec = np.arange(zmin-spacing*3,zmax+spacing*3,spacing) uvw = Pointing(location = array_center.earth_location,obstime = times[0], fixtime=fixtime, phase = phase_center) X,Y,Z = np.meshgrid(xvec,yvec,zvec,indexing='ij') heights = ac.SkyCoord(X.flatten()*au.km,Y.flatten()*au.km,Z.flatten()*au.km, frame=uvw).transform_to('itrs').earth_location.to_geodetic('WGS84')[2].to(au.km).value lat = array_center.earth_location.to_geodetic('WGS84').lat.to(au.deg).value lon = array_center.earth_location.to_geodetic('WGS84').lon.to(au.deg).value ne_model = a_priori_model(heights,zmax,lat,lon,fixtime).reshape(X.shape) return rays, (xvec,yvec,zvec), ne_model
apache-2.0
DiCarloLab-Delft/PycQED_py3
pycqed/instrument_drivers/physical_instruments/SCPIBase.py
1
7440
""" File: SCPIBase.py Author: Wouter Vlothuizen, TNO/QuTech Purpose: self contained base class for SCPI ('Standard Commands for Programmable Instruments') commands, with selectable transport Usage: don't use directly, use a derived class (e.g. Qutech_CC) Notes: Bugs: Changelog: 20190213 WJV - started, based on SCPI.py """ from .Transport import Transport class SCPIBase: def __init__(self, name: str, transport: Transport) -> None: self._transport = transport ### # Helpers ### def _ask(self, cmd_str: str) -> str: self._transport.write(cmd_str) return self._transport.readline().rstrip() # remove trailing white space, CR, LF def _ask_float(self, cmd_str: str) -> float: return float(self._ask(cmd_str)) # FIXME: can raise ValueError def _ask_int(self, cmd_str: str) -> int: return int(self._ask(cmd_str)) # FIXME: can raise ValueError def _ask_bin(self, cmd_str: str) -> bytes: self._transport.write(cmd_str) return self.bin_block_read() ### # Generic SCPI commands from IEEE 488.2 (IEC 625-2) standard ### def clear_status(self) -> None: self._transport.write('*CLS') def set_event_status_enable(self, value: int) -> None: self._transport.write('*ESE %d' % value) def get_event_status_enable(self) -> str: return self._ask('*ESE?') def get_event_status_register(self) -> str: return self._ask('*ESR?') def get_identity(self) -> str: return self._ask('*IDN?') def operation_complete(self) -> None: self._transport.write('*OPC') def get_operation_complete(self) -> str: return self._ask('*OPC?') def get_options(self) -> str: return self._ask('*OPT?') def service_request_enable(self, value: int) -> None: self._transport.write('*SRE %d' % value) def get_service_request_enable(self) -> int: return self._ask_int('*SRE?') def get_status_byte(self) -> int: return self._ask_int('*STB?') def get_test_result(self) -> int: # NB: result bits are device dependent return self._ask_int('*TST?') def trigger(self) -> None: self._transport.write('*TRG') def wait(self) -> None: self._transport.write('*WAI') def reset(self) -> None: self._transport.write('*RST') ### # Required SCPI commands (SCPI std V1999.0 4.2.1) ### def get_error(self) -> str: """ Returns: '0,"No error"' or <error message> """ return self._ask('system:err?') def get_system_error_count(self) -> int: return self._ask_int('system:error:count?') def status_preset(self) -> None: self._transport.write('STATus:PRESet') def get_system_version(self) -> str: return self._ask('system:version?') def get_status_questionable_condition(self) -> int: return self._ask_int('STATus:QUEStionable:CONDition?') def get_status_questionable_event(self) -> int: return self._ask_int('STATus:QUEStionable:EVENt?') def set_status_questionable_enable(self, val) -> None: self._transport.write('STATus:QUEStionable:ENABle {}'.format(val)) def get_status_questionable_enable(self) -> int: return self._ask_int('STATus:QUEStionable:ENABle?') def get_status_operation_condition(self) -> int: return self._ask_int('STATus:OPERation:CONDition?') def get_status_operation_event(self) -> int: return self._ask_int('STATus:OPERation:EVENt?') def set_status_operation_enable(self, val) -> None: self._transport.write('STATus:OPERation:ENABle {}'.format(val)) def get_status_operation_enable(self) -> int: return self._ask_int('STATus:OPERation:ENABle?') ### # IEEE 488.2 binblock handling ### def bin_block_write(self, bin_block: bytes, cmd_str: str) -> None: """ write IEEE488.2 binblock Args: bin_block (bytearray): binary data to send cmd_str (str): command string to use """ header = cmd_str + SCPIBase._build_header_string(len(bin_block)) bin_msg = header.encode() + bin_block self._transport.write_binary(bin_msg) self._transport.write('') # add a Line Terminator def bin_block_read(self) -> bytes: """ read IEEE488.2 binblock """ # get and decode header header_a = self._transport.read_binary(2) # read '#N' header_a_str = header_a.decode() if header_a_str[0] != '#': s = 'SCPI header error: received {}'.format(header_a) raise RuntimeError(s) digit_cnt = int(header_a_str[1]) header_b = self._transport.read_binary(digit_cnt) byte_cnt = int(header_b.decode()) bin_block = self._transport.read_binary(byte_cnt) self._transport.read_binary(2) # consume <CR><LF> return bin_block ### # IEEE488.2 status constants ### # bits for *ESR and *ESE ESR_OPERATION_COMPLETE = 0x01 ESR_REQUEST_CONTROL = 0x02 ESR_QUERY_ERROR = 0x04 ESR_DEVICE_DEPENDENT_ERROR = 0x08 ESR_EXECUTION_ERROR = 0x10 ESR_COMMAND_ERROR = 0x20 ESR_USER_REQUEST = 0x40 ESR_POWER_ON = 0x80 # bits for STATus:OPERation # FIXME: add the function STAT_OPER_CALIBRATING = 0x0001 # The instrument is currently performing a calibration STAT_OPER_SETTLING = 0x0002 # The instrument is waiting for signals it controls to stabilize enough to begin measurements STAT_OPER_RANGING = 0x0004 # The instrument is currently changing its range STAT_OPER_SWEEPING = 0x0008 # A sweep is in progress STAT_OPER_MEASURING = 0x0010 # The instrument is actively measuring STAT_OPER_WAIT_TRIG = 0x0020 # The instrument is in a “wait for trigger” state of the trigger model STAT_OPER_WAIT_ARM = 0x0040 # The instrument is in a “wait for arm” state of the trigger model STAT_OPER_CORRECTING = 0x0080 # The instrument is currently performing a correction STAT_OPER_INST_SUMMARY = 0x2000 # One of n multiple logical instruments is reporting OPERational status STAT_OPER_PROG_RUNNING = 0x4000 # A user-defined program is currently in the run state # bits for STATus:QUEStionable # FIXME: add the function STAT_QUES_VOLTAGE = 0x0001 STAT_QUES_CURRENT = 0x0002 STAT_QUES_TIME = 0x0004 STAT_QUES_POWER = 0x0008 STAT_QUES_TEMPERATURE = 0x0010 STAT_QUES_FREQUENCY = 0x0020 STAT_QUES_PHASE = 0x0040 STAT_QUES_MODULATION = 0x0080 STAT_QUES_CALIBRATION = 0x0100 STAT_QUES_INST_SUMMARY = 0x2000 STAT_QUES_COMMAND_WARNING = 0x4000 ### # static methods ### @staticmethod def _build_header_string(byte_cnt: int) -> str: """ generate IEEE488.2 binblock header """ byte_cnt_str = str(byte_cnt) digit_cnt_str = str(len(byte_cnt_str)) bin_header_str = '#' + digit_cnt_str + byte_cnt_str return bin_header_str
mit
zbsz/micro-protobuf
python/google/protobuf/message.py
43
9283
# Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # http://code.google.com/p/protobuf/ # # 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. # TODO(robinson): We should just make these methods all "pure-virtual" and move # all implementation out, into reflection.py for now. """Contains an abstract base class for protocol messages.""" __author__ = 'robinson@google.com (Will Robinson)' class Error(Exception): pass class DecodeError(Error): pass class EncodeError(Error): pass class Message(object): """Abstract base class for protocol messages. Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below. TODO(robinson): Link to an HTML document here. TODO(robinson): Document that instances of this class will also have an Extensions attribute with __getitem__ and __setitem__. Again, not sure how to best convey this. TODO(robinson): Document that the class must also have a static RegisterExtension(extension_field) method. Not sure how to best express at this point. """ # TODO(robinson): Document these fields and methods. __slots__ = [] DESCRIPTOR = None def __eq__(self, other_msg): raise NotImplementedError def __ne__(self, other_msg): # Can't just say self != other_msg, since that would infinitely recurse. :) return not self == other_msg def __str__(self): raise NotImplementedError def MergeFrom(self, other_msg): """Merges the contents of the specified message into current message. This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged. Args: other_msg: Message to merge into the current message. """ raise NotImplementedError def CopyFrom(self, other_msg): """Copies the content of the specified message into the current message. The method clears the current message and then merges the specified message using MergeFrom. Args: other_msg: Message to copy into the current one. """ if self is other_msg: return self.Clear() self.MergeFrom(other_msg) def Clear(self): """Clears all data that was set in the message.""" raise NotImplementedError def SetInParent(self): """Mark this as present in the parent. This normally happens automatically when you assign a field of a sub-message, but sometimes you want to make the sub-message present while keeping it empty. If you find yourself using this, you may want to reconsider your design.""" raise NotImplementedError def IsInitialized(self): """Checks if the message is initialized. Returns: The method returns True if the message is initialized (i.e. all of its required fields are set). """ raise NotImplementedError # TODO(robinson): MergeFromString() should probably return None and be # implemented in terms of a helper that returns the # of bytes read. Our # deserialization routines would use the helper when recursively # deserializing, but the end user would almost always just want the no-return # MergeFromString(). def MergeFromString(self, serialized): """Merges serialized protocol buffer data into this message. When we find a field in |serialized| that is already present in this message: - If it's a "repeated" field, we append to the end of our list. - Else, if it's a scalar, we overwrite our field. - Else, (it's a nonrepeated composite), we recursively merge into the existing composite. TODO(robinson): Document handling of unknown fields. Args: serialized: Any object that allows us to call buffer(serialized) to access a string of bytes using the buffer interface. TODO(robinson): When we switch to a helper, this will return None. Returns: The number of bytes read from |serialized|. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we *do* stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information. """ raise NotImplementedError def ParseFromString(self, serialized): """Like MergeFromString(), except we clear the object first.""" self.Clear() self.MergeFromString(serialized) def SerializeToString(self): """Serializes the protocol message to a binary string. Returns: A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized). Raises: message.EncodeError if the message isn't initialized. """ raise NotImplementedError def SerializePartialToString(self): """Serializes the protocol message to a binary string. This method is similar to SerializeToString but doesn't check if the message is initialized. Returns: A string representation of the partial message. """ raise NotImplementedError # TODO(robinson): Decide whether we like these better # than auto-generated has_foo() and clear_foo() methods # on the instances themselves. This way is less consistent # with C++, but it makes reflection-type access easier and # reduces the number of magically autogenerated things. # # TODO(robinson): Be sure to document (and test) exactly # which field names are accepted here. Are we case-sensitive? # What do we do with fields that share names with Python keywords # like 'lambda' and 'yield'? # # nnorwitz says: # """ # Typically (in python), an underscore is appended to names that are # keywords. So they would become lambda_ or yield_. # """ def ListFields(self): """Returns a list of (FieldDescriptor, value) tuples for all fields in the message which are not empty. A singular field is non-empty if HasField() would return true, and a repeated field is non-empty if it contains at least one element. The fields are ordered by field number""" raise NotImplementedError def HasField(self, field_name): raise NotImplementedError def ClearField(self, field_name): raise NotImplementedError def HasExtension(self, extension_handle): raise NotImplementedError def ClearExtension(self, extension_handle): raise NotImplementedError def ByteSize(self): """Returns the serialized size of this message. Recursively calls ByteSize() on all contained messages. """ raise NotImplementedError def _SetListener(self, message_listener): """Internal method used by the protocol message implementation. Clients should not call this directly. Sets a listener that this message will call on certain state transitions. The purpose of this method is to register back-edges from children to parents at runtime, for the purpose of setting "has" bits and byte-size-dirty bits in the parent and ancestor objects whenever a child or descendant object is modified. If the client wants to disconnect this Message from the object tree, she explicitly sets callback to None. If message_listener is None, unregisters any existing listener. Otherwise, message_listener must implement the MessageListener interface in internal/message_listener.py, and we discard any listener registered via a previous _SetListener() call. """ raise NotImplementedError
bsd-3-clause
laiqiqi886/kbengine
kbe/src/lib/python/Tools/scripts/patchcheck.py
36
5829
#!/usr/bin/env python3 import re import sys import shutil import os.path import subprocess import sysconfig import reindent import untabify SRCDIR = sysconfig.get_config_var('srcdir') def n_files_str(count): """Return 'N file(s)' with the proper plurality on 'file'.""" return "{} file{}".format(count, "s" if count != 1 else "") def status(message, modal=False, info=None): """Decorator to output status info to stdout.""" def decorated_fxn(fxn): def call_fxn(*args, **kwargs): sys.stdout.write(message + ' ... ') sys.stdout.flush() result = fxn(*args, **kwargs) if not modal and not info: print("done") elif info: print(info(result)) else: print("yes" if result else "NO") return result return call_fxn return decorated_fxn def mq_patches_applied(): """Check if there are any applied MQ patches.""" cmd = 'hg qapplied' with subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) as st: bstdout, _ = st.communicate() return st.returncode == 0 and bstdout @status("Getting the list of files that have been added/changed", info=lambda x: n_files_str(len(x))) def changed_files(): """Get the list of changed or added files from Mercurial.""" if not os.path.isdir(os.path.join(SRCDIR, '.hg')): sys.exit('need a checkout to get modified files') cmd = 'hg status --added --modified --no-status' if mq_patches_applied(): cmd += ' --rev qparent' with subprocess.Popen(cmd.split(), stdout=subprocess.PIPE) as st: return [x.decode().rstrip() for x in st.stdout] def report_modified_files(file_paths): count = len(file_paths) if count == 0: return n_files_str(count) else: lines = ["{}:".format(n_files_str(count))] for path in file_paths: lines.append(" {}".format(path)) return "\n".join(lines) @status("Fixing whitespace", info=report_modified_files) def normalize_whitespace(file_paths): """Make sure that the whitespace for .py files have been normalized.""" reindent.makebackup = False # No need to create backups. fixed = [path for path in file_paths if path.endswith('.py') and reindent.check(os.path.join(SRCDIR, path))] return fixed @status("Fixing C file whitespace", info=report_modified_files) def normalize_c_whitespace(file_paths): """Report if any C files """ fixed = [] for path in file_paths: abspath = os.path.join(SRCDIR, path) with open(abspath, 'r') as f: if '\t' not in f.read(): continue untabify.process(abspath, 8, verbose=False) fixed.append(path) return fixed ws_re = re.compile(br'\s+(\r?\n)$') @status("Fixing docs whitespace", info=report_modified_files) def normalize_docs_whitespace(file_paths): fixed = [] for path in file_paths: abspath = os.path.join(SRCDIR, path) try: with open(abspath, 'rb') as f: lines = f.readlines() new_lines = [ws_re.sub(br'\1', line) for line in lines] if new_lines != lines: shutil.copyfile(abspath, abspath + '.bak') with open(abspath, 'wb') as f: f.writelines(new_lines) fixed.append(path) except Exception as err: print('Cannot fix %s: %s' % (path, err)) return fixed @status("Docs modified", modal=True) def docs_modified(file_paths): """Report if any file in the Doc directory has been changed.""" return bool(file_paths) @status("Misc/ACKS updated", modal=True) def credit_given(file_paths): """Check if Misc/ACKS has been changed.""" return os.path.join('Misc', 'ACKS') in file_paths @status("Misc/NEWS updated", modal=True) def reported_news(file_paths): """Check if Misc/NEWS has been changed.""" return os.path.join('Misc', 'NEWS') in file_paths @status("configure regenerated", modal=True, info=str) def regenerated_configure(file_paths): """Check if configure has been regenerated.""" if 'configure.ac' in file_paths: return "yes" if 'configure' in file_paths else "no" else: return "not needed" @status("pyconfig.h.in regenerated", modal=True, info=str) def regenerated_pyconfig_h_in(file_paths): """Check if pyconfig.h.in has been regenerated.""" if 'configure.ac' in file_paths: return "yes" if 'pyconfig.h.in' in file_paths else "no" else: return "not needed" def main(): file_paths = changed_files() python_files = [fn for fn in file_paths if fn.endswith('.py')] c_files = [fn for fn in file_paths if fn.endswith(('.c', '.h'))] doc_files = [fn for fn in file_paths if fn.startswith('Doc')] misc_files = {os.path.join('Misc', 'ACKS'), os.path.join('Misc', 'NEWS')}\ & set(file_paths) # PEP 8 whitespace rules enforcement. normalize_whitespace(python_files) # C rules enforcement. normalize_c_whitespace(c_files) # Doc whitespace enforcement. normalize_docs_whitespace(doc_files) # Docs updated. docs_modified(doc_files) # Misc/ACKS changed. credit_given(misc_files) # Misc/NEWS changed. reported_news(misc_files) # Regenerated configure, if necessary. regenerated_configure(file_paths) # Regenerated pyconfig.h.in, if necessary. regenerated_pyconfig_h_in(file_paths) # Test suite run and passed. if python_files or c_files: end = " and check for refleaks?" if c_files else "?" print() print("Did you run the test suite" + end) if __name__ == '__main__': main()
lgpl-3.0
pratikmallya/hue
desktop/core/ext-py/Babel-0.9.6/babel/messages/frontend.py
67
51292
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2007 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://babel.edgewall.org/wiki/License. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://babel.edgewall.org/log/. """Frontends for the message extraction functionality.""" from ConfigParser import RawConfigParser from datetime import datetime from distutils import log from distutils.cmd import Command from distutils.errors import DistutilsOptionError, DistutilsSetupError from locale import getpreferredencoding import logging from optparse import OptionParser import os import re import shutil from StringIO import StringIO import sys import tempfile from babel import __version__ as VERSION from babel import Locale, localedata from babel.core import UnknownLocaleError from babel.messages.catalog import Catalog from babel.messages.extract import extract_from_dir, DEFAULT_KEYWORDS, \ DEFAULT_MAPPING from babel.messages.mofile import write_mo from babel.messages.pofile import read_po, write_po from babel.messages.plurals import PLURALS from babel.util import odict, LOCALTZ __all__ = ['CommandLineInterface', 'compile_catalog', 'extract_messages', 'init_catalog', 'check_message_extractors', 'update_catalog'] __docformat__ = 'restructuredtext en' class compile_catalog(Command): """Catalog compilation command for use in ``setup.py`` scripts. If correctly installed, this command is available to Setuptools-using setup scripts automatically. For projects using plain old ``distutils``, the command needs to be registered explicitly in ``setup.py``:: from babel.messages.frontend import compile_catalog setup( ... cmdclass = {'compile_catalog': compile_catalog} ) :since: version 0.9 :see: `Integrating new distutils commands <http://docs.python.org/dist/node32.html>`_ :see: `setuptools <http://peak.telecommunity.com/DevCenter/setuptools>`_ """ description = 'compile message catalogs to binary MO files' user_options = [ ('domain=', 'D', "domain of PO file (default 'messages')"), ('directory=', 'd', 'path to base directory containing the catalogs'), ('input-file=', 'i', 'name of the input file'), ('output-file=', 'o', "name of the output file (default " "'<output_dir>/<locale>/LC_MESSAGES/<domain>.po')"), ('locale=', 'l', 'locale of the catalog to compile'), ('use-fuzzy', 'f', 'also include fuzzy translations'), ('statistics', None, 'print statistics about translations') ] boolean_options = ['use-fuzzy', 'statistics'] def initialize_options(self): self.domain = 'messages' self.directory = None self.input_file = None self.output_file = None self.locale = None self.use_fuzzy = False self.statistics = False def finalize_options(self): if not self.input_file and not self.directory: raise DistutilsOptionError('you must specify either the input file ' 'or the base directory') if not self.output_file and not self.directory: raise DistutilsOptionError('you must specify either the input file ' 'or the base directory') def run(self): po_files = [] mo_files = [] if not self.input_file: if self.locale: po_files.append((self.locale, os.path.join(self.directory, self.locale, 'LC_MESSAGES', self.domain + '.po'))) mo_files.append(os.path.join(self.directory, self.locale, 'LC_MESSAGES', self.domain + '.mo')) else: for locale in os.listdir(self.directory): po_file = os.path.join(self.directory, locale, 'LC_MESSAGES', self.domain + '.po') if os.path.exists(po_file): po_files.append((locale, po_file)) mo_files.append(os.path.join(self.directory, locale, 'LC_MESSAGES', self.domain + '.mo')) else: po_files.append((self.locale, self.input_file)) if self.output_file: mo_files.append(self.output_file) else: mo_files.append(os.path.join(self.directory, self.locale, 'LC_MESSAGES', self.domain + '.mo')) if not po_files: raise DistutilsOptionError('no message catalogs found') for idx, (locale, po_file) in enumerate(po_files): mo_file = mo_files[idx] infile = open(po_file, 'r') try: catalog = read_po(infile, locale) finally: infile.close() if self.statistics: translated = 0 for message in list(catalog)[1:]: if message.string: translated +=1 percentage = 0 if len(catalog): percentage = translated * 100 // len(catalog) log.info('%d of %d messages (%d%%) translated in %r', translated, len(catalog), percentage, po_file) if catalog.fuzzy and not self.use_fuzzy: log.warn('catalog %r is marked as fuzzy, skipping', po_file) continue for message, errors in catalog.check(): for error in errors: log.error('error: %s:%d: %s', po_file, message.lineno, error) log.info('compiling catalog %r to %r', po_file, mo_file) outfile = open(mo_file, 'wb') try: write_mo(outfile, catalog, use_fuzzy=self.use_fuzzy) finally: outfile.close() class extract_messages(Command): """Message extraction command for use in ``setup.py`` scripts. If correctly installed, this command is available to Setuptools-using setup scripts automatically. For projects using plain old ``distutils``, the command needs to be registered explicitly in ``setup.py``:: from babel.messages.frontend import extract_messages setup( ... cmdclass = {'extract_messages': extract_messages} ) :see: `Integrating new distutils commands <http://docs.python.org/dist/node32.html>`_ :see: `setuptools <http://peak.telecommunity.com/DevCenter/setuptools>`_ """ description = 'extract localizable strings from the project code' user_options = [ ('charset=', None, 'charset to use in the output file'), ('keywords=', 'k', 'space-separated list of keywords to look for in addition to the ' 'defaults'), ('no-default-keywords', None, 'do not include the default keywords'), ('mapping-file=', 'F', 'path to the mapping configuration file'), ('no-location', None, 'do not include location comments with filename and line number'), ('omit-header', None, 'do not include msgid "" entry in header'), ('output-file=', 'o', 'name of the output file'), ('width=', 'w', 'set output line width (default 76)'), ('no-wrap', None, 'do not break long message lines, longer than the output line width, ' 'into several lines'), ('sort-output', None, 'generate sorted output (default False)'), ('sort-by-file', None, 'sort output by file location (default False)'), ('msgid-bugs-address=', None, 'set report address for msgid'), ('copyright-holder=', None, 'set copyright holder in output'), ('add-comments=', 'c', 'place comment block with TAG (or those preceding keyword lines) in ' 'output file. Seperate multiple TAGs with commas(,)'), ('strip-comments', None, 'strip the comment TAGs from the comments.'), ('input-dirs=', None, 'directories that should be scanned for messages'), ] boolean_options = [ 'no-default-keywords', 'no-location', 'omit-header', 'no-wrap', 'sort-output', 'sort-by-file', 'strip-comments' ] def initialize_options(self): self.charset = 'utf-8' self.keywords = '' self._keywords = DEFAULT_KEYWORDS.copy() self.no_default_keywords = False self.mapping_file = None self.no_location = False self.omit_header = False self.output_file = None self.input_dirs = None self.width = None self.no_wrap = False self.sort_output = False self.sort_by_file = False self.msgid_bugs_address = None self.copyright_holder = None self.add_comments = None self._add_comments = [] self.strip_comments = False def finalize_options(self): if self.no_default_keywords and not self.keywords: raise DistutilsOptionError('you must specify new keywords if you ' 'disable the default ones') if self.no_default_keywords: self._keywords = {} if self.keywords: self._keywords.update(parse_keywords(self.keywords.split())) if not self.output_file: raise DistutilsOptionError('no output file specified') if self.no_wrap and self.width: raise DistutilsOptionError("'--no-wrap' and '--width' are mutually " "exclusive") if not self.no_wrap and not self.width: self.width = 76 elif self.width is not None: self.width = int(self.width) if self.sort_output and self.sort_by_file: raise DistutilsOptionError("'--sort-output' and '--sort-by-file' " "are mutually exclusive") if not self.input_dirs: self.input_dirs = dict.fromkeys([k.split('.',1)[0] for k in self.distribution.packages ]).keys() if self.add_comments: self._add_comments = self.add_comments.split(',') def run(self): mappings = self._get_mappings() outfile = open(self.output_file, 'w') try: catalog = Catalog(project=self.distribution.get_name(), version=self.distribution.get_version(), msgid_bugs_address=self.msgid_bugs_address, copyright_holder=self.copyright_holder, charset=self.charset) for dirname, (method_map, options_map) in mappings.items(): def callback(filename, method, options): if method == 'ignore': return filepath = os.path.normpath(os.path.join(dirname, filename)) optstr = '' if options: optstr = ' (%s)' % ', '.join(['%s="%s"' % (k, v) for k, v in options.items()]) log.info('extracting messages from %s%s', filepath, optstr) extracted = extract_from_dir(dirname, method_map, options_map, keywords=self._keywords, comment_tags=self._add_comments, callback=callback, strip_comment_tags= self.strip_comments) for filename, lineno, message, comments in extracted: filepath = os.path.normpath(os.path.join(dirname, filename)) catalog.add(message, None, [(filepath, lineno)], auto_comments=comments) log.info('writing PO template file to %s' % self.output_file) write_po(outfile, catalog, width=self.width, no_location=self.no_location, omit_header=self.omit_header, sort_output=self.sort_output, sort_by_file=self.sort_by_file) finally: outfile.close() def _get_mappings(self): mappings = {} if self.mapping_file: fileobj = open(self.mapping_file, 'U') try: method_map, options_map = parse_mapping(fileobj) for dirname in self.input_dirs: mappings[dirname] = method_map, options_map finally: fileobj.close() elif getattr(self.distribution, 'message_extractors', None): message_extractors = self.distribution.message_extractors for dirname, mapping in message_extractors.items(): if isinstance(mapping, basestring): method_map, options_map = parse_mapping(StringIO(mapping)) else: method_map, options_map = [], {} for pattern, method, options in mapping: method_map.append((pattern, method)) options_map[pattern] = options or {} mappings[dirname] = method_map, options_map else: for dirname in self.input_dirs: mappings[dirname] = DEFAULT_MAPPING, {} return mappings def check_message_extractors(dist, name, value): """Validate the ``message_extractors`` keyword argument to ``setup()``. :param dist: the distutils/setuptools ``Distribution`` object :param name: the name of the keyword argument (should always be "message_extractors") :param value: the value of the keyword argument :raise `DistutilsSetupError`: if the value is not valid :see: `Adding setup() arguments <http://peak.telecommunity.com/DevCenter/setuptools#adding-setup-arguments>`_ """ assert name == 'message_extractors' if not isinstance(value, dict): raise DistutilsSetupError('the value of the "message_extractors" ' 'parameter must be a dictionary') class init_catalog(Command): """New catalog initialization command for use in ``setup.py`` scripts. If correctly installed, this command is available to Setuptools-using setup scripts automatically. For projects using plain old ``distutils``, the command needs to be registered explicitly in ``setup.py``:: from babel.messages.frontend import init_catalog setup( ... cmdclass = {'init_catalog': init_catalog} ) :see: `Integrating new distutils commands <http://docs.python.org/dist/node32.html>`_ :see: `setuptools <http://peak.telecommunity.com/DevCenter/setuptools>`_ """ description = 'create a new catalog based on a POT file' user_options = [ ('domain=', 'D', "domain of PO file (default 'messages')"), ('input-file=', 'i', 'name of the input file'), ('output-dir=', 'd', 'path to output directory'), ('output-file=', 'o', "name of the output file (default " "'<output_dir>/<locale>/LC_MESSAGES/<domain>.po')"), ('locale=', 'l', 'locale for the new localized catalog'), ] def initialize_options(self): self.output_dir = None self.output_file = None self.input_file = None self.locale = None self.domain = 'messages' def finalize_options(self): if not self.input_file: raise DistutilsOptionError('you must specify the input file') if not self.locale: raise DistutilsOptionError('you must provide a locale for the ' 'new catalog') try: self._locale = Locale.parse(self.locale) except UnknownLocaleError, e: raise DistutilsOptionError(e) if not self.output_file and not self.output_dir: raise DistutilsOptionError('you must specify the output directory') if not self.output_file: self.output_file = os.path.join(self.output_dir, self.locale, 'LC_MESSAGES', self.domain + '.po') if not os.path.exists(os.path.dirname(self.output_file)): os.makedirs(os.path.dirname(self.output_file)) def run(self): log.info('creating catalog %r based on %r', self.output_file, self.input_file) infile = open(self.input_file, 'r') try: # Although reading from the catalog template, read_po must be fed # the locale in order to correcly calculate plurals catalog = read_po(infile, locale=self.locale) finally: infile.close() catalog.locale = self._locale catalog.fuzzy = False outfile = open(self.output_file, 'w') try: write_po(outfile, catalog) finally: outfile.close() class update_catalog(Command): """Catalog merging command for use in ``setup.py`` scripts. If correctly installed, this command is available to Setuptools-using setup scripts automatically. For projects using plain old ``distutils``, the command needs to be registered explicitly in ``setup.py``:: from babel.messages.frontend import update_catalog setup( ... cmdclass = {'update_catalog': update_catalog} ) :since: version 0.9 :see: `Integrating new distutils commands <http://docs.python.org/dist/node32.html>`_ :see: `setuptools <http://peak.telecommunity.com/DevCenter/setuptools>`_ """ description = 'update message catalogs from a POT file' user_options = [ ('domain=', 'D', "domain of PO file (default 'messages')"), ('input-file=', 'i', 'name of the input file'), ('output-dir=', 'd', 'path to base directory containing the catalogs'), ('output-file=', 'o', "name of the output file (default " "'<output_dir>/<locale>/LC_MESSAGES/<domain>.po')"), ('locale=', 'l', 'locale of the catalog to compile'), ('ignore-obsolete=', None, 'whether to omit obsolete messages from the output'), ('no-fuzzy-matching', 'N', 'do not use fuzzy matching'), ('previous', None, 'keep previous msgids of translated messages') ] boolean_options = ['ignore_obsolete', 'no_fuzzy_matching', 'previous'] def initialize_options(self): self.domain = 'messages' self.input_file = None self.output_dir = None self.output_file = None self.locale = None self.ignore_obsolete = False self.no_fuzzy_matching = False self.previous = False def finalize_options(self): if not self.input_file: raise DistutilsOptionError('you must specify the input file') if not self.output_file and not self.output_dir: raise DistutilsOptionError('you must specify the output file or ' 'directory') if self.output_file and not self.locale: raise DistutilsOptionError('you must specify the locale') if self.no_fuzzy_matching and self.previous: self.previous = False def run(self): po_files = [] if not self.output_file: if self.locale: po_files.append((self.locale, os.path.join(self.output_dir, self.locale, 'LC_MESSAGES', self.domain + '.po'))) else: for locale in os.listdir(self.output_dir): po_file = os.path.join(self.output_dir, locale, 'LC_MESSAGES', self.domain + '.po') if os.path.exists(po_file): po_files.append((locale, po_file)) else: po_files.append((self.locale, self.output_file)) domain = self.domain if not domain: domain = os.path.splitext(os.path.basename(self.input_file))[0] infile = open(self.input_file, 'U') try: template = read_po(infile) finally: infile.close() if not po_files: raise DistutilsOptionError('no message catalogs found') for locale, filename in po_files: log.info('updating catalog %r based on %r', filename, self.input_file) infile = open(filename, 'U') try: catalog = read_po(infile, locale=locale, domain=domain) finally: infile.close() catalog.update(template, self.no_fuzzy_matching) tmpname = os.path.join(os.path.dirname(filename), tempfile.gettempprefix() + os.path.basename(filename)) tmpfile = open(tmpname, 'w') try: try: write_po(tmpfile, catalog, ignore_obsolete=self.ignore_obsolete, include_previous=self.previous) finally: tmpfile.close() except: os.remove(tmpname) raise try: os.rename(tmpname, filename) except OSError: # We're probably on Windows, which doesn't support atomic # renames, at least not through Python # If the error is in fact due to a permissions problem, that # same error is going to be raised from one of the following # operations os.remove(filename) shutil.copy(tmpname, filename) os.remove(tmpname) class CommandLineInterface(object): """Command-line interface. This class provides a simple command-line interface to the message extraction and PO file generation functionality. """ usage = '%%prog %s [options] %s' version = '%%prog %s' % VERSION commands = { 'compile': 'compile message catalogs to MO files', 'extract': 'extract messages from source files and generate a POT file', 'init': 'create new message catalogs from a POT file', 'update': 'update existing message catalogs from a POT file' } def run(self, argv=sys.argv): """Main entry point of the command-line interface. :param argv: list of arguments passed on the command-line """ self.parser = OptionParser(usage=self.usage % ('command', '[args]'), version=self.version) self.parser.disable_interspersed_args() self.parser.print_help = self._help self.parser.add_option('--list-locales', dest='list_locales', action='store_true', help="print all known locales and exit") self.parser.add_option('-v', '--verbose', action='store_const', dest='loglevel', const=logging.DEBUG, help='print as much as possible') self.parser.add_option('-q', '--quiet', action='store_const', dest='loglevel', const=logging.ERROR, help='print as little as possible') self.parser.set_defaults(list_locales=False, loglevel=logging.INFO) options, args = self.parser.parse_args(argv[1:]) self._configure_logging(options.loglevel) if options.list_locales: identifiers = localedata.list() longest = max([len(identifier) for identifier in identifiers]) identifiers.sort() format = u'%%-%ds %%s' % (longest + 1) for identifier in identifiers: locale = Locale.parse(identifier) output = format % (identifier, locale.english_name) print output.encode(sys.stdout.encoding or getpreferredencoding() or 'ascii', 'replace') return 0 if not args: self.parser.error('no valid command or option passed. ' 'Try the -h/--help option for more information.') cmdname = args[0] if cmdname not in self.commands: self.parser.error('unknown command "%s"' % cmdname) return getattr(self, cmdname)(args[1:]) def _configure_logging(self, loglevel): self.log = logging.getLogger('babel') self.log.setLevel(loglevel) # Don't add a new handler for every instance initialization (#227), this # would cause duplicated output when the CommandLineInterface as an # normal Python class. if self.log.handlers: handler = self.log.handlers[0] else: handler = logging.StreamHandler() self.log.addHandler(handler) handler.setLevel(loglevel) formatter = logging.Formatter('%(message)s') handler.setFormatter(formatter) def _help(self): print self.parser.format_help() print "commands:" longest = max([len(command) for command in self.commands]) format = " %%-%ds %%s" % max(8, longest + 1) commands = self.commands.items() commands.sort() for name, description in commands: print format % (name, description) def compile(self, argv): """Subcommand for compiling a message catalog to a MO file. :param argv: the command arguments :since: version 0.9 """ parser = OptionParser(usage=self.usage % ('compile', ''), description=self.commands['compile']) parser.add_option('--domain', '-D', dest='domain', help="domain of MO and PO files (default '%default')") parser.add_option('--directory', '-d', dest='directory', metavar='DIR', help='base directory of catalog files') parser.add_option('--locale', '-l', dest='locale', metavar='LOCALE', help='locale of the catalog') parser.add_option('--input-file', '-i', dest='input_file', metavar='FILE', help='name of the input file') parser.add_option('--output-file', '-o', dest='output_file', metavar='FILE', help="name of the output file (default " "'<output_dir>/<locale>/LC_MESSAGES/" "<domain>.mo')") parser.add_option('--use-fuzzy', '-f', dest='use_fuzzy', action='store_true', help='also include fuzzy translations (default ' '%default)') parser.add_option('--statistics', dest='statistics', action='store_true', help='print statistics about translations') parser.set_defaults(domain='messages', use_fuzzy=False, compile_all=False, statistics=False) options, args = parser.parse_args(argv) po_files = [] mo_files = [] if not options.input_file: if not options.directory: parser.error('you must specify either the input file or the ' 'base directory') if options.locale: po_files.append((options.locale, os.path.join(options.directory, options.locale, 'LC_MESSAGES', options.domain + '.po'))) mo_files.append(os.path.join(options.directory, options.locale, 'LC_MESSAGES', options.domain + '.mo')) else: for locale in os.listdir(options.directory): po_file = os.path.join(options.directory, locale, 'LC_MESSAGES', options.domain + '.po') if os.path.exists(po_file): po_files.append((locale, po_file)) mo_files.append(os.path.join(options.directory, locale, 'LC_MESSAGES', options.domain + '.mo')) else: po_files.append((options.locale, options.input_file)) if options.output_file: mo_files.append(options.output_file) else: if not options.directory: parser.error('you must specify either the input file or ' 'the base directory') mo_files.append(os.path.join(options.directory, options.locale, 'LC_MESSAGES', options.domain + '.mo')) if not po_files: parser.error('no message catalogs found') for idx, (locale, po_file) in enumerate(po_files): mo_file = mo_files[idx] infile = open(po_file, 'r') try: catalog = read_po(infile, locale) finally: infile.close() if options.statistics: translated = 0 for message in list(catalog)[1:]: if message.string: translated +=1 percentage = 0 if len(catalog): percentage = translated * 100 // len(catalog) self.log.info("%d of %d messages (%d%%) translated in %r", translated, len(catalog), percentage, po_file) if catalog.fuzzy and not options.use_fuzzy: self.log.warn('catalog %r is marked as fuzzy, skipping', po_file) continue for message, errors in catalog.check(): for error in errors: self.log.error('error: %s:%d: %s', po_file, message.lineno, error) self.log.info('compiling catalog %r to %r', po_file, mo_file) outfile = open(mo_file, 'wb') try: write_mo(outfile, catalog, use_fuzzy=options.use_fuzzy) finally: outfile.close() def extract(self, argv): """Subcommand for extracting messages from source files and generating a POT file. :param argv: the command arguments """ parser = OptionParser(usage=self.usage % ('extract', 'dir1 <dir2> ...'), description=self.commands['extract']) parser.add_option('--charset', dest='charset', help='charset to use in the output (default ' '"%default")') parser.add_option('-k', '--keyword', dest='keywords', action='append', help='keywords to look for in addition to the ' 'defaults. You can specify multiple -k flags on ' 'the command line.') parser.add_option('--no-default-keywords', dest='no_default_keywords', action='store_true', help="do not include the default keywords") parser.add_option('--mapping', '-F', dest='mapping_file', help='path to the extraction mapping file') parser.add_option('--no-location', dest='no_location', action='store_true', help='do not include location comments with filename ' 'and line number') parser.add_option('--omit-header', dest='omit_header', action='store_true', help='do not include msgid "" entry in header') parser.add_option('-o', '--output', dest='output', help='path to the output POT file') parser.add_option('-w', '--width', dest='width', type='int', help="set output line width (default 76)") parser.add_option('--no-wrap', dest='no_wrap', action = 'store_true', help='do not break long message lines, longer than ' 'the output line width, into several lines') parser.add_option('--sort-output', dest='sort_output', action='store_true', help='generate sorted output (default False)') parser.add_option('--sort-by-file', dest='sort_by_file', action='store_true', help='sort output by file location (default False)') parser.add_option('--msgid-bugs-address', dest='msgid_bugs_address', metavar='EMAIL@ADDRESS', help='set report address for msgid') parser.add_option('--copyright-holder', dest='copyright_holder', help='set copyright holder in output') parser.add_option('--project', dest='project', help='set project name in output') parser.add_option('--version', dest='version', help='set project version in output') parser.add_option('--add-comments', '-c', dest='comment_tags', metavar='TAG', action='append', help='place comment block with TAG (or those ' 'preceding keyword lines) in output file. One ' 'TAG per argument call') parser.add_option('--strip-comment-tags', '-s', dest='strip_comment_tags', action='store_true', help='Strip the comment tags from the comments.') parser.set_defaults(charset='utf-8', keywords=[], no_default_keywords=False, no_location=False, omit_header = False, width=None, no_wrap=False, sort_output=False, sort_by_file=False, comment_tags=[], strip_comment_tags=False) options, args = parser.parse_args(argv) if not args: parser.error('incorrect number of arguments') if options.output not in (None, '-'): outfile = open(options.output, 'w') else: outfile = sys.stdout keywords = DEFAULT_KEYWORDS.copy() if options.no_default_keywords: if not options.keywords: parser.error('you must specify new keywords if you disable the ' 'default ones') keywords = {} if options.keywords: keywords.update(parse_keywords(options.keywords)) if options.mapping_file: fileobj = open(options.mapping_file, 'U') try: method_map, options_map = parse_mapping(fileobj) finally: fileobj.close() else: method_map = DEFAULT_MAPPING options_map = {} if options.width and options.no_wrap: parser.error("'--no-wrap' and '--width' are mutually exclusive.") elif not options.width and not options.no_wrap: options.width = 76 if options.sort_output and options.sort_by_file: parser.error("'--sort-output' and '--sort-by-file' are mutually " "exclusive") try: catalog = Catalog(project=options.project, version=options.version, msgid_bugs_address=options.msgid_bugs_address, copyright_holder=options.copyright_holder, charset=options.charset) for dirname in args: if not os.path.isdir(dirname): parser.error('%r is not a directory' % dirname) def callback(filename, method, options): if method == 'ignore': return filepath = os.path.normpath(os.path.join(dirname, filename)) optstr = '' if options: optstr = ' (%s)' % ', '.join(['%s="%s"' % (k, v) for k, v in options.items()]) self.log.info('extracting messages from %s%s', filepath, optstr) extracted = extract_from_dir(dirname, method_map, options_map, keywords, options.comment_tags, callback=callback, strip_comment_tags= options.strip_comment_tags) for filename, lineno, message, comments in extracted: filepath = os.path.normpath(os.path.join(dirname, filename)) catalog.add(message, None, [(filepath, lineno)], auto_comments=comments) if options.output not in (None, '-'): self.log.info('writing PO template file to %s' % options.output) write_po(outfile, catalog, width=options.width, no_location=options.no_location, omit_header=options.omit_header, sort_output=options.sort_output, sort_by_file=options.sort_by_file) finally: if options.output: outfile.close() def init(self, argv): """Subcommand for creating new message catalogs from a template. :param argv: the command arguments """ parser = OptionParser(usage=self.usage % ('init', ''), description=self.commands['init']) parser.add_option('--domain', '-D', dest='domain', help="domain of PO file (default '%default')") parser.add_option('--input-file', '-i', dest='input_file', metavar='FILE', help='name of the input file') parser.add_option('--output-dir', '-d', dest='output_dir', metavar='DIR', help='path to output directory') parser.add_option('--output-file', '-o', dest='output_file', metavar='FILE', help="name of the output file (default " "'<output_dir>/<locale>/LC_MESSAGES/" "<domain>.po')") parser.add_option('--locale', '-l', dest='locale', metavar='LOCALE', help='locale for the new localized catalog') parser.set_defaults(domain='messages') options, args = parser.parse_args(argv) if not options.locale: parser.error('you must provide a locale for the new catalog') try: locale = Locale.parse(options.locale) except UnknownLocaleError, e: parser.error(e) if not options.input_file: parser.error('you must specify the input file') if not options.output_file and not options.output_dir: parser.error('you must specify the output file or directory') if not options.output_file: options.output_file = os.path.join(options.output_dir, options.locale, 'LC_MESSAGES', options.domain + '.po') if not os.path.exists(os.path.dirname(options.output_file)): os.makedirs(os.path.dirname(options.output_file)) infile = open(options.input_file, 'r') try: # Although reading from the catalog template, read_po must be fed # the locale in order to correcly calculate plurals catalog = read_po(infile, locale=options.locale) finally: infile.close() catalog.locale = locale catalog.revision_date = datetime.now(LOCALTZ) self.log.info('creating catalog %r based on %r', options.output_file, options.input_file) outfile = open(options.output_file, 'w') try: write_po(outfile, catalog) finally: outfile.close() def update(self, argv): """Subcommand for updating existing message catalogs from a template. :param argv: the command arguments :since: version 0.9 """ parser = OptionParser(usage=self.usage % ('update', ''), description=self.commands['update']) parser.add_option('--domain', '-D', dest='domain', help="domain of PO file (default '%default')") parser.add_option('--input-file', '-i', dest='input_file', metavar='FILE', help='name of the input file') parser.add_option('--output-dir', '-d', dest='output_dir', metavar='DIR', help='path to output directory') parser.add_option('--output-file', '-o', dest='output_file', metavar='FILE', help="name of the output file (default " "'<output_dir>/<locale>/LC_MESSAGES/" "<domain>.po')") parser.add_option('--locale', '-l', dest='locale', metavar='LOCALE', help='locale of the translations catalog') parser.add_option('--ignore-obsolete', dest='ignore_obsolete', action='store_true', help='do not include obsolete messages in the output ' '(default %default)') parser.add_option('--no-fuzzy-matching', '-N', dest='no_fuzzy_matching', action='store_true', help='do not use fuzzy matching (default %default)') parser.add_option('--previous', dest='previous', action='store_true', help='keep previous msgids of translated messages ' '(default %default)') parser.set_defaults(domain='messages', ignore_obsolete=False, no_fuzzy_matching=False, previous=False) options, args = parser.parse_args(argv) if not options.input_file: parser.error('you must specify the input file') if not options.output_file and not options.output_dir: parser.error('you must specify the output file or directory') if options.output_file and not options.locale: parser.error('you must specify the locale') if options.no_fuzzy_matching and options.previous: options.previous = False po_files = [] if not options.output_file: if options.locale: po_files.append((options.locale, os.path.join(options.output_dir, options.locale, 'LC_MESSAGES', options.domain + '.po'))) else: for locale in os.listdir(options.output_dir): po_file = os.path.join(options.output_dir, locale, 'LC_MESSAGES', options.domain + '.po') if os.path.exists(po_file): po_files.append((locale, po_file)) else: po_files.append((options.locale, options.output_file)) domain = options.domain if not domain: domain = os.path.splitext(os.path.basename(options.input_file))[0] infile = open(options.input_file, 'U') try: template = read_po(infile) finally: infile.close() if not po_files: parser.error('no message catalogs found') for locale, filename in po_files: self.log.info('updating catalog %r based on %r', filename, options.input_file) infile = open(filename, 'U') try: catalog = read_po(infile, locale=locale, domain=domain) finally: infile.close() catalog.update(template, options.no_fuzzy_matching) tmpname = os.path.join(os.path.dirname(filename), tempfile.gettempprefix() + os.path.basename(filename)) tmpfile = open(tmpname, 'w') try: try: write_po(tmpfile, catalog, ignore_obsolete=options.ignore_obsolete, include_previous=options.previous) finally: tmpfile.close() except: os.remove(tmpname) raise try: os.rename(tmpname, filename) except OSError: # We're probably on Windows, which doesn't support atomic # renames, at least not through Python # If the error is in fact due to a permissions problem, that # same error is going to be raised from one of the following # operations os.remove(filename) shutil.copy(tmpname, filename) os.remove(tmpname) def main(): return CommandLineInterface().run(sys.argv) def parse_mapping(fileobj, filename=None): """Parse an extraction method mapping from a file-like object. >>> buf = StringIO(''' ... [extractors] ... custom = mypackage.module:myfunc ... ... # Python source files ... [python: **.py] ... ... # Genshi templates ... [genshi: **/templates/**.html] ... include_attrs = ... [genshi: **/templates/**.txt] ... template_class = genshi.template:TextTemplate ... encoding = latin-1 ... ... # Some custom extractor ... [custom: **/custom/*.*] ... ''') >>> method_map, options_map = parse_mapping(buf) >>> len(method_map) 4 >>> method_map[0] ('**.py', 'python') >>> options_map['**.py'] {} >>> method_map[1] ('**/templates/**.html', 'genshi') >>> options_map['**/templates/**.html']['include_attrs'] '' >>> method_map[2] ('**/templates/**.txt', 'genshi') >>> options_map['**/templates/**.txt']['template_class'] 'genshi.template:TextTemplate' >>> options_map['**/templates/**.txt']['encoding'] 'latin-1' >>> method_map[3] ('**/custom/*.*', 'mypackage.module:myfunc') >>> options_map['**/custom/*.*'] {} :param fileobj: a readable file-like object containing the configuration text to parse :return: a `(method_map, options_map)` tuple :rtype: `tuple` :see: `extract_from_directory` """ extractors = {} method_map = [] options_map = {} parser = RawConfigParser() parser._sections = odict(parser._sections) # We need ordered sections parser.readfp(fileobj, filename) for section in parser.sections(): if section == 'extractors': extractors = dict(parser.items(section)) else: method, pattern = [part.strip() for part in section.split(':', 1)] method_map.append((pattern, method)) options_map[pattern] = dict(parser.items(section)) if extractors: for idx, (pattern, method) in enumerate(method_map): if method in extractors: method = extractors[method] method_map[idx] = (pattern, method) return (method_map, options_map) def parse_keywords(strings=[]): """Parse keywords specifications from the given list of strings. >>> kw = parse_keywords(['_', 'dgettext:2', 'dngettext:2,3']).items() >>> kw.sort() >>> for keyword, indices in kw: ... print (keyword, indices) ('_', None) ('dgettext', (2,)) ('dngettext', (2, 3)) """ keywords = {} for string in strings: if ':' in string: funcname, indices = string.split(':') else: funcname, indices = string, None if funcname not in keywords: if indices: indices = tuple([(int(x)) for x in indices.split(',')]) keywords[funcname] = indices return keywords if __name__ == '__main__': main()
apache-2.0
ronny3050/MobileNet
retrain.py
1
56996
# 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. # ============================================================================== r"""Simple transfer learning with Inception v3 or Mobilenet models. With support for TensorBoard. This example shows how to take a Inception v3 or Mobilenet model trained on ImageNet images, and train a new top layer that can recognize other classes of images. The top layer receives as input a 2048-dimensional vector (1001-dimensional for Mobilenet) for each image. We train a softmax layer on top of this representation. Assuming the softmax layer contains N labels, this corresponds to learning N + 2048*N (or 1001*N) model parameters corresponding to the learned biases and weights. Here's an example, which assumes you have a folder containing class-named subfolders, each full of images for each label. The example folder flower_photos should have a structure like this: ~/flower_photos/daisy/photo1.jpg ~/flower_photos/daisy/photo2.jpg ... ~/flower_photos/rose/anotherphoto77.jpg ... ~/flower_photos/sunflower/somepicture.jpg The subfolder names are important, since they define what label is applied to each image, but the filenames themselves don't matter. Once your images are prepared, you can run the training with a command like this: ```bash bazel build tensorflow/examples/image_retraining:retrain && \ bazel-bin/tensorflow/examples/image_retraining/retrain \ --image_dir ~/flower_photos ``` Or, if you have a pip installation of tensorflow, `retrain.py` can be run without bazel: ```bash python tensorflow/examples/image_retraining/retrain.py \ --image_dir ~/flower_photos ``` You can replace the image_dir argument with any folder containing subfolders of images. The label for each image is taken from the name of the subfolder it's in. This produces a new model file that can be loaded and run by any TensorFlow program, for example the label_image sample code. By default this script will use the high accuracy, but comparatively large and slow Inception v3 model architecture. It's recommended that you start with this to validate that you have gathered good training data, but if you want to deploy on resource-limited platforms, you can try the `--architecture` flag with a Mobilenet model. For example: ```bash python tensorflow/examples/image_retraining/retrain.py \ --image_dir ~/flower_photos --architecture mobilenet_1.0_224 ``` There are 32 different Mobilenet models to choose from, with a variety of file size and latency options. The first number can be '1.0', '0.75', '0.50', or '0.25' to control the size, and the second controls the input image size, either '224', '192', '160', or '128', with smaller sizes running faster. See https://research.googleblog.com/2017/06/mobilenets-open-source-models-for.html for more information on Mobilenet. To use with TensorBoard: By default, this script will log summaries to /tmp/retrain_logs directory Visualize the summaries with this command: tensorboard --logdir /tmp/retrain_logs """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse from datetime import datetime import hashlib import os.path import random import re import sys import tarfile from sklearn.model_selection import train_test_split import numpy as np from six.moves import urllib import tensorflow as tf from tensorflow.python.framework import graph_util from tensorflow.python.framework import tensor_shape from tensorflow.python.platform import gfile from tensorflow.python.util import compat FLAGS = None # These are all parameters that are tied to the particular model architecture # we're using for Inception v3. These include things like tensor names and their # sizes. If you want to adapt this script to work with another model, you will # need to update these to reflect the values in the network you're using. MAX_NUM_IMAGES_PER_CLASS = 2 ** 27 - 1 # ~134M def create_image_lists(image_dir, testing_percentage, validation_percentage): """Builds a list of training images from the file system. Analyzes the sub folders in the image directory, splits them into stable training, testing, and validation sets, and returns a data structure describing the lists of images for each label and their paths. Args: image_dir: String path to a folder containing subfolders of images. testing_percentage: Integer percentage of the images to reserve for tests. validation_percentage: Integer percentage of images reserved for validation. Returns: A dictionary containing an entry for each label subfolder, with images split into training, testing, and validation sets within each label. """ if not gfile.Exists(image_dir): tf.logging.error("Image directory '" + image_dir + "' not found.") return None result = {} sub_dirs = [x[0] for x in gfile.Walk(image_dir)] # The root directory comes first, so skip it. is_root_dir = True for sub_dir in sub_dirs: if is_root_dir: is_root_dir = False continue extensions = ['jpg', 'jpeg', 'JPG', 'JPEG'] file_list = [] dir_name = os.path.basename(sub_dir) if dir_name == image_dir: continue tf.logging.info("Looking for images in '" + dir_name + "'") for extension in extensions: file_glob = os.path.join(image_dir, dir_name, '*.' + extension) file_list.extend(gfile.Glob(file_glob)) if not file_list: tf.logging.warning('No files found') continue if len(file_list) < 20: tf.logging.warning( 'WARNING: Folder has less than 20 images, which may cause issues.') elif len(file_list) > MAX_NUM_IMAGES_PER_CLASS: tf.logging.warning( 'WARNING: Folder {} has more than {} images. Some images will ' 'never be selected.'.format(dir_name, MAX_NUM_IMAGES_PER_CLASS)) label_name = re.sub(r'[^a-z0-9]+', ' ', dir_name.lower()) training_images = [] testing_images = [] validation_images = [] file_names = [os.path.basename(file_name) for file_name in file_list] training_images, validation_images = train_test_split(file_names, test_size=validation_percentage/100.0) ## for file_name in file_list: ## base_name = os.path.basename(file_name) ## # We want to ignore anything after '_nohash_' in the file name when ## # deciding which set to put an image in, the data set creator has a way of ## # grouping photos that are close variations of each other. For example ## # this is used in the plant disease data set to group multiple pictures of ## # the same leaf. ## hash_name = re.sub(r'_nohash_.*$', '', file_name) ## # This looks a bit magical, but we need to decide whether this file should ## # go into the training, testing, or validation sets, and we want to keep ## # existing files in the same set even if more files are subsequently ## # added. ## # To do that, we need a stable way of deciding based on just the file name ## # itself, so we do a hash of that and then use that to generate a ## # probability value that we use to assign it. ## hash_name_hashed = hashlib.sha1(compat.as_bytes(hash_name)).hexdigest() ## percentage_hash = ((int(hash_name_hashed, 16) % ## (MAX_NUM_IMAGES_PER_CLASS + 1)) * ## (100.0 / MAX_NUM_IMAGES_PER_CLASS)) ## if percentage_hash < validation_percentage: ## validation_images.append(base_name) #### elif percentage_hash < (testing_percentage + validation_percentage): #### testing_images.append(base_name) ## else: ## training_images.append(base_name) result[label_name] = { 'dir': dir_name, 'training': training_images, 'testing': testing_images, 'validation': validation_images, } return result def get_image_path(image_lists, label_name, index, image_dir, category): """"Returns a path to an image for a label at the given index. Args: image_lists: Dictionary of training images for each label. label_name: Label string we want to get an image for. index: Int offset of the image we want. This will be moduloed by the available number of images for the label, so it can be arbitrarily large. image_dir: Root folder string of the subfolders containing the training images. category: Name string of set to pull images from - training, testing, or validation. Returns: File system path string to an image that meets the requested parameters. """ if label_name not in image_lists: tf.logging.fatal('Label does not exist %s.', label_name) label_lists = image_lists[label_name] if category not in label_lists: tf.logging.fatal('Category does not exist %s.', category) category_list = label_lists[category] if not category_list: tf.logging.fatal('Label %s has no images in the category %s.', label_name, category) mod_index = index % len(category_list) base_name = category_list[mod_index] sub_dir = label_lists['dir'] full_path = os.path.join(image_dir, sub_dir, base_name) return full_path def get_bottleneck_path(image_lists, label_name, index, bottleneck_dir, category, architecture): """"Returns a path to a bottleneck file for a label at the given index. Args: image_lists: Dictionary of training images for each label. label_name: Label string we want to get an image for. index: Integer offset of the image we want. This will be moduloed by the available number of images for the label, so it can be arbitrarily large. bottleneck_dir: Folder string holding cached files of bottleneck values. category: Name string of set to pull images from - training, testing, or validation. architecture: The name of the model architecture. Returns: File system path string to an image that meets the requested parameters. """ return get_image_path(image_lists, label_name, index, bottleneck_dir, category) + '_' + architecture + '.txt' def create_model_graph(model_info): """"Creates a graph from saved GraphDef file and returns a Graph object. Args: model_info: Dictionary containing information about the model architecture. Returns: Graph holding the trained Inception network, and various tensors we'll be manipulating. """ with tf.Graph().as_default() as graph: model_path = os.path.join(FLAGS.model_dir, model_info['model_file_name']) with gfile.FastGFile(model_path, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) bottleneck_tensor, resized_input_tensor = (tf.import_graph_def( graph_def, name='', return_elements=[ model_info['bottleneck_tensor_name'], model_info['resized_input_tensor_name'], ])) return graph, bottleneck_tensor, resized_input_tensor def run_bottleneck_on_image(sess, image_data, image_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor): """Runs inference on an image to extract the 'bottleneck' summary layer. Args: sess: Current active TensorFlow Session. image_data: String of raw JPEG data. image_data_tensor: Input data layer in the graph. decoded_image_tensor: Output of initial image resizing and preprocessing. resized_input_tensor: The input node of the recognition graph. bottleneck_tensor: Layer before the final softmax. Returns: Numpy array of bottleneck values. """ # First decode the JPEG image, resize it, and rescale the pixel values. resized_input_values = sess.run(decoded_image_tensor, {image_data_tensor: image_data}) # Then run it through the recognition network. bottleneck_values = sess.run(bottleneck_tensor, {resized_input_tensor: resized_input_values}) bottleneck_values = np.squeeze(bottleneck_values) return bottleneck_values def maybe_download_and_extract(data_url): """Download and extract model tar file. If the pretrained model we're using doesn't already exist, this function downloads it from the TensorFlow.org website and unpacks it into a directory. Args: data_url: Web location of the tar file containing the pretrained model. """ dest_directory = FLAGS.model_dir if not os.path.exists(dest_directory): os.makedirs(dest_directory) filename = data_url.split('/')[-1] filepath = os.path.join(dest_directory, filename) if not os.path.exists(filepath): def _progress(count, block_size, total_size): sys.stdout.write('\r>> Downloading %s %.1f%%' % (filename, float(count * block_size) / float(total_size) * 100.0)) sys.stdout.flush() filepath, _ = urllib.request.urlretrieve(data_url, filepath, _progress) print() statinfo = os.stat(filepath) tf.logging.info('Successfully downloaded', filename, statinfo.st_size, 'bytes.') tarfile.open(filepath, 'r:gz').extractall(dest_directory) def ensure_dir_exists(dir_name): """Makes sure the folder exists on disk. Args: dir_name: Path string to the folder we want to create. """ if not os.path.exists(dir_name): os.makedirs(dir_name) bottleneck_path_2_bottleneck_values = {} def create_bottleneck_file(bottleneck_path, image_lists, label_name, index, image_dir, category, sess, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor): """Create a single bottleneck file.""" tf.logging.info('Creating bottleneck at ' + bottleneck_path) image_path = get_image_path(image_lists, label_name, index, image_dir, category) if not gfile.Exists(image_path): tf.logging.fatal('File does not exist %s', image_path) image_data = gfile.FastGFile(image_path, 'rb').read() try: bottleneck_values = run_bottleneck_on_image( sess, image_data, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor) except Exception as e: raise RuntimeError('Error during processing file %s (%s)' % (image_path, str(e))) bottleneck_string = ','.join(str(x) for x in bottleneck_values) with open(bottleneck_path, 'w') as bottleneck_file: bottleneck_file.write(bottleneck_string) def get_or_create_bottleneck(sess, image_lists, label_name, index, image_dir, category, bottleneck_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor, architecture): """Retrieves or calculates bottleneck values for an image. If a cached version of the bottleneck data exists on-disk, return that, otherwise calculate the data and save it to disk for future use. Args: sess: The current active TensorFlow Session. image_lists: Dictionary of training images for each label. label_name: Label string we want to get an image for. index: Integer offset of the image we want. This will be modulo-ed by the available number of images for the label, so it can be arbitrarily large. image_dir: Root folder string of the subfolders containing the training images. category: Name string of which set to pull images from - training, testing, or validation. bottleneck_dir: Folder string holding cached files of bottleneck values. jpeg_data_tensor: The tensor to feed loaded jpeg data into. decoded_image_tensor: The output of decoding and resizing the image. resized_input_tensor: The input node of the recognition graph. bottleneck_tensor: The output tensor for the bottleneck values. architecture: The name of the model architecture. Returns: Numpy array of values produced by the bottleneck layer for the image. """ label_lists = image_lists[label_name] sub_dir = label_lists['dir'] sub_dir_path = os.path.join(bottleneck_dir, sub_dir) ensure_dir_exists(sub_dir_path) bottleneck_path = get_bottleneck_path(image_lists, label_name, index, bottleneck_dir, category, architecture) if not os.path.exists(bottleneck_path): create_bottleneck_file(bottleneck_path, image_lists, label_name, index, image_dir, category, sess, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor) with open(bottleneck_path, 'r') as bottleneck_file: bottleneck_string = bottleneck_file.read() did_hit_error = False try: bottleneck_values = [float(x) for x in bottleneck_string.split(',')] except ValueError: tf.logging.warning('Invalid float found, recreating bottleneck') did_hit_error = True if did_hit_error: create_bottleneck_file(bottleneck_path, image_lists, label_name, index, image_dir, category, sess, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor) with open(bottleneck_path, 'r') as bottleneck_file: bottleneck_string = bottleneck_file.read() # Allow exceptions to propagate here, since they shouldn't happen after a # fresh creation bottleneck_values = [float(x) for x in bottleneck_string.split(',')] return bottleneck_values def cache_bottlenecks(sess, image_lists, image_dir, bottleneck_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor, architecture): """Ensures all the training, testing, and validation bottlenecks are cached. Because we're likely to read the same image multiple times (if there are no distortions applied during training) it can speed things up a lot if we calculate the bottleneck layer values once for each image during preprocessing, and then just read those cached values repeatedly during training. Here we go through all the images we've found, calculate those values, and save them off. Args: sess: The current active TensorFlow Session. image_lists: Dictionary of training images for each label. image_dir: Root folder string of the subfolders containing the training images. bottleneck_dir: Folder string holding cached files of bottleneck values. jpeg_data_tensor: Input tensor for jpeg data from file. decoded_image_tensor: The output of decoding and resizing the image. resized_input_tensor: The input node of the recognition graph. bottleneck_tensor: The penultimate output layer of the graph. architecture: The name of the model architecture. Returns: Nothing. """ how_many_bottlenecks = 0 ensure_dir_exists(bottleneck_dir) for label_name, label_lists in image_lists.items(): for category in ['training', 'testing', 'validation']: category_list = label_lists[category] for index, unused_base_name in enumerate(category_list): get_or_create_bottleneck( sess, image_lists, label_name, index, image_dir, category, bottleneck_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor, architecture) how_many_bottlenecks += 1 if how_many_bottlenecks % 100 == 0: tf.logging.info( str(how_many_bottlenecks) + ' bottleneck files created.') def get_random_cached_bottlenecks(sess, image_lists, how_many, category, bottleneck_dir, image_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor, architecture): """Retrieves bottleneck values for cached images. If no distortions are being applied, this function can retrieve the cached bottleneck values directly from disk for images. It picks a random set of images from the specified category. Args: sess: Current TensorFlow Session. image_lists: Dictionary of training images for each label. how_many: If positive, a random sample of this size will be chosen. If negative, all bottlenecks will be retrieved. category: Name string of which set to pull from - training, testing, or validation. bottleneck_dir: Folder string holding cached files of bottleneck values. image_dir: Root folder string of the subfolders containing the training images. jpeg_data_tensor: The layer to feed jpeg image data into. decoded_image_tensor: The output of decoding and resizing the image. resized_input_tensor: The input node of the recognition graph. bottleneck_tensor: The bottleneck output layer of the CNN graph. architecture: The name of the model architecture. Returns: List of bottleneck arrays, their corresponding ground truths, and the relevant filenames. """ class_count = len(image_lists.keys()) bottlenecks = [] ground_truths = [] filenames = [] if how_many >= 0: # Retrieve a random sample of bottlenecks. for unused_i in range(how_many): label_index = random.randrange(class_count) label_name = list(image_lists.keys())[label_index] image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1) image_name = get_image_path(image_lists, label_name, image_index, image_dir, category) bottleneck = get_or_create_bottleneck( sess, image_lists, label_name, image_index, image_dir, category, bottleneck_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor, architecture) ground_truth = np.zeros(class_count, dtype=np.float32) ground_truth[label_index] = 1.0 bottlenecks.append(bottleneck) ground_truths.append(ground_truth) filenames.append(image_name) else: # Retrieve all bottlenecks. for label_index, label_name in enumerate(image_lists.keys()): for image_index, image_name in enumerate( image_lists[label_name][category]): image_name = get_image_path(image_lists, label_name, image_index, image_dir, category) bottleneck = get_or_create_bottleneck( sess, image_lists, label_name, image_index, image_dir, category, bottleneck_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor, architecture) ground_truth = np.zeros(class_count, dtype=np.float32) ground_truth[label_index] = 1.0 bottlenecks.append(bottleneck) ground_truths.append(ground_truth) filenames.append(image_name) return bottlenecks, ground_truths, filenames def get_random_distorted_bottlenecks( sess, image_lists, how_many, category, image_dir, input_jpeg_tensor, distorted_image, resized_input_tensor, bottleneck_tensor): """Retrieves bottleneck values for training images, after distortions. If we're training with distortions like crops, scales, or flips, we have to recalculate the full model for every image, and so we can't use cached bottleneck values. Instead we find random images for the requested category, run them through the distortion graph, and then the full graph to get the bottleneck results for each. Args: sess: Current TensorFlow Session. image_lists: Dictionary of training images for each label. how_many: The integer number of bottleneck values to return. category: Name string of which set of images to fetch - training, testing, or validation. image_dir: Root folder string of the subfolders containing the training images. input_jpeg_tensor: The input layer we feed the image data to. distorted_image: The output node of the distortion graph. resized_input_tensor: The input node of the recognition graph. bottleneck_tensor: The bottleneck output layer of the CNN graph. Returns: List of bottleneck arrays and their corresponding ground truths. """ class_count = len(image_lists.keys()) bottlenecks = [] ground_truths = [] for unused_i in range(how_many): label_index = random.randrange(class_count) label_name = list(image_lists.keys())[label_index] image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1) image_path = get_image_path(image_lists, label_name, image_index, image_dir, category) if not gfile.Exists(image_path): tf.logging.fatal('File does not exist %s', image_path) jpeg_data = gfile.FastGFile(image_path, 'rb').read() # Note that we materialize the distorted_image_data as a numpy array before # sending running inference on the image. This involves 2 memory copies and # might be optimized in other implementations. distorted_image_data = sess.run(distorted_image, {input_jpeg_tensor: jpeg_data}) bottleneck_values = sess.run(bottleneck_tensor, {resized_input_tensor: distorted_image_data}) bottleneck_values = np.squeeze(bottleneck_values) ground_truth = np.zeros(class_count, dtype=np.float32) ground_truth[label_index] = 1.0 bottlenecks.append(bottleneck_values) ground_truths.append(ground_truth) return bottlenecks, ground_truths def should_distort_images(flip_left_right, random_crop, random_scale, random_brightness): """Whether any distortions are enabled, from the input flags. Args: flip_left_right: Boolean whether to randomly mirror images horizontally. random_crop: Integer percentage setting the total margin used around the crop box. random_scale: Integer percentage of how much to vary the scale by. random_brightness: Integer range to randomly multiply the pixel values by. Returns: Boolean value indicating whether any distortions should be applied. """ return (flip_left_right or (random_crop != 0) or (random_scale != 0) or (random_brightness != 0)) def add_input_distortions(flip_left_right, random_crop, random_scale, random_brightness, input_width, input_height, input_depth, input_mean, input_std): """Creates the operations to apply the specified distortions. During training it can help to improve the results if we run the images through simple distortions like crops, scales, and flips. These reflect the kind of variations we expect in the real world, and so can help train the model to cope with natural data more effectively. Here we take the supplied parameters and construct a network of operations to apply them to an image. Cropping ~~~~~~~~ Cropping is done by placing a bounding box at a random position in the full image. The cropping parameter controls the size of that box relative to the input image. If it's zero, then the box is the same size as the input and no cropping is performed. If the value is 50%, then the crop box will be half the width and height of the input. In a diagram it looks like this: < width > +---------------------+ | | | width - crop% | | < > | | +------+ | | | | | | | | | | | | | | +------+ | | | | | +---------------------+ Scaling ~~~~~~~ Scaling is a lot like cropping, except that the bounding box is always centered and its size varies randomly within the given range. For example if the scale percentage is zero, then the bounding box is the same size as the input and no scaling is applied. If it's 50%, then the bounding box will be in a random range between half the width and height and full size. Args: flip_left_right: Boolean whether to randomly mirror images horizontally. random_crop: Integer percentage setting the total margin used around the crop box. random_scale: Integer percentage of how much to vary the scale by. random_brightness: Integer range to randomly multiply the pixel values by. graph. input_width: Horizontal size of expected input image to model. input_height: Vertical size of expected input image to model. input_depth: How many channels the expected input image should have. input_mean: Pixel value that should be zero in the image for the graph. input_std: How much to divide the pixel values by before recognition. Returns: The jpeg input layer and the distorted result tensor. """ jpeg_data = tf.placeholder(tf.string, name='DistortJPGInput') decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth) decoded_image_as_float = tf.cast(decoded_image, dtype=tf.float32) decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0) margin_scale = 1.0 + (random_crop / 100.0) resize_scale = 1.0 + (random_scale / 100.0) margin_scale_value = tf.constant(margin_scale) resize_scale_value = tf.random_uniform(tensor_shape.scalar(), minval=1.0, maxval=resize_scale) scale_value = tf.multiply(margin_scale_value, resize_scale_value) precrop_width = tf.multiply(scale_value, input_width) precrop_height = tf.multiply(scale_value, input_height) precrop_shape = tf.stack([precrop_height, precrop_width]) precrop_shape_as_int = tf.cast(precrop_shape, dtype=tf.int32) precropped_image = tf.image.resize_bilinear(decoded_image_4d, precrop_shape_as_int) precropped_image_3d = tf.squeeze(precropped_image, squeeze_dims=[0]) cropped_image = tf.random_crop(precropped_image_3d, [input_height, input_width, input_depth]) if flip_left_right: flipped_image = tf.image.random_flip_left_right(cropped_image) else: flipped_image = cropped_image brightness_min = 1.0 - (random_brightness / 100.0) brightness_max = 1.0 + (random_brightness / 100.0) brightness_value = tf.random_uniform(tensor_shape.scalar(), minval=brightness_min, maxval=brightness_max) brightened_image = tf.multiply(flipped_image, brightness_value) offset_image = tf.subtract(brightened_image, input_mean) mul_image = tf.multiply(offset_image, 1.0 / input_std) distort_result = tf.expand_dims(mul_image, 0, name='DistortResult') return jpeg_data, distort_result def variable_summaries(var): """Attach a lot of summaries to a Tensor (for TensorBoard visualization).""" with tf.name_scope('summaries'): mean = tf.reduce_mean(var) tf.summary.scalar('mean', mean) with tf.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean))) tf.summary.scalar('stddev', stddev) tf.summary.scalar('max', tf.reduce_max(var)) tf.summary.scalar('min', tf.reduce_min(var)) tf.summary.histogram('histogram', var) def get_center_loss(features, labels, alpha, num_classes): nrof_features = features.get_shape()[1] centers = tf.get_variable('centers', [num_classes, nrof_features], dtype=tf.float32, initializer=tf.constant_initializer(0), trainable=False) labels = tf.argmax(labels,1) label = tf.reshape(labels, [-1]) centers_batch = tf.gather(centers, label) diff = (1 - alpha) * (centers_batch - features) centers = tf.scatter_sub(centers, label, diff) with tf.control_dependencies([centers]): loss = tf.reduce_mean(tf.square(features - centers_batch)) return loss, centers def add_final_training_ops(class_count, labels, final_tensor_name, bottleneck_tensor, bottleneck_tensor_size): """Adds a new softmax and fully-connected layer for training. We need to retrain the top layer to identify our new classes, so this function adds the right operations to the graph, along with some variables to hold the weights, and then sets up all the gradients for the backward pass. The set up for the softmax and fully-connected layers is based on: https://www.tensorflow.org/versions/master/tutorials/mnist/beginners/index.html Args: class_count: Integer of how many categories of things we're trying to recognize. final_tensor_name: Name string for the new final node that produces results. bottleneck_tensor: The output of the main CNN graph. bottleneck_tensor_size: How many entries in the bottleneck vector. Returns: The tensors for the training and cross entropy results, and tensors for the bottleneck input and ground truth input. """ with tf.name_scope('input'): bottleneck_input = tf.placeholder_with_default( bottleneck_tensor, shape=[None, bottleneck_tensor_size], name='BottleneckInputPlaceholder') ground_truth_input = tf.placeholder(tf.int32, [None, class_count], name='GroundTruthInput') # Organizing the following ops as `final_training_ops` so they're easier # to see in TensorBoard layer_name = 'final_training_ops' with tf.name_scope(layer_name): with tf.name_scope('weights'): initial_value = tf.truncated_normal( [bottleneck_tensor_size, class_count], stddev=0.001) layer_weights = tf.Variable(initial_value, name='final_weights') variable_summaries(layer_weights) with tf.name_scope('biases'): layer_biases = tf.Variable(tf.zeros([class_count]), name='final_biases') variable_summaries(layer_biases) with tf.name_scope('Wx_plus_b'): logits = tf.matmul(bottleneck_input, layer_weights) + layer_biases tf.summary.histogram('pre_activations', logits) final_tensor = tf.nn.softmax(logits, name=final_tensor_name) tf.summary.histogram('activations', final_tensor) with tf.name_scope('center_loss'): center_loss, centers = get_center_loss(bottleneck_input, ground_truth_input, FLAGS.center_loss_alpha, class_count) with tf.name_scope('cross_entropy'): cross_entropy = tf.nn.softmax_cross_entropy_with_logits( labels=ground_truth_input, logits=logits) with tf.name_scope('total'): cross_entropy_mean = tf.reduce_mean(cross_entropy) total_loss = cross_entropy_mean + FLAGS.center_loss_factor * center_loss tf.summary.scalar('center_loss', center_loss) tf.summary.scalar('cross_entropy', cross_entropy_mean) tf.summary.scalar('total_loss', total_loss) with tf.name_scope('train'): optimizer = tf.train.GradientDescentOptimizer(FLAGS.learning_rate) train_step = optimizer.minimize(total_loss) return (train_step, total_loss, bottleneck_input, ground_truth_input, final_tensor) def add_evaluation_step(result_tensor, ground_truth_tensor): """Inserts the operations we need to evaluate the accuracy of our results. Args: result_tensor: The new final node that produces results. ground_truth_tensor: The node we feed ground truth data into. Returns: Tuple of (evaluation step, prediction). """ with tf.name_scope('accuracy'): with tf.name_scope('correct_prediction'): prediction = tf.argmax(result_tensor, 1) correct_prediction = tf.equal( prediction, tf.argmax(ground_truth_tensor, 1)) with tf.name_scope('accuracy'): evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) tf.summary.scalar('accuracy', evaluation_step) return evaluation_step, prediction def save_graph_to_file(sess, graph, graph_file_name): output_graph_def = graph_util.convert_variables_to_constants( sess, graph.as_graph_def(), [FLAGS.final_tensor_name]) with gfile.FastGFile(graph_file_name, 'wb') as f: f.write(output_graph_def.SerializeToString()) return def prepare_file_system(): # Setup the directory we'll write summaries to for TensorBoard if tf.gfile.Exists(FLAGS.summaries_dir): tf.gfile.DeleteRecursively(FLAGS.summaries_dir) tf.gfile.MakeDirs(FLAGS.summaries_dir) if FLAGS.intermediate_store_frequency > 0: ensure_dir_exists(FLAGS.intermediate_output_graphs_dir) return def create_model_info(architecture): """Given the name of a model architecture, returns information about it. There are different base image recognition pretrained models that can be retrained using transfer learning, and this function translates from the name of a model to the attributes that are needed to download and train with it. Args: architecture: Name of a model architecture. Returns: Dictionary of information about the model, or None if the name isn't recognized Raises: ValueError: If architecture name is unknown. """ architecture = architecture.lower() if architecture == 'inception_v3': # pylint: disable=line-too-long data_url = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz' # pylint: enable=line-too-long bottleneck_tensor_name = 'pool_3/_reshape:0' bottleneck_tensor_size = 2048 input_width = 299 input_height = 299 input_depth = 3 resized_input_tensor_name = 'Mul:0' model_file_name = 'classify_image_graph_def.pb' input_mean = 128 input_std = 128 elif architecture.startswith('mobilenet_'): parts = architecture.split('_') if len(parts) != 3 and len(parts) != 4: tf.logging.error("Couldn't understand architecture name '%s'", architecture) return None version_string = parts[1] if (version_string != '1.0' and version_string != '0.75' and version_string != '0.50' and version_string != '0.25'): tf.logging.error( """"The Mobilenet version should be '1.0', '0.75', '0.50', or '0.25', but found '%s' for architecture '%s'""", version_string, architecture) return None size_string = parts[2] if (size_string != '224' and size_string != '192' and size_string != '160' and size_string != '128'): tf.logging.error( """The Mobilenet input size should be '224', '192', '160', or '128', but found '%s' for architecture '%s'""", size_string, architecture) return None if len(parts) == 3: is_quantized = False else: if parts[3] != 'quantized': tf.logging.error( "Couldn't understand architecture suffix '%s' for '%s'", parts[3], architecture) return None is_quantized = True data_url = 'http://download.tensorflow.org/models/mobilenet_v1_' data_url += version_string + '_' + size_string + '_frozen.tgz' bottleneck_tensor_name = 'MobilenetV1/Predictions/Reshape:0' bottleneck_tensor_size = 1001 input_width = int(size_string) input_height = int(size_string) input_depth = 3 resized_input_tensor_name = 'input:0' if is_quantized: model_base_name = 'quantized_graph.pb' else: model_base_name = 'frozen_graph.pb' model_dir_name = 'mobilenet_v1_' + version_string + '_' + size_string model_file_name = os.path.join(model_dir_name, model_base_name) input_mean = 127.5 input_std = 127.5 else: tf.logging.error("Couldn't understand architecture name '%s'", architecture) raise ValueError('Unknown architecture', architecture) return { 'data_url': data_url, 'bottleneck_tensor_name': bottleneck_tensor_name, 'bottleneck_tensor_size': bottleneck_tensor_size, 'input_width': input_width, 'input_height': input_height, 'input_depth': input_depth, 'resized_input_tensor_name': resized_input_tensor_name, 'model_file_name': model_file_name, 'input_mean': input_mean, 'input_std': input_std, } def add_jpeg_decoding(input_width, input_height, input_depth, input_mean, input_std): """Adds operations that perform JPEG decoding and resizing to the graph.. Args: input_width: Desired width of the image fed into the recognizer graph. input_height: Desired width of the image fed into the recognizer graph. input_depth: Desired channels of the image fed into the recognizer graph. input_mean: Pixel value that should be zero in the image for the graph. input_std: How much to divide the pixel values by before recognition. Returns: Tensors for the node to feed JPEG data into, and the output of the preprocessing steps. """ jpeg_data = tf.placeholder(tf.string, name='DecodeJPGInput') decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth) decoded_image_as_float = tf.cast(decoded_image, dtype=tf.float32) decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0) resize_shape = tf.stack([input_height, input_width]) resize_shape_as_int = tf.cast(resize_shape, dtype=tf.int32) resized_image = tf.image.resize_bilinear(decoded_image_4d, resize_shape_as_int) offset_image = tf.subtract(resized_image, input_mean) mul_image = tf.multiply(offset_image, 1.0 / input_std) return jpeg_data, mul_image def get_numerical_labels(image_lists): numerical_labels = [] cnt = 0 prev = '' for i in image_lists.keys(): numerical_labels.append(cnt) cnt = cnt + 1 return numerical_labels def main(_): # Needed to make sure the logging output is visible. # See https://github.com/tensorflow/tensorflow/issues/3047 tf.logging.set_verbosity(tf.logging.INFO) # Prepare necessary directories that can be used during training prepare_file_system() # Gather information about the model architecture we'll be using. model_info = create_model_info(FLAGS.architecture) if not model_info: tf.logging.error('Did not recognize architecture flag') return -1 # Set up the pre-trained graph. maybe_download_and_extract(model_info['data_url']) graph, bottleneck_tensor, resized_image_tensor = ( create_model_graph(model_info)) # Look at the folder structure, and create lists of all the images. image_lists = create_image_lists(FLAGS.image_dir, FLAGS.testing_percentage, FLAGS.validation_percentage) f = open( 'image_lists.py', 'w' ) f.write( 'dict = ' + repr(image_lists) + '\n' ) f.close() class_count = len(image_lists.keys()) if class_count == 0: tf.logging.error('No valid folders of images found at ' + FLAGS.image_dir) return -1 if class_count == 1: tf.logging.error('Only one valid folder of images found at ' + FLAGS.image_dir + ' - multiple classes are needed for classification.') return -1 # See if the command-line flags mean we're applying any distortions. do_distort_images = should_distort_images( FLAGS.flip_left_right, FLAGS.random_crop, FLAGS.random_scale, FLAGS.random_brightness) numerical_labels = get_numerical_labels(image_lists) with tf.Session(graph=graph) as sess: # Set up the image decoding sub-graph. jpeg_data_tensor, decoded_image_tensor = add_jpeg_decoding( model_info['input_width'], model_info['input_height'], model_info['input_depth'], model_info['input_mean'], model_info['input_std']) if do_distort_images: # We will be applying distortions, so setup the operations we'll need. (distorted_jpeg_data_tensor, distorted_image_tensor) = add_input_distortions( FLAGS.flip_left_right, FLAGS.random_crop, FLAGS.random_scale, FLAGS.random_brightness, model_info['input_width'], model_info['input_height'], model_info['input_depth'], model_info['input_mean'], model_info['input_std']) else: # We'll make sure we've calculated the 'bottleneck' image summaries and # cached them on disk. cache_bottlenecks(sess, image_lists, FLAGS.image_dir, FLAGS.bottleneck_dir, jpeg_data_tensor, decoded_image_tensor, resized_image_tensor, bottleneck_tensor, FLAGS.architecture) # Add the new layer that we'll be training. (train_step, total_loss, bottleneck_input, ground_truth_input, final_tensor) = add_final_training_ops( len(image_lists.keys()), get_numerical_labels(image_lists), FLAGS.final_tensor_name, bottleneck_tensor, model_info['bottleneck_tensor_size']) # Create the operations we need to evaluate the accuracy of our new layer. evaluation_step, prediction = add_evaluation_step( final_tensor, ground_truth_input) # Merge all the summaries and write them out to the summaries_dir merged = tf.summary.merge_all() train_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/train', sess.graph) validation_writer = tf.summary.FileWriter( FLAGS.summaries_dir + '/validation') # Set up all our weights to their initial default values. init = tf.global_variables_initializer() sess.run(init) # Run the training for as many cycles as requested on the command line. for i in range(FLAGS.how_many_training_steps): # Get a batch of input bottleneck values, either calculated fresh every # time with distortions applied, or from the cache stored on disk. if do_distort_images: (train_bottlenecks, train_ground_truth) = get_random_distorted_bottlenecks( sess, image_lists, FLAGS.train_batch_size, 'training', FLAGS.image_dir, distorted_jpeg_data_tensor, distorted_image_tensor, resized_image_tensor, bottleneck_tensor) else: (train_bottlenecks, train_ground_truth, _) = get_random_cached_bottlenecks( sess, image_lists, FLAGS.train_batch_size, 'training', FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor, decoded_image_tensor, resized_image_tensor, bottleneck_tensor, FLAGS.architecture) # Feed the bottlenecks and ground truth into the graph, and run a training # step. Capture training summaries for TensorBoard with the `merged` op. train_summary, _ = sess.run( [merged, train_step], feed_dict={bottleneck_input: train_bottlenecks, ground_truth_input: train_ground_truth}) train_writer.add_summary(train_summary, i) # Every so often, print out how well the graph is training. is_last_step = (i + 1 == FLAGS.how_many_training_steps) if (i % FLAGS.eval_step_interval) == 0 or is_last_step: train_accuracy, total_loss_values = sess.run( [evaluation_step, total_loss], feed_dict={bottleneck_input: train_bottlenecks, ground_truth_input: train_ground_truth}) tf.logging.info('%s: Step %d: Train accuracy = %.1f%%' % (datetime.now(), i, train_accuracy * 100)) tf.logging.info('%s: Step %d: Total loss = %f' % (datetime.now(), i, total_loss_values)) validation_bottlenecks, validation_ground_truth, _ = ( get_random_cached_bottlenecks( sess, image_lists, FLAGS.validation_batch_size, 'validation', FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor, decoded_image_tensor, resized_image_tensor, bottleneck_tensor, FLAGS.architecture)) # Run a validation step and capture training summaries for TensorBoard # with the `merged` op. validation_summary, validation_accuracy = sess.run( [merged, evaluation_step], feed_dict={bottleneck_input: validation_bottlenecks, ground_truth_input: validation_ground_truth}) validation_writer.add_summary(validation_summary, i) tf.logging.info('%s: Step %d: Validation accuracy = %.1f%% (N=%d)' % (datetime.now(), i, validation_accuracy * 100, len(validation_bottlenecks))) # Store intermediate results intermediate_frequency = FLAGS.intermediate_store_frequency if (intermediate_frequency > 0 and (i % intermediate_frequency == 0) and i > 0): intermediate_file_name = (FLAGS.intermediate_output_graphs_dir + 'intermediate_' + str(i) + '.pb') tf.logging.info('Save intermediate result to : ' + intermediate_file_name) save_graph_to_file(sess, graph, intermediate_file_name) # We've completed all our training, so run a final test evaluation on # some new images we haven't used before. if(FLAGS.testing_percentage > 0): test_bottlenecks, test_ground_truth, test_filenames = ( get_random_cached_bottlenecks( sess, image_lists, FLAGS.test_batch_size, 'testing', FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor, decoded_image_tensor, resized_image_tensor, bottleneck_tensor, FLAGS.architecture)) test_accuracy, predictions = sess.run( [evaluation_step, prediction], feed_dict={bottleneck_input: test_bottlenecks, ground_truth_input: test_ground_truth}) tf.logging.info('Final test accuracy = %.1f%% (N=%d)' % (test_accuracy * 100, len(test_bottlenecks))) if FLAGS.print_misclassified_test_images: tf.logging.info('=== MISCLASSIFIED TEST IMAGES ===') for i, test_filename in enumerate(test_filenames): if predictions[i] != test_ground_truth[i].argmax(): tf.logging.info('%70s %s' % (test_filename, list(image_lists.keys())[predictions[i]])) # Write out the trained graph and labels with the weights stored as # constants. save_graph_to_file(sess, graph, FLAGS.output_graph) with gfile.FastGFile(FLAGS.output_labels, 'w') as f: f.write('\n'.join(image_lists.keys()) + '\n') if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--image_dir', type=str, default='', help='Path to folders of labeled images.' ) parser.add_argument( '--output_graph', type=str, default='tmp/output_graph.pb', help='Where to save the trained graph.' ) parser.add_argument( '--intermediate_output_graphs_dir', type=str, default='', help='Where to save the intermediate graphs.' ) parser.add_argument( '--intermediate_store_frequency', type=int, default=0, help="""\ How many steps to store intermediate graph. If "0" then will not store.\ """ ) parser.add_argument( '--center_loss', default=False, help="""\ Use center loss along with softmax? """ ) parser.add_argument( '--output_labels', type=str, default='tmp/output_labels.txt', help='Where to save the trained graph\'s labels.' ) parser.add_argument( '--summaries_dir', type=str, default='tmp/retrain_logs', help='Where to save summary logs for TensorBoard.' ) parser.add_argument( '--how_many_training_steps', type=int, default=4000, help='How many training steps to run before ending.' ) parser.add_argument( '--learning_rate', type=float, default=0.01, help='How large a learning rate to use when training.' ) parser.add_argument( '--testing_percentage', type=int, default=10, help='What percentage of images to use as a test set.' ) parser.add_argument( '--validation_percentage', type=int, default=10, help='What percentage of images to use as a validation set.' ) parser.add_argument( '--eval_step_interval', type=int, default=10, help='How often to evaluate the training results.' ) parser.add_argument( '--train_batch_size', type=int, default=100, help='How many images to train on at a time.' ) parser.add_argument( '--test_batch_size', type=int, default=-1, help="""\ How many images to test on. This test set is only used once, to evaluate the final accuracy of the model after training completes. A value of -1 causes the entire test set to be used, which leads to more stable results across runs.\ """ ) parser.add_argument( '--validation_batch_size', type=int, default=100, help="""\ How many images to use in an evaluation batch. This validation set is used much more often than the test set, and is an early indicator of how accurate the model is during training. A value of -1 causes the entire validation set to be used, which leads to more stable results across training iterations, but may be slower on large training sets.\ """ ) parser.add_argument( '--print_misclassified_test_images', default=False, help="""\ Whether to print out a list of all misclassified test images.\ """, action='store_true' ) parser.add_argument( '--model_dir', type=str, default='tmp/imagenet', help="""\ Path to classify_image_graph_def.pb, imagenet_synset_to_human_label_map.txt, and imagenet_2012_challenge_label_map_proto.pbtxt.\ """ ) parser.add_argument( '--bottleneck_dir', type=str, default='tmp/bottleneck', help='Path to cache bottleneck layer values as files.' ) parser.add_argument( '--final_tensor_name', type=str, default='final_result', help="""\ The name of the output classification layer in the retrained graph.\ """ ) parser.add_argument( '--flip_left_right', default=False, help="""\ Whether to randomly flip half of the training images horizontally.\ """, action='store_true' ) parser.add_argument( '--random_crop', type=int, default=0, help="""\ A percentage determining how much of a margin to randomly crop off the training images.\ """ ) parser.add_argument( '--random_scale', type=int, default=0, help="""\ A percentage determining how much to randomly scale up the size of the training images by.\ """ ) parser.add_argument( '--random_brightness', type=int, default=0, help="""\ A percentage determining how much to randomly multiply the training image input pixels up or down by.\ """ ) parser.add_argument( '--center_loss_alpha', type=float, default=0, help="""\ A percentage determining how much to randomly multiply the training image input pixels up or down by.\ """ ) parser.add_argument( '--center_loss_factor', type=float, default=0, help="""\ A percentage determining how much to randomly multiply the training image input pixels up or down by.\ """ ) parser.add_argument( '--architecture', type=str, default='inception_v3', help="""\ Which model architecture to use. 'inception_v3' is the most accurate, but also the slowest. For faster or smaller models, chose a MobileNet with the form 'mobilenet_<parameter size>_<input_size>[_quantized]'. For example, 'mobilenet_1.0_224' will pick a model that is 17 MB in size and takes 224 pixel input images, while 'mobilenet_0.25_128_quantized' will choose a much less accurate, but smaller and faster network that's 920 KB on disk and takes 128x128 images. See https://research.googleblog.com/2017/06/mobilenets-open-source-models-for.html for more information on Mobilenet.\ """) FLAGS, unparsed = parser.parse_known_args() tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
mit
LANGFAN/APM
libraries/AP_InertialSensor/examples/coning.py
241
10508
#!/usr/bin/python from math import * from pymavlink.rotmat import Vector3, Matrix3 from numpy import linspace from visual import * class Quat: def __init__(self,w=1.0,x=0.0,y=0.0,z=0.0): self.w = w self.x = x self.y = y self.z = z def to_euler(self): roll = (atan2(2.0*(self.w*self.x + self.y*self.z), 1 - 2.0*(self.x*self.x + self.y*self.y))) pitch = asin(2.0*(self.w*self.y - self.z*self.x)) yaw = atan2(2.0*(self.w*self.z + self.x*self.y), 1 - 2.0*(self.y*self.y + self.z*self.z)) return Vector3(roll,pitch,yaw) def from_euler(self,euler): #(roll,pitch,yaw) cr2 = cos(euler[0]*0.5) cp2 = cos(euler[1]*0.5) cy2 = cos(euler[2]*0.5) sr2 = sin(euler[0]*0.5) sp2 = sin(euler[1]*0.5) sy2 = sin(euler[2]*0.5) self.w = cr2*cp2*cy2 + sr2*sp2*sy2 self.x = sr2*cp2*cy2 - cr2*sp2*sy2 self.y = cr2*sp2*cy2 + sr2*cp2*sy2 self.z = cr2*cp2*sy2 - sr2*sp2*cy2 return self def from_axis_angle(self, vec): theta = vec.length() if theta == 0: self.w = 1.0 self.x = 0.0 self.y = 0.0 self.z = 0.0 return vec_normalized = vec.normalized() st2 = sin(theta/2.0) self.w = cos(theta/2.0) self.x = vec_normalized.x * st2 self.y = vec_normalized.y * st2 self.z = vec_normalized.z * st2 def rotate(self, vec): r = Quat() r.from_axis_angle(vec) q = self * r self.w = q.w self.x = q.x self.y = q.y self.z = q.z def to_axis_angle(self): l = sqrt(self.x**2+self.y**2+self.z**2) (x,y,z) = (self.x,self.y,self.z) if l != 0: temp = 2.0*atan2(l,self.w) if temp > pi: temp -= 2*pi elif temp < -pi: temp += 2*pi (x,y,z) = (temp*x/l,temp*y/l,temp*z/l) return Vector3(x,y,z) def to_rotation_matrix(self): m = Matrix3() yy = self.y**2 yz = self.y * self.z xx = self.x**2 xy = self.x * self.y xz = self.x * self.z wx = self.w * self.x wy = self.w * self.y wz = self.w * self.z zz = self.z**2 m.a.x = 1.0-2.0*(yy + zz) m.a.y = 2.0*(xy - wz) m.a.z = 2.0*(xz + wy) m.b.x = 2.0*(xy + wz) m.b.y = 1.0-2.0*(xx + zz) m.b.z = 2.0*(yz - wx) m.c.x = 2.0*(xz - wy) m.c.y = 2.0*(yz + wx) m.c.z = 1.0-2.0*(xx + yy) return m def inverse(self): return Quat(self.w,-self.x,-self.y,-self.z) def __mul__(self,operand): ret = Quat() w1=self.w x1=self.x y1=self.y z1=self.z w2=operand.w x2=operand.x y2=operand.y z2=operand.z ret.w = w1*w2 - x1*x2 - y1*y2 - z1*z2 ret.x = w1*x2 + x1*w2 + y1*z2 - z1*y2 ret.y = w1*y2 - x1*z2 + y1*w2 + z1*x2 ret.z = w1*z2 + x1*y2 - y1*x2 + z1*w2 return ret def __str__(self): return "Quat(%f, %f, %f, %f)" % (self.w,self.x,self.y,self.z) def vpy_vec(vec): return vector(vec.y, -vec.z, -vec.x) def update_arrows(q,x,y,z): m = q.to_rotation_matrix().transposed() x.axis = vpy_vec(m*Vector3(1,0,0)) x.up = vpy_vec(m*Vector3(0,1,0)) y.axis = vpy_vec(m*Vector3(0,1,0)) y.up = vpy_vec(m*Vector3(1,0,0)) z.axis = vpy_vec(m*Vector3(0,0,1)) z.up = vpy_vec(m*Vector3(1,0,0)) class Attitude: def __init__(self,reference=False): self.labels = [] self.xarrows = [] self.yarrows = [] self.zarrows = [] self.q = Quat() self.reference = reference self.update_arrows() def add_arrows(self, arrowpos = Vector3(0,0,0), labeltext=None): if labeltext is not None: self.labels.append(label(pos = vpy_vec(arrowpos), text=labeltext)) sw = .005 if self.reference else .05 self.xarrows.append(arrow(pos=vpy_vec(arrowpos),color=color.red,opacity=1,shaftwidth=sw)) self.yarrows.append(arrow(pos=vpy_vec(arrowpos),color=color.green,opacity=1,shaftwidth=sw)) self.zarrows.append(arrow(pos=vpy_vec(arrowpos),color=color.blue,opacity=1,shaftwidth=sw)) self.update_arrows() def rotate(self, vec): self.q.rotate(vec) def update_arrows(self): m = self.q.to_rotation_matrix().transposed() sl = 1.1 if self.reference else 1.0 for i in self.xarrows: i.axis = vpy_vec(m*Vector3(sl,0,0)) i.up = vpy_vec(m*Vector3(0,1,0)) for i in self.yarrows: i.axis = vpy_vec(m*Vector3(0,sl,0)) i.up = vpy_vec(m*Vector3(1,0,0)) for i in self.zarrows: i.axis = vpy_vec(m*Vector3(0,0,sl)) i.up = vpy_vec(m*Vector3(1,0,0)) for i in self.labels: i.xoffset = scene.width*0.07 i.yoffset = scene.width*0.1 class Tian_integrator: def __init__(self, integrate_separately=True): self.alpha = Vector3(0,0,0) self.beta = Vector3(0,0,0) self.last_alpha = Vector3(0,0,0) self.last_delta_alpha = Vector3(0,0,0) self.last_sample = Vector3(0,0,0) self.integrate_separately = integrate_separately def add_sample(self, sample, dt): delta_alpha = (self.last_sample+sample)*0.5*dt self.alpha += delta_alpha delta_beta = 0.5 * (self.last_alpha + (1.0/6.0)*self.last_delta_alpha)%delta_alpha if self.integrate_separately: self.beta += delta_beta else: self.alpha += delta_beta self.last_alpha = self.alpha self.last_delta_alpha = delta_alpha self.last_sample = sample def pop_delta_angles(self): ret = self.alpha + self.beta self.alpha.zero() self.beta.zero() return ret filter2p_1khz_30hz_data = {} def filter2p_1khz_30hz(sample, key): global filter2p_1khz_30hz_data if not key in filter2p_1khz_30hz_data: filter2p_1khz_30hz_data[key] = (0.0,0.0) (delay_element_1, delay_element_2) = filter2p_1khz_30hz_data[key] sample_freq = 1000 cutoff_freq = 30 fr = sample_freq/cutoff_freq ohm = tan(pi/fr) c = 1.0+2.0*cos(pi/4.0)*ohm + ohm**2 b0 = ohm**2/c b1 = 2.0*b0 b2 = b0 a1 = 2.0*(ohm**2-1.0)/c a2 = (1.0-2.0*cos(pi/4.0)*ohm+ohm**2)/c delay_element_0 = sample - delay_element_1 * a1 - delay_element_2 * a2 output = delay_element_0 * b0 + delay_element_1 * b1 + delay_element_2 * b2 filter2p_1khz_30hz_data[key] = (delay_element_0, delay_element_1) return output def filter2p_1khz_30hz_vector3(sample, key): ret = Vector3() ret.x = filter2p_1khz_30hz(sample.x, "vec3f"+key+"x") ret.y = filter2p_1khz_30hz(sample.y, "vec3f"+key+"y") ret.z = filter2p_1khz_30hz(sample.z, "vec3f"+key+"z") return ret reference_attitude = Attitude(True) uncorrected_attitude_low = Attitude() uncorrected_attitude_high = Attitude() corrected_attitude = Attitude() corrected_attitude_combined = Attitude() corrected_attitude_integrator = Tian_integrator() corrected_attitude_integrator_combined = Tian_integrator(integrate_separately = False) reference_attitude.add_arrows(Vector3(0,-3,0)) uncorrected_attitude_low.add_arrows(Vector3(0,-3,0), "no correction\nlow rate integration\n30hz software LPF @ 1khz\n(ardupilot 2015-02-18)") reference_attitude.add_arrows(Vector3(0,-1,0)) uncorrected_attitude_high.add_arrows(Vector3(0,-1,0), "no correction\nhigh rate integration") reference_attitude.add_arrows(Vector3(0,1,0)) corrected_attitude.add_arrows(Vector3(0,1,0), "Tian et al\nseparate integration") reference_attitude.add_arrows(Vector3(0,3,0)) corrected_attitude_combined.add_arrows(Vector3(0,3,0), "Tian et al\ncombined_integration\n(proposed patch)") #scene.scale = (0.3,0.3,0.3) scene.fov = 0.001 scene.forward = (-0.5, -0.5, -1) coning_frequency_hz = 50 coning_magnitude_rad_s = 2 label_text = ( "coning motion frequency %f hz\n" "coning motion peak amplitude %f deg/s\n" "thin arrows are reference attitude" ) % (coning_frequency_hz, degrees(coning_magnitude_rad_s)) label(pos = vpy_vec(Vector3(0,0,2)), text=label_text) t = 0.0 dt_10000 = 0.0001 dt_1000 = 0.001 dt_333 = 0.003 accumulated_delta_angle = Vector3(0,0,0) last_gyro_10000 = Vector3(0,0,0) last_gyro_1000 = Vector3(0,0,0) last_filtered_gyro_333 = Vector3(0,0,0) filtered_gyro = Vector3(0,0,0) while True: rate(66) for i in range(5): for j in range(3): for k in range(10): #vvvvvvvvvv 10 kHz vvvvvvvvvv# #compute angular rate at current time gyro = Vector3(sin(t*coning_frequency_hz*2*pi), cos(t*coning_frequency_hz*2*pi),0)*coning_magnitude_rad_s #integrate reference attitude reference_attitude.rotate((gyro+last_gyro_10000) * dt_10000 * 0.5) #increment time t += dt_10000 last_gyro_10000 = gyro #vvvvvvvvvv 1 kHz vvvvvvvvvv# #update filter for sim 1 filtered_gyro = filter2p_1khz_30hz_vector3(gyro, "1") #update integrator for sim 2 accumulated_delta_angle += (gyro+last_gyro_1000) * dt_1000 * 0.5 #update integrator for sim 3 corrected_attitude_integrator.add_sample(gyro, dt_1000) #update integrator for sim 4 corrected_attitude_integrator_combined.add_sample(gyro, dt_1000) last_gyro_1000 = gyro #vvvvvvvvvv 333 Hz vvvvvvvvvv# #update sim 1 (leftmost) uncorrected_attitude_low.rotate((filtered_gyro+last_filtered_gyro_333) * dt_333 * 0.5) #update sim 2 uncorrected_attitude_high.rotate(accumulated_delta_angle) accumulated_delta_angle.zero() #update sim 3 corrected_attitude.rotate(corrected_attitude_integrator.pop_delta_angles()) #update sim 4 (rightmost) corrected_attitude_combined.rotate(corrected_attitude_integrator_combined.pop_delta_angles()) last_filtered_gyro_333 = filtered_gyro #vvvvvvvvvv 66 Hz vvvvvvvvvv# reference_attitude.update_arrows() corrected_attitude.update_arrows() corrected_attitude_combined.update_arrows() uncorrected_attitude_low.update_arrows() uncorrected_attitude_high.update_arrows()
gpl-3.0