code
stringlengths
2
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.core.backends.chrome import timeline_recorder from telemetry.timeline import inspector_timeline_data class TabBackendException(Exception): """An exception which indicates an error response from devtools inspector.""" pass class InspectorTimeline(timeline_recorder.TimelineRecorder): """Implementation of dev tools timeline.""" class Recorder(object): """Utility class to Start and Stop recording timeline. Example usage: with inspector_timeline.InspectorTimeline.Recorder(tab): # Something to run while the timeline is recording. This is an alternative to directly calling the Start and Stop methods below. """ def __init__(self, tab): self._tab = tab def __enter__(self): self._tab.StartTimelineRecording() def __exit__(self, *args): self._tab.StopTimelineRecording() def __init__(self, inspector_backend): super(InspectorTimeline, self).__init__() self._inspector_backend = inspector_backend self._is_recording = False @property def is_timeline_recording_running(self): return self._is_recording def Start(self): """Starts recording.""" assert not self._is_recording, 'Start should only be called once.' self._is_recording = True self._inspector_backend.RegisterDomain( 'Timeline', self._OnNotification, self._OnClose) # The 'bufferEvents' parameter below means that events should not be sent # individually as messages, but instead all at once when a Timeline.stop # request is sent. request = { 'method': 'Timeline.start', 'params': {'bufferEvents': True}, } self._SendSyncRequest(request) def Stop(self): """Stops recording and returns timeline event data.""" if not self._is_recording: return None request = {'method': 'Timeline.stop'} result = self._SendSyncRequest(request) self._inspector_backend.UnregisterDomain('Timeline') self._is_recording = False raw_events = result['events'] return inspector_timeline_data.InspectorTimelineData(raw_events) def _SendSyncRequest(self, request, timeout=60): """Sends a devtools remote debugging protocol request. The types of request that are valid is determined by protocol.json: https://src.chromium.org/viewvc/blink/trunk/Source/devtools/protocol.json Args: request: Request dict, may contain the keys 'method' and 'params'. timeout: Number of seconds to wait for a response. Returns: The result given in the response message. Raises: TabBackendException: The response indicates an error occurred. """ response = self._inspector_backend.SyncRequest(request, timeout) if 'error' in response: raise TabBackendException(response['error']['message']) return response['result'] def _OnNotification(self, msg): """Handler called when a message is received.""" # Since 'Timeline.start' was invoked with the 'bufferEvents' parameter, # there will be no timeline notifications while recording. pass def _OnClose(self): """Handler called when a domain is unregistered.""" pass
TeamEOS/external_chromium_org
tools/telemetry/telemetry/core/backends/chrome/inspector_timeline.py
Python
bsd-3-clause
3,318
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Test cases for bounce message generation """ from twisted.trial import unittest from twisted.mail import bounce import cStringIO import email.message import email.parser class BounceTests(unittest.TestCase): """ testcases for bounce message generation """ def testBounceFormat(self): from_, to, s = bounce.generateBounce(cStringIO.StringIO('''\ From: Moshe Zadka <moshez@example.com> To: nonexistent@example.org Subject: test '''), 'moshez@example.com', 'nonexistent@example.org') self.assertEqual(from_, '') self.assertEqual(to, 'moshez@example.com') emailParser = email.parser.Parser() mess = emailParser.parse(cStringIO.StringIO(s)) self.assertEqual(mess['To'], 'moshez@example.com') self.assertEqual(mess['From'], 'postmaster@example.org') self.assertEqual(mess['subject'], 'Returned Mail: see transcript for details') def testBounceMIME(self): pass
EricMuller/mynotes-backend
requirements/twisted/Twisted-17.1.0/src/twisted/mail/test/test_bounce.py
Python
mit
1,029
import urllib from askbot.deps.django_authopenid.util import OAuthConnection class Twitter(OAuthConnection): def __init__(self): super(Twitter, self).__init__('twitter') self.tweet_url = 'https://api.twitter.com/1.1/statuses/update.json' def tweet(self, text, access_token=None): client = self.get_client(access_token) body = urllib.urlencode({'status': text}) return self.send_request(client, self.tweet_url, 'POST', body=body)
PearsonIOKI/compose-forum
askbot/utils/twitter.py
Python
gpl-3.0
479
from django.db import models # Django doesn't support big auto fields out of the box, see # https://code.djangoproject.com/ticket/14286. # This is a stripped down version of the BoundedBigAutoField from Sentry. class BigAutoField(models.AutoField): description = "Big Integer" def db_type(self, connection): engine = connection.settings_dict['ENGINE'] if 'mysql' in engine: return "bigint AUTO_INCREMENT" elif 'postgres' in engine: return "bigserial" else: raise NotImplemented def get_related_db_type(self, connection): return models.BigIntegerField().db_type(connection) def get_internal_type(self): return "BigIntegerField" class FlexibleForeignKey(models.ForeignKey): def db_type(self, connection): # This is required to support BigAutoField rel_field = self.related_field if hasattr(rel_field, 'get_related_db_type'): return rel_field.get_related_db_type(connection) return super(FlexibleForeignKey, self).db_type(connection)
adusca/treeherder
treeherder/model/fields.py
Python
mpl-2.0
1,086
"""Support for sending data to Emoncms.""" import logging from datetime import timedelta import requests import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.const import ( CONF_API_KEY, CONF_WHITELIST, CONF_URL, STATE_UNKNOWN, STATE_UNAVAILABLE, CONF_SCAN_INTERVAL) from homeassistant.helpers import state as state_helper from homeassistant.helpers.event import track_point_in_time from homeassistant.util import dt as dt_util _LOGGER = logging.getLogger(__name__) DOMAIN = 'emoncms_history' CONF_INPUTNODE = 'inputnode' CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Required(CONF_API_KEY): cv.string, vol.Required(CONF_URL): cv.string, vol.Required(CONF_INPUTNODE): cv.positive_int, vol.Required(CONF_WHITELIST): cv.entity_ids, vol.Optional(CONF_SCAN_INTERVAL, default=30): cv.positive_int, }), }, extra=vol.ALLOW_EXTRA) def setup(hass, config): """Set up the Emoncms history component.""" conf = config[DOMAIN] whitelist = conf.get(CONF_WHITELIST) def send_data(url, apikey, node, payload): """Send payload data to Emoncms.""" try: fullurl = '{}/input/post.json'.format(url) data = {"apikey": apikey, "data": payload} parameters = {"node": node} req = requests.post( fullurl, params=parameters, data=data, allow_redirects=True, timeout=5) except requests.exceptions.RequestException: _LOGGER.error("Error saving data '%s' to '%s'", payload, fullurl) else: if req.status_code != 200: _LOGGER.error( "Error saving data %s to %s (http status code = %d)", payload, fullurl, req.status_code) def update_emoncms(time): """Send whitelisted entities states regularly to Emoncms.""" payload_dict = {} for entity_id in whitelist: state = hass.states.get(entity_id) if state is None or state.state in ( STATE_UNKNOWN, '', STATE_UNAVAILABLE): continue try: payload_dict[entity_id] = state_helper.state_as_number(state) except ValueError: continue if payload_dict: payload = "{%s}" % ",".join("{}:{}".format(key, val) for key, val in payload_dict.items()) send_data(conf.get(CONF_URL), conf.get(CONF_API_KEY), str(conf.get(CONF_INPUTNODE)), payload) track_point_in_time(hass, update_emoncms, time + timedelta(seconds=conf.get(CONF_SCAN_INTERVAL))) update_emoncms(dt_util.utcnow()) return True
MartinHjelmare/home-assistant
homeassistant/components/emoncms_history/__init__.py
Python
apache-2.0
2,839
# # 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. # """Add standard attribute table Revision ID: 32e5974ada25 Revises: 13cfb89f881a Create Date: 2015-09-10 00:22:47.618593 """ # revision identifiers, used by Alembic. revision = '32e5974ada25' down_revision = '13cfb89f881a' from alembic import op import sqlalchemy as sa TABLES = ('ports', 'networks', 'subnets', 'subnetpools', 'securitygroups', 'floatingips', 'routers', 'securitygrouprules') def upgrade(): op.create_table( 'standardattributes', sa.Column('id', sa.BigInteger(), autoincrement=True), sa.Column('resource_type', sa.String(length=255), nullable=False), sa.PrimaryKeyConstraint('id') ) for table in TABLES: op.add_column(table, sa.Column('standard_attr_id', sa.BigInteger(), nullable=True))
dims/neutron
neutron/db/migration/alembic_migrations/versions/mitaka/expand/32e5974ada25_add_neutron_resources_table.py
Python
apache-2.0
1,390
""" Boolean geometry difference of solids. """ from __future__ import absolute_import #Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module. import __init__ from fabmetheus_utilities.geometry.geometry_utilities import boolean_solid from fabmetheus_utilities.geometry.geometry_utilities import evaluate from fabmetheus_utilities.geometry.solids import group __author__ = 'Enrique Perez (perez_enrique@yahoo.com)' __credits__ = 'Nophead <http://hydraraptor.blogspot.com/>\nArt of Illusion <http://www.artofillusion.org/>' __date__ = '$Date: 2008/21/04 $' __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' def convertElementNode(elementNode, geometryOutput): "Convert the xml element to a difference xml element." group.convertContainerElementNode(elementNode, geometryOutput, Difference()) def getNewDerivation(elementNode): 'Get new derivation.' return evaluate.EmptyObject(elementNode) def processElementNode(elementNode): "Process the xml element." evaluate.processArchivable(Difference, elementNode) class Difference( boolean_solid.BooleanSolid ): "A difference object." def getLoopsFromObjectLoopsList(self, importRadius, visibleObjectLoopsList): "Get loops from visible object loops list." return self.getDifference(importRadius, visibleObjectLoopsList) def getXMLLocalName(self): "Get xml class name." return self.__class__.__name__.lower()
dob71/x2swn
skeinforge/fabmetheus_utilities/geometry/solids/difference.py
Python
gpl-3.0
1,517
# *************************************************************************** # * Copyright (c) 2017 Markus Hovorka <m.hovorka@live.de> * # * Copyright (c) 2020 Bernd Hahnebach <bernd@bimstatik.org> * # * * # * This file is part of the FreeCAD CAx development system. * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * 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 Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library 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 * # * * # *************************************************************************** __title__ = "FreeCAD FEM constraint electrostatic potential document object" __author__ = "Markus Hovorka, Bernd Hahnebach" __url__ = "https://www.freecadweb.org" ## @package constraint_electrostaticpotential # \ingroup FEM # \brief constraint electrostatic potential object from . import base_fempythonobject class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject): Type = "Fem::ConstraintElectrostaticPotential" def __init__(self, obj): super(ConstraintElectrostaticPotential, self).__init__(obj) self.add_properties(obj) def onDocumentRestored(self, obj): self.add_properties(obj) def add_properties(self, obj): if not hasattr(obj, "Potential"): obj.addProperty( "App::PropertyFloat", "Potential", "Parameter", "Potential" ), obj.Potential = 0.0 if not hasattr(obj, "PotentialEnabled"): obj.addProperty( "App::PropertyBool", "PotentialEnabled", "Parameter", "Potential Enabled" ), obj.PotentialEnabled = False if not hasattr(obj, "PotentialConstant"): obj.addProperty( "App::PropertyBool", "PotentialConstant", "Parameter", "Potential Constant" ), obj.PotentialConstant = False if not hasattr(obj, "ElectricInfinity"): obj.addProperty( "App::PropertyBool", "ElectricInfinity", "Parameter", "Electric Infinity" ), obj.ElectricInfinity = False if not hasattr(obj, "ElectricForcecalculation"): obj.addProperty( "App::PropertyBool", "ElectricForcecalculation", "Parameter", "Electric Force Calculation" ), obj.ElectricForcecalculation = False if not hasattr(obj, "CapacitanceBody"): obj.addProperty( "App::PropertyInteger", "CapacitanceBody", "Parameter", "Capacitance Body" ), obj.CapacitanceBody = 0 if not hasattr(obj, "CapacitanceBodyEnabled"): obj.addProperty( "App::PropertyBool", "CapacitanceBodyEnabled", "Parameter", "Capacitance Body Enabled" ) obj.CapacitanceBodyEnabled = False
sanguinariojoe/FreeCAD
src/Mod/Fem/femobjects/constraint_electrostaticpotential.py
Python
lgpl-2.1
4,421
try: import os, gettext locale_dir = os.path.split(__file__)[0] gettext.install('4Suite', locale_dir) except (ImportError,AttributeError,IOError): def _(msg): return msg SYNTAX_ERR_MSG = _("Error parsing expression:\n'%s'\nSyntax error at or near '%s' Line: %d") INTERNAL_ERR_MSG = _("Error parsing expression:\n'%s'\nInternal error in processing at or near '%s', Line: %d, Exception: %s") class SyntaxException(Exception): def __init__(self, source, lineNum, location): Exception.__init__(self, SYNTAX_ERR_MSG%(source, location, lineNum)) self.source = source self.lineNum = lineNum self.loc = location class InternalException(Exception): def __init__(self, source, lineNum, location, exc, val, tb): Exception.__init__(self, INTERNAL_ERR_MSG%(source, location, lineNum, exc)) self.source = source self.lineNum = lineNum self.loc = location self.errorType = exc self.errorValue = val self.errorTraceback = tb class XPathParserBase: def __init__(self): self.initialize() def initialize(self): self.results = None self.__stack = [] XPath.cvar.g_errorOccured = 0 def parse(self,st): g_parseLock.acquire() try: self.initialize() XPath.my_XPathparse(self,st) if XPath.cvar.g_errorOccured == 1: raise SyntaxException( st, XPath.cvar.lineNum, XPath.cvar.g_errorLocation) if XPath.cvar.g_errorOccured == 2: raise InternalException( st, XPath.cvar.lineNum, XPath.cvar.g_errorLocation, XPath.cvar.g_errorType, XPath.cvar.g_errorValue, XPath.cvar.g_errorTraceback) return self.__stack finally: g_parseLock.release() def pop(self): if len(self.__stack): rt = self.__stack[-1] del self.__stack[-1] return rt self.raiseException("Pop with 0 stack length") def push(self,item): self.__stack.append(item) def empty(self): return len(self.__stack) == 0 def size(self): return len(self.__stack) def raiseException(self, message): raise Exception(message) ### Callback methods ### def PrintSyntaxException(e): print "********** Syntax Exception **********" print "Exception at or near '%s'" % e.loc print " Line: %d" % (e.lineNum) def PrintInternalException(e): print "********** Internal Exception **********" print "Exception at or near '%s'" % e.loc print " Line: %d" % (e.lineNum) print " Exception: %s" % e.errorType print "Original traceback:" import traceback traceback.print_tb(e.errorTraceback)
selfcommit/gaedav
pyxml/xpath/XPathParserBase.py
Python
lgpl-2.1
2,924
########################################################################## # # Copyright (c) 2008, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # * Neither the name of Image Engine Design nor the names of any # other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import maya.cmds import IECore import IECoreMaya class TestPluginLoadUnload( IECoreMaya.TestCase ) : def test( self ): """ Test loading/unloading of plugin """ # Plugin should be loaded by MayaUnitTest.TestProgram when we get here self.assert_( maya.cmds.pluginInfo( "ieCore", query = True, loaded = True ) ) for i in range( 0, 20 ) : self.failIf( maya.cmds.pluginInfo( "ieCore", query = True, serviceDescriptions = True ) ) maya.cmds.unloadPlugin( "ieCore" ) self.failIf( maya.cmds.pluginInfo( "ieCore", query = True, loaded = True ) ) maya.cmds.loadPlugin( "ieCore" ) self.assert_( maya.cmds.pluginInfo( "ieCore", query = True, loaded = True ) ) self.assert_( maya.cmds.pluginInfo( "ieCore", query = True, loaded = True ) ) def tearDown( self ): if not maya.cmds.pluginInfo( "ieCore", query = True, loaded = True ) : maya.cmds.loadPlugin( "ieCore" ) # Make sure plugin is definitely loaded when we exit tests assert( maya.cmds.pluginInfo( "ieCore", query = True, loaded = True ) ) if __name__ == "__main__": IECoreMaya.TestProgram()
lento/cortex
test/IECoreMaya/PluginLoadUnload.py
Python
bsd-3-clause
2,870
import json import traceback from couchpotato.core._base.downloader.main import DownloaderBase from couchpotato.core.helpers.encoding import isInt from couchpotato.core.helpers.variable import cleanHost from couchpotato.core.logger import CPLog import requests log = CPLog(__name__) autoload = 'Synology' class Synology(DownloaderBase): protocol = ['nzb', 'torrent', 'torrent_magnet'] status_support = False def download(self, data = None, media = None, filedata = None): """ Send a torrent/nzb file to the downloader :param data: dict returned from provider Contains the release information :param media: media dict with information Used for creating the filename when possible :param filedata: downloaded torrent/nzb filedata The file gets downloaded in the searcher and send to this function This is done to have fail checking before using the downloader, so the downloader doesn't need to worry about that :return: boolean One fail returns false, but the downloader should log his own errors """ if not media: media = {} if not data: data = {} response = False log.info('Sending "%s" (%s) to Synology.', (data['name'], data['protocol'])) # Load host from config and split out port. host = cleanHost(self.conf('host'), protocol = False).split(':') if not isInt(host[1]): log.error('Config properties are not filled in correctly, port is missing.') return False try: # Send request to Synology srpc = SynologyRPC(host[0], host[1], self.conf('username'), self.conf('password'), self.conf('destination')) if data['protocol'] == 'torrent_magnet': log.info('Adding torrent URL %s', data['url']) response = srpc.create_task(url = data['url']) elif data['protocol'] in ['nzb', 'torrent']: log.info('Adding %s' % data['protocol']) if not filedata: log.error('No %s data found', data['protocol']) else: filename = data['name'] + '.' + data['protocol'] response = srpc.create_task(filename = filename, filedata = filedata) except: log.error('Exception while adding torrent: %s', traceback.format_exc()) finally: return self.downloadReturnId('') if response else False def test(self): """ Check if connection works :return: bool """ host = cleanHost(self.conf('host'), protocol = False).split(':') try: srpc = SynologyRPC(host[0], host[1], self.conf('username'), self.conf('password')) test_result = srpc.test() except: return False return test_result def getEnabledProtocol(self): if self.conf('use_for') == 'both': return super(Synology, self).getEnabledProtocol() elif self.conf('use_for') == 'torrent': return ['torrent', 'torrent_magnet'] else: return ['nzb'] def isEnabled(self, manual = False, data = None): if not data: data = {} for_protocol = ['both'] if data and 'torrent' in data.get('protocol'): for_protocol.append('torrent') elif data: for_protocol.append(data.get('protocol')) return super(Synology, self).isEnabled(manual, data) and\ ((self.conf('use_for') in for_protocol)) class SynologyRPC(object): """SynologyRPC lite library""" def __init__(self, host = 'localhost', port = 5000, username = None, password = None, destination = None): super(SynologyRPC, self).__init__() self.download_url = 'http://%s:%s/webapi/DownloadStation/task.cgi' % (host, port) self.auth_url = 'http://%s:%s/webapi/auth.cgi' % (host, port) self.sid = None self.username = username self.password = password self.destination = destination self.session_name = 'DownloadStation' def _login(self): if self.username and self.password: args = {'api': 'SYNO.API.Auth', 'account': self.username, 'passwd': self.password, 'version': 2, 'method': 'login', 'session': self.session_name, 'format': 'sid'} response = self._req(self.auth_url, args) if response['success']: self.sid = response['data']['sid'] log.debug('sid=%s', self.sid) else: log.error('Couldn\'t log into Synology, %s', response) return response['success'] else: log.error('User or password missing, not using authentication.') return False def _logout(self): args = {'api':'SYNO.API.Auth', 'version':1, 'method':'logout', 'session':self.session_name, '_sid':self.sid} return self._req(self.auth_url, args) def _req(self, url, args, files = None): response = {'success': False} try: req = requests.post(url, data = args, files = files, verify = False) req.raise_for_status() response = json.loads(req.text) if response['success']: log.info('Synology action successfull') return response except requests.ConnectionError as err: log.error('Synology connection error, check your config %s', err) except requests.HTTPError as err: log.error('SynologyRPC HTTPError: %s', err) except Exception as err: log.error('Exception: %s', err) finally: return response def create_task(self, url = None, filename = None, filedata = None): """ Creates new download task in Synology DownloadStation. Either specify url or pair (filename, filedata). Returns True if task was created, False otherwise """ result = False # login if self._login(): args = {'api': 'SYNO.DownloadStation.Task', 'version': '1', 'method': 'create', '_sid': self.sid} if self.destination and len(self.destination) > 0: args['destination'] = self.destination if url: log.info('Login success, adding torrent URI') args['uri'] = url response = self._req(self.download_url, args = args) if response['success']: log.info('Response: %s', response) else: log.error('Response: %s', response) synoerrortype = { 400 : 'File upload failed', 401 : 'Max number of tasks reached', 402 : 'Destination denied', 403 : 'Destination does not exist', 404 : 'Invalid task id', 405 : 'Invalid task action', 406 : 'No default destination', 407 : 'Set destination failed', 408 : 'File does not exist' } log.error('DownloadStation returned the following error : %s', synoerrortype[response['error']['code']]) result = response['success'] elif filename and filedata: log.info('Login success, adding torrent') files = {'file': (filename, filedata)} response = self._req(self.download_url, args = args, files = files) log.info('Response: %s', response) result = response['success'] else: log.error('Invalid use of SynologyRPC.create_task: either url or filename+filedata must be specified') self._logout() return result def test(self): return bool(self._login()) config = [{ 'name': 'synology', 'groups': [ { 'tab': 'downloaders', 'list': 'download_providers', 'name': 'synology', 'label': 'Synology', 'description': 'Use <a href="https://www.synology.com/en-us/dsm/app_packages/DownloadStation" target="_blank">Synology Download Station</a> to download.', 'wizard': True, 'options': [ { 'name': 'enabled', 'default': 0, 'type': 'enabler', 'radio_group': 'nzb,torrent', }, { 'name': 'host', 'default': 'localhost:5000', 'description': 'Hostname with port. Usually <strong>localhost:5000</strong>', }, { 'name': 'username', }, { 'name': 'password', 'type': 'password', }, { 'name': 'destination', 'description': 'Specify <strong>existing</strong> destination share to where your files will be downloaded, usually <strong>Downloads</strong>', 'advanced': True, }, { 'name': 'use_for', 'label': 'Use for', 'default': 'both', 'type': 'dropdown', 'values': [('usenet & torrents', 'both'), ('usenet', 'nzb'), ('torrent', 'torrent')], }, { 'name': 'manual', 'default': 0, 'type': 'bool', 'advanced': True, 'description': 'Disable this downloader for automated searches, but use it when I manually send a release.', }, ], } ], }]
loulich/Couchpotato
couchpotato/core/downloaders/synology.py
Python
gpl-3.0
10,004
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for parser module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import textwrap from tensorflow.contrib.autograph.pyct import parser from tensorflow.python.platform import test class ParserTest(test.TestCase): def test_parse_entity(self): def f(x): return x + 1 mod, _ = parser.parse_entity(f) self.assertEqual('f', mod.body[0].name) def test_parse_str(self): mod = parser.parse_str( textwrap.dedent(""" def f(x): return x + 1 """)) self.assertEqual('f', mod.body[0].name) def test_parse_expression(self): node = parser.parse_expression('a.b') self.assertEqual('a', node.value.id) self.assertEqual('b', node.attr) if __name__ == '__main__': test.main()
nburn42/tensorflow
tensorflow/contrib/autograph/pyct/parser_test.py
Python
apache-2.0
1,514
#!/usr/bin/env python3 import subprocess as sp def main(args): with open(args.disk, 'rb') as f: f.seek(args.block * args.block_size) block = (f.read(args.block_size) .ljust(args.block_size, b'\xff')) # what did you expect? print("%-8s %-s" % ('off', 'data')) return sp.run(['xxd', '-g1', '-'], input=block).returncode if __name__ == "__main__": import argparse import sys parser = argparse.ArgumentParser( description="Hex dump a specific block in a disk.") parser.add_argument('disk', help="File representing the block device.") parser.add_argument('block_size', type=lambda x: int(x, 0), help="Size of a block in bytes.") parser.add_argument('block', type=lambda x: int(x, 0), help="Address of block to dump.") sys.exit(main(parser.parse_args()))
adfernandes/mbed
storage/filesystem/littlefsv2/littlefs/scripts/readblock.py
Python
apache-2.0
858
# # Copyright 2015 Google 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. """Generated message classes for fusiontables version v1. API for working with Fusion Tables data. """ # NOTE: This file is autogenerated and should not be edited by hand. from apitools.base.protorpclite import messages as _messages package = 'fusiontables' class Column(_messages.Message): """Specifies the id, name and type of a column in a table. Messages: BaseColumnValue: Optional identifier of the base column. If present, this column is derived from the specified base column. Fields: baseColumn: Optional identifier of the base column. If present, this column is derived from the specified base column. columnId: Identifier for the column. description: Optional column description. graph_predicate: Optional column predicate. Used to map table to graph data model (subject,predicate,object) See http://www.w3.org/TR/2014/REC- rdf11-concepts-20140225/#data-model kind: Type name: a template for an individual column. name: Required name of the column. type: Required type of the column. """ class BaseColumnValue(_messages.Message): """Optional identifier of the base column. If present, this column is derived from the specified base column. Fields: columnId: The id of the column in the base table from which this column is derived. tableIndex: Offset to the entry in the list of base tables in the table definition. """ columnId = _messages.IntegerField(1, variant=_messages.Variant.INT32) tableIndex = _messages.IntegerField(2, variant=_messages.Variant.INT32) baseColumn = _messages.MessageField('BaseColumnValue', 1) columnId = _messages.IntegerField(2, variant=_messages.Variant.INT32) description = _messages.StringField(3) graph_predicate = _messages.StringField(4) kind = _messages.StringField(5, default=u'fusiontables#column') name = _messages.StringField(6) type = _messages.StringField(7) class ColumnList(_messages.Message): """Represents a list of columns in a table. Fields: items: List of all requested columns. kind: Type name: a list of all columns. nextPageToken: Token used to access the next page of this result. No token is displayed if there are no more pages left. totalItems: Total number of columns for the table. """ items = _messages.MessageField('Column', 1, repeated=True) kind = _messages.StringField(2, default=u'fusiontables#columnList') nextPageToken = _messages.StringField(3) totalItems = _messages.IntegerField(4, variant=_messages.Variant.INT32) class FusiontablesColumnListRequest(_messages.Message): """A FusiontablesColumnListRequest object. Fields: maxResults: Maximum number of columns to return. Optional. Default is 5. pageToken: Continuation token specifying which result page to return. Optional. tableId: Table whose columns are being listed. """ maxResults = _messages.IntegerField(1, variant=_messages.Variant.UINT32) pageToken = _messages.StringField(2) tableId = _messages.StringField(3, required=True) class FusiontablesColumnListAlternateRequest(_messages.Message): """A FusiontablesColumnListRequest object. Fields: pageSize: Maximum number of columns to return. Optional. Default is 5. pageToken: Continuation token specifying which result page to return. Optional. tableId: Table whose columns are being listed. """ pageSize = _messages.IntegerField(1, variant=_messages.Variant.UINT32) pageToken = _messages.StringField(2) tableId = _messages.StringField(3, required=True) class ColumnListAlternate(_messages.Message): """Represents a list of columns in a table. Fields: items: List of all requested columns. kind: Type name: a list of all columns. nextPageToken: Token used to access the next page of this result. No token is displayed if there are no more pages left. totalItems: Total number of columns for the table. """ columns = _messages.MessageField('Column', 1, repeated=True) kind = _messages.StringField(2, default=u'fusiontables#columnList') nextPageToken = _messages.StringField(3) totalItems = _messages.IntegerField(4, variant=_messages.Variant.INT32)
catapult-project/catapult-csm
third_party/google-endpoints/apitools/base/py/testing/testclient/fusiontables_v1_messages.py
Python
bsd-3-clause
4,998
from crits.vocabulary.vocab import vocab class RelationshipTypes(vocab): """ Vocabulary for Relationship Types. """ COMPRESSED_FROM = "Compressed From" COMPRESSED_INTO = "Compressed Into" CONNECTED_FROM = "Connected From" CONNECTED_TO = "Connected To" CONTAINS = "Contains" CONTAINED_WITHIN = "Contained Within" CREATED = "Created" CREATED_BY = "Created By" DECODED = "Decoded" DECODED_BY = "Decoded By" DECRYPTED = "Decrypted" DECRYPTED_BY = "Decrypted By" DOWNLOADED = "Downloaded" DOWNLOADED_BY = "Downloaded By" DOWNLOADED_FROM = "Downloaded From" DOWNLOADED_TO = "Downloaded To" DROPPED = "Dropped" DROPPED_BY = "Dropped By" INSTALLED = "Installed" INSTALLED_BY = "Installed By" LOADED_FROM = "Loaded From" LOADED_INTO = "Loaded Into" PACKED_FROM = "Packed From" PACKED_INTO = "Packed Into" RECEIVED_FROM = "Received From" SENT_TO = "Sent To" REGISTERED = "Registered" REGISTERED_TO = "Registered To" RELATED_TO = "Related To" RESOLVED_TO = "Resolved To" SENT = "Sent" SENT_BY = "Sent By" SUB_DOMAIN_OF = "Sub-domain Of" SUPRA_DOMAIN_OF = "Supra-domain Of" @classmethod def inverse(cls, relationship=None): """ Return the inverse relationship of the provided relationship. :param relationship: The relationship to get the inverse of. :type relationship: str :returns: str or None """ if relationship is None: return None if relationship == cls.COMPRESSED_FROM: return cls.COMPRESSED_INTO elif relationship == cls.COMPRESSED_INTO: return cls.COMPRESSED_FROM elif relationship == cls.CONNECTED_FROM: return cls.CONNECTED_TO elif relationship == cls.CONNECTED_TO: return cls.CONNECTED_FROM elif relationship == cls.CONTAINS: return cls.CONTAINED_WITHIN elif relationship == cls.CONTAINED_WITHIN: return cls.CONTAINS elif relationship == cls.CREATED: return cls.CREATED_BY elif relationship == cls.CREATED_BY: return cls.CREATED elif relationship == cls.DECODED: return cls.DECODED_BY elif relationship == cls.DECODED_BY: return cls.DECODED elif relationship == cls.DECRYPTED: return cls.DECRYPTED_BY elif relationship == cls.DECRYPTED_BY: return cls.DECRYPTED elif relationship == cls.DOWNLOADED: return cls.DOWNLOADED_BY elif relationship == cls.DOWNLOADED_BY: return cls.DOWNLOADED elif relationship == cls.DOWNLOADED_FROM: return cls.DOWNLOADED_TO elif relationship == cls.DOWNLOADED_TO: return cls.DOWNLOADED_FROM elif relationship == cls.DROPPED: return cls.DROPPED_BY elif relationship == cls.DROPPED_BY: return cls.DROPPED elif relationship == cls.INSTALLED: return cls.INSTALLED_BY elif relationship == cls.INSTALLED_BY: return cls.INSTALLED elif relationship == cls.LOADED_FROM: return cls.LOADED_INTO elif relationship == cls.LOADED_INTO: return cls.LOADED_FROM elif relationship == cls.PACKED_FROM: return cls.PACKED_INTO elif relationship == cls.PACKED_INTO: return cls.PACKED_FROM elif relationship == cls.RECEIVED_FROM: return cls.SENT_TO elif relationship == cls.SENT_TO: return cls.RECEIVED_FROM elif relationship == cls.REGISTERED: return cls.REGISTERED_TO elif relationship == cls.REGISTERED_TO: return cls.REGISTERED elif relationship == cls.RELATED_TO: return cls.RELATED_TO elif relationship == cls.RESOLVED_TO: return cls.RESOLVED_TO elif relationship == cls.SENT: return cls.SENT_BY elif relationship == cls.SENT_BY: return cls.SENT elif relationship == cls.SUB_DOMAIN_OF: return cls.SUPRA_DOMAIN_OF elif relationship == cls.SUPRA_DOMAIN_OF: return cls.SUB_DOMAIN_OF else: return None
ckane/crits
crits/vocabulary/relationships.py
Python
mit
4,362
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class RequestHeaders(object): '''A custom dictionary impementation for headers which ignores the case of requests, since different HTTP libraries seem to mangle them. ''' def __init__(self, dict_): if isinstance(dict_, RequestHeaders): self._dict = dict_ else: self._dict = dict((k.lower(), v) for k, v in dict_.iteritems()) def get(self, key, default=None): return self._dict.get(key.lower(), default) def __repr__(self): return repr(self._dict) def __str__(self): return repr(self._dict) class Request(object): '''Request data. ''' def __init__(self, path, host, headers): self.path = path.lstrip('/') self.host = host.rstrip('/') self.headers = RequestHeaders(headers) @staticmethod def ForTest(path, host=None, headers=None): return Request(path, host or 'http://developer.chrome.com', headers or {}) def __repr__(self): return 'Request(path=%s, host=%s, headers=%s)' % ( self.path, self.host, self.headers) def __str__(self): return repr(self) class _ContentBuilder(object): '''Builds the response content. ''' def __init__(self): self._buf = [] def Append(self, content): if isinstance(content, unicode): content = content.encode('utf-8', 'replace') self._buf.append(content) def ToString(self): self._Collapse() return self._buf[0] def __str__(self): return self.ToString() def __len__(self): return len(self.ToString()) def _Collapse(self): self._buf = [''.join(self._buf)] class Response(object): '''The response from Get(). ''' def __init__(self, content=None, headers=None, status=None): self.content = _ContentBuilder() if content is not None: self.content.Append(content) self.headers = {} if headers is not None: self.headers.update(headers) self.status = status @staticmethod def Ok(content, headers=None): '''Returns an OK (200) response. ''' return Response(content=content, headers=headers, status=200) @staticmethod def Redirect(url, permanent=False): '''Returns a redirect (301 or 302) response. ''' status = 301 if permanent else 302 return Response(headers={'Location': url}, status=status) @staticmethod def NotFound(content, headers=None): '''Returns a not found (404) response. ''' return Response(content=content, headers=headers, status=404) @staticmethod def NotModified(content, headers=None): return Response(content=content, headers=headers, status=304) @staticmethod def InternalError(content, headers=None): '''Returns an internal error (500) response. ''' return Response(content=content, headers=headers, status=500) def Append(self, content): '''Appends |content| to the response content. ''' self.content.append(content) def AddHeader(self, key, value): '''Adds a header to the response. ''' self.headers[key] = value def AddHeaders(self, headers): '''Adds several headers to the response. ''' self.headers.update(headers) def SetStatus(self, status): self.status = status def GetRedirect(self): if self.headers.get('Location') is None: return (None, None) return (self.headers.get('Location'), self.status == 301) def IsNotFound(self): return self.status == 404 def __eq__(self, other): return (isinstance(other, self.__class__) and str(other.content) == str(self.content) and other.headers == self.headers and other.status == self.status) def __ne__(self, other): return not (self == other) def __repr__(self): return 'Response(content=%s bytes, status=%s, headers=%s)' % ( len(self.content), self.status, self.headers) def __str__(self): return repr(self) class Servlet(object): def __init__(self, request): self._request = request def Get(self): '''Returns a Response. ''' raise NotImplemented()
7kbird/chrome
chrome/common/extensions/docs/server2/servlet.py
Python
bsd-3-clause
4,151
from cStringIO import StringIO import unittest import unittest2 from unittest2.test.support import resultFactory class TestUnittest(unittest2.TestCase): def assertIsSubclass(self, actual, klass): self.assertTrue(issubclass(actual, klass), "Not a subclass.") def testInheritance(self): self.assertIsSubclass(unittest2.TestCase, unittest.TestCase) self.assertIsSubclass(unittest2.TestResult, unittest.TestResult) self.assertIsSubclass(unittest2.TestSuite, unittest.TestSuite) self.assertIsSubclass( unittest2.TextTestRunner, unittest.TextTestRunner) self.assertIsSubclass(unittest2.TestLoader, unittest.TestLoader) self.assertIsSubclass(unittest2.TextTestResult, unittest.TestResult) def test_new_runner_old_case(self): runner = unittest2.TextTestRunner(resultclass=resultFactory, stream=StringIO()) class Test(unittest.TestCase): def testOne(self): pass suite = unittest2.TestSuite((Test('testOne'),)) result = runner.run(suite) self.assertEqual(result.testsRun, 1) self.assertEqual(len(result.errors), 0) def test_old_runner_new_case(self): runner = unittest.TextTestRunner(stream=StringIO()) class Test(unittest2.TestCase): def testOne(self): self.assertDictEqual({}, {}) suite = unittest.TestSuite((Test('testOne'),)) result = runner.run(suite) self.assertEqual(result.testsRun, 1) self.assertEqual(len(result.errors), 0) if __name__ == '__main__': unittest2.main()
endlessm/chromium-browser
third_party/llvm/lldb/third_party/Python/module/unittest2/unittest2/test/test_new_tests.py
Python
bsd-3-clause
1,677
# Copyright 2013 The Servo Project Developers. See the COPYRIGHT # file at the top-level directory of this distribution. # # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your # option. This file may not be copied, modified, or distributed # except according to those terms. # These licenses are valid for use in Servo licenses = [ """\ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ """, """\ # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. """, """\ // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. """, """\ // Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. """, """\ # Copyright 2013 The Servo Project Developers. See the COPYRIGHT # file at the top-level directory of this distribution. # # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your # option. This file may not be copied, modified, or distributed # except according to those terms. """, ]
chotchki/servo
python/licenseck.py
Python
mpl-2.0
1,985
# Authors: Gilles Louppe, Mathieu Blondel, Maheshakya Wijewardena # License: BSD 3 clause import numpy as np from .base import SelectorMixin from ..base import BaseEstimator, clone from ..externals import six from ..exceptions import NotFittedError from ..utils.fixes import norm def _get_feature_importances(estimator, norm_order=1): """Retrieve or aggregate feature importances from estimator""" importances = getattr(estimator, "feature_importances_", None) if importances is None and hasattr(estimator, "coef_"): if estimator.coef_.ndim == 1: importances = np.abs(estimator.coef_) else: importances = norm(estimator.coef_, axis=0, ord=norm_order) elif importances is None: raise ValueError( "The underlying estimator %s has no `coef_` or " "`feature_importances_` attribute. Either pass a fitted estimator" " to SelectFromModel or call fit before calling transform." % estimator.__class__.__name__) return importances def _calculate_threshold(estimator, importances, threshold): """Interpret the threshold value""" if threshold is None: # determine default from estimator est_name = estimator.__class__.__name__ if ((hasattr(estimator, "penalty") and estimator.penalty == "l1") or "Lasso" in est_name): # the natural default threshold is 0 when l1 penalty was used threshold = 1e-5 else: threshold = "mean" if isinstance(threshold, six.string_types): if "*" in threshold: scale, reference = threshold.split("*") scale = float(scale.strip()) reference = reference.strip() if reference == "median": reference = np.median(importances) elif reference == "mean": reference = np.mean(importances) else: raise ValueError("Unknown reference: " + reference) threshold = scale * reference elif threshold == "median": threshold = np.median(importances) elif threshold == "mean": threshold = np.mean(importances) else: raise ValueError("Expected threshold='mean' or threshold='median' " "got %s" % threshold) else: threshold = float(threshold) return threshold class SelectFromModel(BaseEstimator, SelectorMixin): """Meta-transformer for selecting features based on importance weights. .. versionadded:: 0.17 Parameters ---------- estimator : object The base estimator from which the transformer is built. This can be both a fitted (if ``prefit`` is set to True) or a non-fitted estimator. threshold : string, float, optional default None The threshold value to use for feature selection. Features whose importance is greater or equal are kept while the others are discarded. If "median" (resp. "mean"), then the ``threshold`` value is the median (resp. the mean) of the feature importances. A scaling factor (e.g., "1.25*mean") may also be used. If None and if the estimator has a parameter penalty set to l1, either explicitly or implicitly (e.g, Lasso), the threshold used is 1e-5. Otherwise, "mean" is used by default. prefit : bool, default False Whether a prefit model is expected to be passed into the constructor directly or not. If True, ``transform`` must be called directly and SelectFromModel cannot be used with ``cross_val_score``, ``GridSearchCV`` and similar utilities that clone the estimator. Otherwise train the model using ``fit`` and then ``transform`` to do feature selection. norm_order : non-zero int, inf, -inf, default 1 Order of the norm used to filter the vectors of coefficients below ``threshold`` in the case where the ``coef_`` attribute of the estimator is of dimension 2. Attributes ---------- estimator_ : an estimator The base estimator from which the transformer is built. This is stored only when a non-fitted estimator is passed to the ``SelectFromModel``, i.e when prefit is False. threshold_ : float The threshold value used for feature selection. """ def __init__(self, estimator, threshold=None, prefit=False, norm_order=1): self.estimator = estimator self.threshold = threshold self.prefit = prefit self.norm_order = norm_order def _get_support_mask(self): # SelectFromModel can directly call on transform. if self.prefit: estimator = self.estimator elif hasattr(self, 'estimator_'): estimator = self.estimator_ else: raise ValueError( 'Either fit the model before transform or set "prefit=True"' ' while passing the fitted estimator to the constructor.') scores = _get_feature_importances(estimator, self.norm_order) self.threshold_ = _calculate_threshold(estimator, scores, self.threshold) return scores >= self.threshold_ def fit(self, X, y=None, **fit_params): """Fit the SelectFromModel meta-transformer. Parameters ---------- X : array-like of shape (n_samples, n_features) The training input samples. y : array-like, shape (n_samples,) The target values (integers that correspond to classes in classification, real numbers in regression). **fit_params : Other estimator specific parameters Returns ------- self : object Returns self. """ if self.prefit: raise NotFittedError( "Since 'prefit=True', call transform directly") self.estimator_ = clone(self.estimator) self.estimator_.fit(X, y, **fit_params) return self def partial_fit(self, X, y=None, **fit_params): """Fit the SelectFromModel meta-transformer only once. Parameters ---------- X : array-like of shape (n_samples, n_features) The training input samples. y : array-like, shape (n_samples,) The target values (integers that correspond to classes in classification, real numbers in regression). **fit_params : Other estimator specific parameters Returns ------- self : object Returns self. """ if self.prefit: raise NotFittedError( "Since 'prefit=True', call transform directly") if not hasattr(self, "estimator_"): self.estimator_ = clone(self.estimator) self.estimator_.partial_fit(X, y, **fit_params) return self
pprett/scikit-learn
sklearn/feature_selection/from_model.py
Python
bsd-3-clause
6,968
#!/usr/bin/env python # -*- coding=utf-8 -*- import sys import re import os import argparse import requests from lxml import html as lxml_html try: import html except ImportError: import HTMLParser html = HTMLParser.HTMLParser() try: import cPickle as pk except ImportError: import pickle as pk class LeetcodeProblems(object): def get_problems_info(self): leetcode_url = 'https://leetcode.com/problemset/algorithms' res = requests.get(leetcode_url) if not res.ok: print('request error') sys.exit() cm = res.text cmt = cm.split('tbody>')[-2] indexs = re.findall(r'<td>(\d+)</td>', cmt) problem_urls = ['https://leetcode.com' + url \ for url in re.findall( r'<a href="(/problems/.+?)"', cmt)] levels = re.findall(r"<td value='\d*'>(.+?)</td>", cmt) tinfos = zip(indexs, levels, problem_urls) assert (len(indexs) == len(problem_urls) == len(levels)) infos = [] for info in tinfos: res = requests.get(info[-1]) if not res.ok: print('request error') sys.exit() tree = lxml_html.fromstring(res.text) title = tree.xpath('//meta[@property="og:title"]/@content')[0] description = tree.xpath('//meta[@property="description"]/@content') if not description: description = tree.xpath('//meta[@property="og:description"]/@content')[0] else: description = description[0] description = html.unescape(description.strip()) tags = tree.xpath('//div[@id="tags"]/following::a[@class="btn btn-xs btn-primary"]/text()') infos.append( { 'title': title, 'level': info[1], 'index': int(info[0]), 'description': description, 'tags': tags } ) with open('leecode_problems.pk', 'wb') as g: pk.dump(infos, g) return infos def to_text(self, pm_infos): if self.args.index: key = 'index' elif self.args.title: key = 'title' elif self.args.tag: key = 'tags' elif self.args.level: key = 'level' else: key = 'index' infos = sorted(pm_infos, key=lambda i: i[key]) text_template = '## {index} - {title}\n' \ '~{level}~ {tags}\n' \ '{description}\n' + '\n' * self.args.line text = '' for info in infos: if self.args.rm_blank: info['description'] = re.sub(r'[\n\r]+', r'\n', info['description']) text += text_template.format(**info) with open('leecode problems.txt', 'w') as g: g.write(text) def run(self): if os.path.exists('leecode_problems.pk') and not self.args.redownload: with open('leecode_problems.pk', 'rb') as f: pm_infos = pk.load(f) else: pm_infos = self.get_problems_info() print('find %s problems.' % len(pm_infos)) self.to_text(pm_infos) def handle_args(argv): p = argparse.ArgumentParser(description='extract all leecode problems to location') p.add_argument('--index', action='store_true', help='sort by index') p.add_argument('--level', action='store_true', help='sort by level') p.add_argument('--tag', action='store_true', help='sort by tag') p.add_argument('--title', action='store_true', help='sort by title') p.add_argument('--rm_blank', action='store_true', help='remove blank') p.add_argument('--line', action='store', type=int, default=10, help='blank of two problems') p.add_argument('-r', '--redownload', action='store_true', help='redownload data') args = p.parse_args(argv[1:]) return args def main(argv): args = handle_args(argv) x = LeetcodeProblems() x.args = args x.run() if __name__ == '__main__': argv = sys.argv main(argv)
RadonX/iScript
leetcode_problems.py
Python
mit
4,146
KEYIDS = { "KEY_RESERVED": 0, "KEY_ESC": 1, "KEY_1": 2, "KEY_2": 3, "KEY_3": 4, "KEY_4": 5, "KEY_5": 6, "KEY_6": 7, "KEY_7": 8, "KEY_8": 9, "KEY_9": 10, "KEY_0": 11, "KEY_MINUS": 12, "KEY_EQUAL": 13, "KEY_BACKSPACE": 14, "KEY_TAB": 15, "KEY_Q": 16, "KEY_W": 17, "KEY_E": 18, "KEY_R": 19, "KEY_T": 20, "KEY_Y": 21, "KEY_U": 22, "KEY_I": 23, "KEY_O": 24, "KEY_P": 25, "KEY_LEFTBRACE": 26, "KEY_RIGHTBRACE": 27, "KEY_ENTER": 28, "KEY_LEFTCTRL": 29, "KEY_A": 30, "KEY_S": 31, "KEY_D": 32, "KEY_F": 33, "KEY_G": 34, "KEY_H": 35, "KEY_J": 36, "KEY_K": 37, "KEY_L": 38, "KEY_SEMICOLON": 39, "KEY_APOSTROPHE": 40, "KEY_GRAVE": 41, "KEY_LEFTSHIFT": 42, "KEY_BACKSLASH": 43, "KEY_Z": 44, "KEY_X": 45, "KEY_C": 46, "KEY_V": 47, "KEY_B": 48, "KEY_N": 49, "KEY_M": 50, "KEY_COMMA": 51, "KEY_DOT": 52, "KEY_SLASH": 53, "KEY_RIGHTSHIFT": 54, "KEY_KPASTERISK": 55, "KEY_LEFTALT": 56, "KEY_SPACE": 57, "KEY_CAPSLOCK": 58, "KEY_F1": 59, "KEY_F2": 60, "KEY_F3": 61, "KEY_F4": 62, "KEY_F5": 63, "KEY_F6": 64, "KEY_F7": 65, "KEY_F8": 66, "KEY_F9": 67, "KEY_F10": 68, "KEY_NUMLOCK": 69, "KEY_SCROLLLOCK": 70, "KEY_KP7": 71, "KEY_KP8": 72, "KEY_KP9": 73, "KEY_KPMINUS": 74, "KEY_KP4": 75, "KEY_KP5": 76, "KEY_KP6": 77, "KEY_KPPLUS": 78, "KEY_KP1": 79, "KEY_KP2": 80, "KEY_KP3": 81, "KEY_KP0": 82, "KEY_KPDOT": 83, "KEY_103RD": 84, "KEY_F13": 85, "KEY_102ND": 86, "KEY_F11": 87, "KEY_F12": 88, "KEY_F14": 89, "KEY_F15": 90, "KEY_F16": 91, "KEY_F17": 92, "KEY_F18": 93, "KEY_F19": 94, "KEY_F20": 95, "KEY_KPENTER": 96, "KEY_RIGHTCTRL": 97, "KEY_KPSLASH": 98, "KEY_SYSRQ": 99, "KEY_RIGHTALT": 100, "KEY_LINEFEED": 101, "KEY_HOME": 102, "KEY_UP": 103, "KEY_PAGEUP": 104, "KEY_LEFT": 105, "KEY_RIGHT": 106, "KEY_END": 107, "KEY_DOWN": 108, "KEY_PAGEDOWN": 109, "KEY_INSERT": 110, "KEY_DELETE": 111, "KEY_MACRO": 112, "KEY_MUTE": 113, "KEY_VOLUMEDOWN": 114, "KEY_VOLUMEUP": 115, "KEY_POWER": 116, "KEY_KPEQUAL": 117, "KEY_KPPLUSMINUS": 118, "KEY_PAUSE": 119, "KEY_F21": 120, "KEY_F22": 121, "KEY_F23": 122, "KEY_F24": 123, "KEY_KPCOMMA": 124, "KEY_LEFTMETA": 125, "KEY_RIGHTMETA": 126, "KEY_COMPOSE": 127, "KEY_STOP": 128, "KEY_AGAIN": 129, "KEY_PROPS": 130, "KEY_UNDO": 131, "KEY_FRONT": 132, "KEY_COPY": 133, "KEY_OPEN": 134, "KEY_PASTE": 135, "KEY_FIND": 136, "KEY_CUT": 137, "KEY_HELP": 138, "KEY_MENU": 139, "KEY_CALC": 140, "KEY_SETUP": 141, "KEY_SLEEP": 142, "KEY_WAKEUP": 143, "KEY_FILE": 144, "KEY_SENDFILE": 145, "KEY_DELETEFILE": 146, "KEY_XFER": 147, "KEY_PROG1": 148, "KEY_PROG2": 149, "KEY_WWW": 150, "KEY_MSDOS": 151, "KEY_COFFEE": 152, "KEY_DIRECTION": 153, "KEY_CYCLEWINDOWS": 154, "KEY_MAIL": 155, "KEY_BOOKMARKS": 156, "KEY_COMPUTER": 157, "KEY_BACK": 158, "KEY_FORWARD": 159, "KEY_CLOSECD": 160, "KEY_EJECTCD": 161, "KEY_EJECTCLOSECD": 162, "KEY_NEXTSONG": 163, "KEY_PLAYPAUSE": 164, "KEY_PREVIOUSSONG": 165, "KEY_STOPCD": 166, "KEY_RECORD": 167, "KEY_REWIND": 168, "KEY_PHONE": 169, "KEY_ISO": 170, "KEY_CONFIG": 171, "KEY_HOMEPAGE": 172, "KEY_REFRESH": 173, "KEY_EXIT": 174, "KEY_MOVE": 175, "KEY_EDIT": 176, "KEY_SCROLLUP": 177, "KEY_SCROLLDOWN": 178, "KEY_KPLEFTPAREN": 179, "KEY_KPRIGHTPAREN": 180, "KEY_INTL1": 181, "KEY_INTL2": 182, "KEY_INTL3": 183, "KEY_INTL4": 184, "KEY_INTL5": 185, "KEY_INTL6": 186, "KEY_INTL7": 187, "KEY_INTL8": 188, "KEY_INTL9": 189, "KEY_LANG1": 190, "KEY_LANG2": 191, "KEY_LANG3": 192, "KEY_LANG4": 193, "KEY_LANG5": 194, "KEY_LANG6": 195, "KEY_LANG7": 196, "KEY_LANG8": 197, "KEY_LANG9": 198, "KEY_PLAYCD": 200, "KEY_PAUSECD": 201, "KEY_PROG3": 202, "KEY_PROG4": 203, "KEY_SUSPEND": 205, "KEY_CLOSE": 206, "KEY_PLAY": 207, "KEY_FASTFORWARD": 208, "KEY_BASSBOOST": 209, "KEY_PRINT": 210, "KEY_HP": 211, "KEY_CAMERA": 212, "KEY_SOUND": 213, "KEY_QUESTION": 214, "KEY_EMAIL": 215, "KEY_CHAT": 216, "KEY_SEARCH": 217, "KEY_CONNECT": 218, "KEY_FINANCE": 219, "KEY_SPORT": 220, "KEY_SHOP": 221, "KEY_ALTERASE": 222, "KEY_CANCEL": 223, "KEY_BRIGHTNESSDOWN": 224, "KEY_BRIGHTNESSUP": 225, "KEY_MEDIA": 226, "KEY_VMODE": 227, "KEY_LAN": 238, "KEY_UNKNOWN": 240, "BtnA": 304, "BtnY": 308, "BtnB": 305, "BtnX": 307, "BtnTL": 310, "BtnTR": 311, "KEY_OK": 352, "KEY_SELECT": 353, "KEY_GOTO": 354, "KEY_CLEAR": 355, "KEY_POWER2": 356, "KEY_OPTION": 357, "KEY_INFO": 358, "KEY_TIME": 359, "KEY_VENDOR": 360, "KEY_ARCHIVE": 361, "KEY_PROGRAM": 362, "KEY_CHANNEL": 363, "KEY_FAVORITES": 364, "KEY_EPG": 365, "KEY_PVR": 366, "KEY_MHP": 367, "KEY_LANGUAGE": 368, "KEY_TITLE": 369, "KEY_SUBTITLE": 370, "KEY_ANGLE": 371, "KEY_ZOOM": 372, "KEY_MODE": 373, "KEY_KEYBOARD": 374, "KEY_SCREEN": 375, "KEY_PC": 376, "KEY_TV": 377, "KEY_TV2": 378, "KEY_VCR": 379, "KEY_VCR2": 380, "KEY_SAT": 381, "KEY_SAT2": 382, "KEY_CD": 383, "KEY_TAPE": 384, "KEY_RADIO": 385, "KEY_TUNER": 386, "KEY_PLAYER": 387, "KEY_TEXT": 388, "KEY_DVD": 389, "KEY_AUX": 390, "KEY_MP3": 391, "KEY_AUDIO": 392, "KEY_VIDEO": 393, "KEY_DIRECTORY": 394, "KEY_LIST": 395, "KEY_MEMO": 396, "KEY_CALENDAR": 397, "KEY_RED": 398, "KEY_GREEN": 399, "KEY_YELLOW": 400, "KEY_BLUE": 401, "KEY_CHANNELUP": 402, "KEY_CHANNELDOWN": 403, "KEY_FIRST": 404, "KEY_LAST": 405, "KEY_AB": 406, "KEY_NEXT": 407, "KEY_RESTART": 408, "KEY_SLOW": 409, "KEY_SHUFFLE": 410, "KEY_BREAK": 411, "KEY_PREVIOUS": 412, "KEY_DIGITS": 413, "KEY_TEEN": 414, "KEY_TWEN": 415, "KEY_CONTEXT_MENU": 438, "KEY_DEL_EOL": 448, "KEY_DEL_EOS": 449, "KEY_INS_LINE": 450, "KEY_DEL_LINE": 451, "KEY_ASCII": 510, "KEY_MAX": 511, "BTN_0": 256, "BTN_1": 257, }
openhdf/enigma2-wetek
keyids.py
Python
gpl-2.0
5,381
# -*- coding: utf-8 -*- from __future__ import unicode_literals from .. import Provider as PhoneNumberProvider class Provider(PhoneNumberProvider): phonenumber_prefixes = [134, 135, 136, 137, 138, 139, 147, 150, 151, 152, 157, 158, 159, 182, 187, 188, 130, 131, 132, 145, 155, 156, 185, 186, 145, 133, 153, 180, 181, 189] formats = [str(i) + "########" for i in phonenumber_prefixes] @classmethod def phonenumber_prefix(cls): return cls.random_element(cls.phonenumber_prefixes)
Nebucatnetzer/tamagotchi
pygame/lib/python3.4/site-packages/faker/providers/phone_number/zh_CN/__init__.py
Python
gpl-2.0
589
"""Test result object""" import os import sys import traceback from StringIO import StringIO from . import util from functools import wraps __unittest = True def failfast(method): @wraps(method) def inner(self, *args, **kw): if getattr(self, 'failfast', False): self.stop() return method(self, *args, **kw) return inner STDOUT_LINE = '\nStdout:\n%s' STDERR_LINE = '\nStderr:\n%s' class TestResult(object): """Holder for test result information. Test results are automatically managed by the TestCase and TestSuite classes, and do not need to be explicitly manipulated by writers of tests. Each instance holds the total number of tests run, and collections of failures and errors that occurred among those test runs. The collections contain tuples of (testcase, exceptioninfo), where exceptioninfo is the formatted traceback of the error that occurred. """ _previousTestClass = None _testRunEntered = False _moduleSetUpFailed = False def __init__(self, stream=None, descriptions=None, verbosity=None): self.failfast = False self.failures = [] self.errors = [] self.testsRun = 0 self.skipped = [] self.expectedFailures = [] self.unexpectedSuccesses = [] self.shouldStop = False self.buffer = False self._stdout_buffer = None self._stderr_buffer = None self._original_stdout = sys.stdout self._original_stderr = sys.stderr self._mirrorOutput = False def printErrors(self): "Called by TestRunner after test run" def startTest(self, test): "Called when the given test is about to be run" self.testsRun += 1 self._mirrorOutput = False self._setupStdout() def _setupStdout(self): if self.buffer: if self._stderr_buffer is None: self._stderr_buffer = StringIO() self._stdout_buffer = StringIO() sys.stdout = self._stdout_buffer sys.stderr = self._stderr_buffer def startTestRun(self): """Called once before any tests are executed. See startTest for a method called before each test. """ def stopTest(self, test): """Called when the given test has been run""" self._restoreStdout() self._mirrorOutput = False def _restoreStdout(self): if self.buffer: if self._mirrorOutput: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endswith('\n'): output += '\n' self._original_stdout.write(STDOUT_LINE % output) if error: if not error.endswith('\n'): error += '\n' self._original_stderr.write(STDERR_LINE % error) sys.stdout = self._original_stdout sys.stderr = self._original_stderr self._stdout_buffer.seek(0) self._stdout_buffer.truncate() self._stderr_buffer.seek(0) self._stderr_buffer.truncate() def stopTestRun(self): """Called once after all tests are executed. See stopTest for a method called after each test. """ @failfast def addError(self, test, err): """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). """ self.errors.append((test, self._exc_info_to_string(err, test))) self._mirrorOutput = True @failfast def addFailure(self, test, err): """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info().""" self.failures.append((test, self._exc_info_to_string(err, test))) self._mirrorOutput = True def addSuccess(self, test): "Called when a test has completed successfully" pass def addSkip(self, test, reason): """Called when a test is skipped.""" self.skipped.append((test, reason)) def addExpectedFailure(self, test, err): """Called when an expected failure/error occurred.""" self.expectedFailures.append( (test, self._exc_info_to_string(err, test))) @failfast def addUnexpectedSuccess(self, test): """Called when a test was expected to fail, but succeed.""" self.unexpectedSuccesses.append(test) def wasSuccessful(self): "Tells whether or not this result was a success" return len(self.failures) == len(self.errors) == 0 def stop(self): "Indicates that the tests should be aborted" self.shouldStop = True def _exc_info_to_string(self, err, test): """Converts a sys.exc_info()-style tuple of values into a string.""" exctype, value, tb = err # Skip test runner traceback levels while tb and self._is_relevant_tb_level(tb): tb = tb.tb_next if exctype is test.failureException: # Skip assert*() traceback levels length = self._count_relevant_tb_levels(tb) msgLines = traceback.format_exception(exctype, value, tb, length) else: msgLines = traceback.format_exception(exctype, value, tb) if self.buffer: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endswith('\n'): output += '\n' msgLines.append(STDOUT_LINE % output) if error: if not error.endswith('\n'): error += '\n' msgLines.append(STDERR_LINE % error) return ''.join(msgLines) def _is_relevant_tb_level(self, tb): return '__unittest' in tb.tb_frame.f_globals def _count_relevant_tb_levels(self, tb): length = 0 while tb and not self._is_relevant_tb_level(tb): length += 1 tb = tb.tb_next return length def __repr__(self): return ("<%s run=%i errors=%i failures=%i>" % (util.strclass(self.__class__), self.testsRun, len(self.errors), len(self.failures)))
HiSPARC/station-software
user/python/Lib/unittest/result.py
Python
gpl-3.0
6,308
from django.utils import timezone import pytest from django_bulk_update.helper import bulk_update from django.db.models import DateTimeField from osf_tests.factories import UserFactory, PreprintFactory, NodeFactory @pytest.mark.django_db class TestGuidAutoInclude: guid_factories = [ UserFactory, PreprintFactory, NodeFactory ] @pytest.mark.parametrize('Factory', guid_factories) def test_filter_object(self, Factory): obj = Factory() assert '__guids' in str(obj._meta.model.objects.filter(id=obj.id).query), 'Guids were not included in filter query for {}'.format(obj._meta.model.__name__) @pytest.mark.parametrize('Factory', guid_factories) @pytest.mark.django_assert_num_queries def test_all(self, Factory, django_assert_num_queries): for _ in range(0, 5): UserFactory() with django_assert_num_queries(1): wut = Factory._meta.model.objects.all() for x in wut: assert x._id is not None, 'Guid was None' @pytest.mark.parametrize('Factory', guid_factories) @pytest.mark.django_assert_num_queries def test_filter(self, Factory, django_assert_num_queries): objects = [] for _ in range(0, 5): objects.append(Factory()) new_ids = [o.id for o in objects] with django_assert_num_queries(1): wut = Factory._meta.model.objects.filter(id__in=new_ids) for x in wut: assert x._id is not None, 'Guid was None' @pytest.mark.parametrize('Factory', guid_factories) @pytest.mark.django_assert_num_queries def test_filter_order_by(self, Factory, django_assert_num_queries): objects = [] for _ in range(0, 5): objects.append(Factory()) new_ids = [o.id for o in objects] with django_assert_num_queries(1): wut = Factory._meta.model.objects.filter(id__in=new_ids).order_by('id') for x in wut: assert x._id is not None, 'Guid was None' @pytest.mark.parametrize('Factory', guid_factories) @pytest.mark.django_assert_num_queries def test_values(self, Factory, django_assert_num_queries): objects = [] for _ in range(0, 5): objects.append(Factory()) with django_assert_num_queries(1): wut = Factory._meta.model.objects.values('id') for x in wut: assert len(x) == 1, 'Too many keys in values' @pytest.mark.parametrize('Factory', guid_factories) @pytest.mark.django_assert_num_queries def test_exclude(self, Factory, django_assert_num_queries): objects = [] for _ in range(0, 5): objects.append(Factory()) try: dtfield = [x.name for x in objects[0]._meta.get_fields() if isinstance(x, DateTimeField)][0] except IndexError: pytest.skip('Thing doesn\'t have a DateTimeField') with django_assert_num_queries(1): wut = Factory._meta.model.objects.exclude(**{dtfield: timezone.now()}) for x in wut: assert x._id is not None, 'Guid was None' @pytest.mark.parametrize('Factory', guid_factories) def test_update_objects(self, Factory): objects = [] for _ in range(0, 5): objects.append(Factory()) new_ids = [o.id for o in objects] try: dtfield = [x.name for x in objects[0]._meta.get_fields() if isinstance(x, DateTimeField)][0] except IndexError: pytest.skip('Thing doesn\'t have a DateTimeField') qs = objects[0]._meta.model.objects.filter(id__in=new_ids) assert len(qs) > 0, 'No results returned' try: qs.update(**{dtfield: timezone.now()}) except Exception as ex: pytest.fail('Queryset update failed for {} with exception {}'.format(Factory._meta.model.__name__, ex)) @pytest.mark.parametrize('Factory', guid_factories) def test_update_on_objects_filtered_by_guids(self, Factory): objects = [] for _ in range(0, 5): objects.append(Factory()) new__ids = [o._id for o in objects] try: dtfield = [x.name for x in objects[0]._meta.get_fields() if isinstance(x, DateTimeField)][0] except IndexError: pytest.skip('Thing doesn\'t have a DateTimeField') qs = objects[0]._meta.model.objects.filter(guids___id__in=new__ids) assert len(qs) > 0, 'No results returned' try: qs.update(**{dtfield: timezone.now()}) except Exception as ex: pytest.fail('Queryset update failed for {} with exception {}'.format(Factory._meta.model.__name__, ex)) @pytest.mark.parametrize('Factory', guid_factories) @pytest.mark.django_assert_num_queries def test_related_manager(self, Factory, django_assert_num_queries): thing_with_contributors = Factory() if not hasattr(thing_with_contributors, 'contributors'): pytest.skip('Thing must have contributors') try: with django_assert_num_queries(1): [x._id for x in thing_with_contributors.contributors.all()] except Exception as ex: pytest.fail('Related manager failed for {} with exception {}'.format(Factory._meta.model.__name__, ex)) @pytest.mark.parametrize('Factory', guid_factories) @pytest.mark.django_assert_num_queries def test_count_objects(self, Factory, django_assert_num_queries): objects = [] for _ in range(0, 5): objects.append(Factory()) new_ids = [o.id for o in objects] with django_assert_num_queries(1): qs = objects[0]._meta.model.objects.filter(id__in=new_ids) count = qs.count() assert count == len(objects) @pytest.mark.parametrize('Factory', guid_factories) @pytest.mark.django_assert_num_queries def test_bulk_create_objects(self, Factory, django_assert_num_queries): objects = [] Model = Factory._meta.model kwargs = {} if Factory == PreprintFactory: # Don't try to save preprints on build when neither the subject nor provider have been saved kwargs['finish'] = False for _ in range(0, 5): objects.append(Factory.build(**kwargs)) with django_assert_num_queries(1): things = Model.objects.bulk_create(objects) assert len(things) == len(objects) @pytest.mark.parametrize('Factory', guid_factories) @pytest.mark.django_assert_num_queries def test_bulk_update_objects(self, Factory, django_assert_num_queries): objects = [] ids = range(0, 5) for id in ids: objects.append(Factory()) try: dtfield = [x.name for x in objects[0]._meta.get_fields() if isinstance(x, DateTimeField)][0] except IndexError: pytest.skip('Thing doesn\'t have a DateTimeField') for obj in objects: setattr(obj, dtfield, timezone.now()) with django_assert_num_queries(1): bulk_update(objects)
erinspace/osf.io
osf_tests/test_guid_auto_include.py
Python
apache-2.0
7,146
# 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. # ============================================================================== """Functional tests for quantized operations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.platform import test class QuantizedOpsTest(test.TestCase): def __init__(self, method_name="runTest"): super(QuantizedOpsTest, self).__init__(method_name) def testQuantizeOp(self): expected_output = [1, 1, 2, 127, 255, 255] with self.session(use_gpu=False) as sess: x = constant_op.constant( [1.0, 1.25, 1.75, 127.0, 255.0, 500.0], shape=[6], dtype=dtypes.float32) x_min = 0.0 x_max = 255.0 op = array_ops.quantize(x, x_min, x_max, dtypes.quint8, mode="MIN_FIRST") value = self.evaluate(op) self.assertArrayNear(expected_output, value.output, 0.1) def testDequantizeOp(self): expected_output = [1.0, 2.0, 4.0, 8.0, 16.0, 255.0] inp = np.array([1, 2, 4, 8, 16, 255]).astype(np.uint8) with self.session(use_gpu=False) as sess: x = constant_op.constant(inp, shape=[6], dtype=dtypes.quint8) x_min = 0.0 x_max = 255.0 op = array_ops.dequantize(x, x_min, x_max, mode="MIN_FIRST") value = self.evaluate(op) self.assertArrayNear(expected_output, value, 0.1) def testAxis(self): # Generates a tensor of the specified `shape` using values from `values` # scaled by (slice_idx + 1) along `axis` dimension. def scale_per_slice(shape, axis, values): # Note: repeats the values if the shape is larger than values. out = np.take(values, np.remainder(np.arange(np.prod(shape)), len(values))).reshape(shape) if axis is not None: scale_shape = [1] * len(shape) scale_shape[axis] = shape[axis] out *= np.arange(1, shape[axis] + 1).reshape(scale_shape) return out shape = np.array([2, 3, 4, 5]) values = np.array([-1, -0.5, 0, 0.3, 0.8, 0.555, 0.5], dtype=np.float32) quant_values = np.array([-128, -64, 0, 38, 102, 71, 64], dtype=np.int32) for axis in [None, 0, 1, 2, 3]: inputs = constant_op.constant(scale_per_slice(shape, axis, values)) expected_quantized = scale_per_slice(shape, None, quant_values) if axis is None: min_range, max_range = -1.0, 0.8 else: num_slices = shape[axis] min_range, max_range = [], [] for slice_idx in range(num_slices): min_range.append(-1.0 * (slice_idx + 1)) max_range.append(0.8 * (slice_idx + 1)) quantized = self.evaluate( array_ops.quantize( inputs, min_range, max_range, T=dtypes.qint8, mode="SCALED", round_mode="HALF_TO_EVEN", axis=axis)).output self.assertAllEqual(quantized, expected_quantized) if axis is not None: quantized = self.evaluate( array_ops.quantize( inputs, min_range, max_range, T=dtypes.qint8, mode="SCALED", round_mode="HALF_TO_EVEN", axis=(axis - 4))).output self.assertAllClose(quantized, expected_quantized) if __name__ == "__main__": test.main()
gunan/tensorflow
tensorflow/python/ops/quantized_ops_test.py
Python
apache-2.0
4,127
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import division from telemetry.core import _bitmap def Channels(bitmap): return bitmap.bpp def Width(bitmap): return bitmap.width def Height(bitmap): return bitmap.height def Pixels(bitmap): return bitmap.pixels def GetPixelColor(bitmap, x, y): return bitmap.GetPixelColor(x, y) def WritePngFile(bitmap, path): bitmap.WritePngFile(path) def FromRGBPixels(width, height, pixels, bpp): return _bitmap.Bitmap(bpp, width, height, pixels) def FromPng(png_data): return _bitmap.Bitmap.FromPng(png_data) def FromPngFile(path): return _bitmap.Bitmap.FromPngFile(path) def AreEqual(bitmap1, bitmap2, tolerance, _): return bitmap1.IsEqual(bitmap2, tolerance) def Diff(bitmap1, bitmap2): return bitmap1.Diff(bitmap2) def GetBoundingBox(bitmap, color, tolerance): return bitmap.GetBoundingBox(color, tolerance) def Crop(bitmap, left, top, width, height): return bitmap.Crop(left, top, width, height) def GetColorHistogram(bitmap, ignore_color, tolerance): return bitmap.ColorHistogram(ignore_color, tolerance)
guorendong/iridium-browser-ubuntu
tools/telemetry/telemetry/image_processing/image_util_bitmap_impl.py
Python
bsd-3-clause
1,221
""" Django admin pages for student app """ from django import forms from django.contrib.auth.models import User from ratelimitbackend import admin from xmodule.modulestore.django import modulestore from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey from config_models.admin import ConfigurationModelAdmin from student.models import ( UserProfile, UserTestGroup, CourseEnrollmentAllowed, DashboardConfiguration, CourseEnrollment, Registration, PendingNameChange, CourseAccessRole, LinkedInAddToProfileConfiguration ) from student.roles import REGISTERED_ACCESS_ROLES class CourseAccessRoleForm(forms.ModelForm): """Form for adding new Course Access Roles view the Django Admin Panel.""" class Meta(object): model = CourseAccessRole fields = '__all__' email = forms.EmailField(required=True) COURSE_ACCESS_ROLES = [(role_name, role_name) for role_name in REGISTERED_ACCESS_ROLES.keys()] role = forms.ChoiceField(choices=COURSE_ACCESS_ROLES) def clean_course_id(self): """ Checking course-id format and course exists in module store. This field can be null. """ if self.cleaned_data['course_id']: course_id = self.cleaned_data['course_id'] try: course_key = CourseKey.from_string(course_id) except InvalidKeyError: raise forms.ValidationError(u"Invalid CourseID. Please check the format and re-try.") if not modulestore().has_course(course_key): raise forms.ValidationError(u"Cannot find course with id {} in the modulestore".format(course_id)) return course_key return None def clean_org(self): """If org and course-id exists then Check organization name against the given course. """ if self.cleaned_data.get('course_id') and self.cleaned_data['org']: org = self.cleaned_data['org'] org_name = self.cleaned_data.get('course_id').org if org.lower() != org_name.lower(): raise forms.ValidationError( u"Org name {} is not valid. Valid name is {}.".format( org, org_name ) ) return self.cleaned_data['org'] def clean_email(self): """ Checking user object against given email id. """ email = self.cleaned_data['email'] try: user = User.objects.get(email=email) except Exception: raise forms.ValidationError( u"Email does not exist. Could not find {email}. Please re-enter email address".format( email=email ) ) return user def clean(self): """ Checking the course already exists in db. """ cleaned_data = super(CourseAccessRoleForm, self).clean() if not self.errors: if CourseAccessRole.objects.filter( user=cleaned_data.get("email"), org=cleaned_data.get("org"), course_id=cleaned_data.get("course_id"), role=cleaned_data.get("role") ).exists(): raise forms.ValidationError("Duplicate Record.") return cleaned_data def __init__(self, *args, **kwargs): super(CourseAccessRoleForm, self).__init__(*args, **kwargs) if self.instance.user_id: self.fields['email'].initial = self.instance.user.email class CourseAccessRoleAdmin(admin.ModelAdmin): """Admin panel for the Course Access Role. """ form = CourseAccessRoleForm raw_id_fields = ("user",) exclude = ("user",) fieldsets = ( (None, { 'fields': ('email', 'course_id', 'org', 'role',) }), ) list_display = ( 'id', 'user', 'org', 'course_id', 'role', ) search_fields = ( 'id', 'user__username', 'user__email', 'org', 'course_id', 'role', ) def save_model(self, request, obj, form, change): obj.user = form.cleaned_data['email'] super(CourseAccessRoleAdmin, self).save_model(request, obj, form, change) class LinkedInAddToProfileConfigurationAdmin(admin.ModelAdmin): """Admin interface for the LinkedIn Add to Profile configuration. """ class Meta(object): model = LinkedInAddToProfileConfiguration # Exclude deprecated fields exclude = ('dashboard_tracking_code',) class CourseEnrollmentAdmin(admin.ModelAdmin): """ Admin interface for the CourseEnrollment model. """ list_display = ('id', 'course_id', 'mode', 'user', 'is_active',) list_filter = ('mode', 'is_active',) raw_id_fields = ('user',) search_fields = ('course_id', 'mode', 'user__username',) def queryset(self, request): return super(CourseEnrollmentAdmin, self).queryset(request).select_related('user') class Meta(object): model = CourseEnrollment class UserProfileAdmin(admin.ModelAdmin): """ Admin interface for UserProfile model. """ list_display = ('user', 'name',) raw_id_fields = ('user',) search_fields = ('user__username', 'user__first_name', 'user__last_name', 'user__email', 'name',) def get_readonly_fields(self, request, obj=None): # The user field should not be editable for an existing user profile. if obj: return self.readonly_fields + ('user',) return self.readonly_fields class Meta(object): model = UserProfile admin.site.register(UserTestGroup) admin.site.register(CourseEnrollmentAllowed) admin.site.register(Registration) admin.site.register(PendingNameChange) admin.site.register(CourseAccessRole, CourseAccessRoleAdmin) admin.site.register(DashboardConfiguration, ConfigurationModelAdmin) admin.site.register(LinkedInAddToProfileConfiguration, LinkedInAddToProfileConfigurationAdmin) admin.site.register(CourseEnrollment, CourseEnrollmentAdmin) admin.site.register(UserProfile, UserProfileAdmin)
hamzehd/edx-platform
common/djangoapps/student/admin.py
Python
agpl-3.0
6,073
# (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' callback: syslog_json callback_type: notification requirements: - whitelist in configuration short_description: sends JSON events to syslog version_added: "1.9" description: - This plugin logs ansible-playbook and ansible runs to a syslog server in JSON format - Before 2.9 only environment variables were available for configuration options: server: description: syslog server that will receive the event env: - name: SYSLOG_SERVER default: localhost ini: - section: callback_syslog_json key: syslog_server port: description: port on which the syslog server is listening env: - name: SYSLOG_PORT default: 514 ini: - section: callback_syslog_json key: syslog_port facility: description: syslog facility to log as env: - name: SYSLOG_FACILITY default: user ini: - section: callback_syslog_json key: syslog_facility ''' import os import json import logging import logging.handlers import socket from ansible.plugins.callback import CallbackBase class CallbackModule(CallbackBase): """ logs ansible-playbook and ansible runs to a syslog server in json format """ CALLBACK_VERSION = 2.0 CALLBACK_TYPE = 'aggregate' CALLBACK_NAME = 'syslog_json' CALLBACK_NEEDS_WHITELIST = True def __init__(self): super(CallbackModule, self).__init__() self.set_options() syslog_host = self.get_option("server") syslog_port = int(self.get_option("port")) syslog_facility = self.get_option("facility") self.logger = logging.getLogger('ansible logger') self.logger.setLevel(logging.DEBUG) self.handler = logging.handlers.SysLogHandler( address=(syslog_host, syslog_port), facility=syslog_facility ) self.logger.addHandler(self.handler) self.hostname = socket.gethostname() def runner_on_failed(self, host, res, ignore_errors=False): self.logger.error('%s ansible-command: task execution FAILED; host: %s; message: %s', self.hostname, host, self._dump_results(res)) def runner_on_ok(self, host, res): self.logger.info('%s ansible-command: task execution OK; host: %s; message: %s', self.hostname, host, self._dump_results(res)) def runner_on_skipped(self, host, item=None): self.logger.info('%s ansible-command: task execution SKIPPED; host: %s; message: %s', self.hostname, host, 'skipped') def runner_on_unreachable(self, host, res): self.logger.error('%s ansible-command: task execution UNREACHABLE; host: %s; message: %s', self.hostname, host, self._dump_results(res)) def runner_on_async_failed(self, host, res, jid): self.logger.error('%s ansible-command: task execution FAILED; host: %s; message: %s', self.hostname, host, self._dump_results(res)) def playbook_on_import_for_host(self, host, imported_file): self.logger.info('%s ansible-command: playbook IMPORTED; host: %s; message: imported file %s', self.hostname, host, imported_file) def playbook_on_not_import_for_host(self, host, missing_file): self.logger.info('%s ansible-command: playbook NOT IMPORTED; host: %s; message: missing file %s', self.hostname, host, missing_file)
thaim/ansible
lib/ansible/plugins/callback/syslog_json.py
Python
mit
3,681
# 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. # ============================================================================== """Seq2seq layer operations for use in neural networks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import six from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import rnn from tensorflow.python.ops import tensor_array_ops from tensorflow.python.ops import variable_scope from tensorflow.python.util import nest __all__ = ["Decoder", "dynamic_decode"] _transpose_batch_time = rnn._transpose_batch_time # pylint: disable=protected-access @six.add_metaclass(abc.ABCMeta) class Decoder(object): """An RNN Decoder abstract interface object. Concepts used by this interface: - `inputs`: (structure of) tensors and TensorArrays that is passed as input to the RNNCell composing the decoder, at each time step. - `state`: (structure of) tensors and TensorArrays that is passed to the RNNCell instance as the state. - `finished`: boolean tensor telling whether each sequence in the batch is finished. - `outputs`: Instance of BasicDecoderOutput. Result of the decoding, at each time step. """ @property def batch_size(self): """The batch size of input values.""" raise NotImplementedError @property def output_size(self): """A (possibly nested tuple of...) integer[s] or `TensorShape` object[s].""" raise NotImplementedError @property def output_dtype(self): """A (possibly nested tuple of...) dtype[s].""" raise NotImplementedError @abc.abstractmethod def initialize(self, name=None): """Called before any decoding iterations. This methods must compute initial input values and initial state. Args: name: Name scope for any created operations. Returns: `(finished, initial_inputs, initial_state)`: initial values of 'finished' flags, inputs and state. """ raise NotImplementedError @abc.abstractmethod def step(self, time, inputs, state, name=None): """Called per step of decoding (but only once for dynamic decoding). Args: time: Scalar `int32` tensor. Current step number. inputs: RNNCell input (possibly nested tuple of) tensor[s] for this time step. state: RNNCell state (possibly nested tuple of) tensor[s] from previous time step. name: Name scope for any created operations. Returns: `(outputs, next_state, next_inputs, finished)`: `outputs` is an instance of BasicDecoderOutput, `next_state` is a (structure of) state tensors and TensorArrays, `next_inputs` is the tensor that should be used as input for the next step, `finished` is a boolean tensor telling whether the sequence is complete, for each sequence in the batch. """ raise NotImplementedError def finalize(self, outputs, final_state, sequence_lengths): raise NotImplementedError def _create_zero_outputs(size, dtype, batch_size): """Create a zero outputs Tensor structure.""" def _t(s): return (s if isinstance(s, ops.Tensor) else constant_op.constant( tensor_shape.TensorShape(s).as_list(), dtype=dtypes.int32, name="zero_suffix_shape")) def _create(s, d): return array_ops.zeros( array_ops.concat( ([batch_size], _t(s)), axis=0), dtype=d) return nest.map_structure(_create, size, dtype) def dynamic_decode(decoder, output_time_major=False, impute_finished=False, maximum_iterations=None, parallel_iterations=32, swap_memory=False, scope=None): """Perform dynamic decoding with `decoder`. Calls initialize() once and step() repeatedly on the Decoder object. Args: decoder: A `Decoder` instance. output_time_major: Python boolean. Default: `False` (batch major). If `True`, outputs are returned as time major tensors (this mode is faster). Otherwise, outputs are returned as batch major tensors (this adds extra time to the computation). impute_finished: Python boolean. If `True`, then states for batch entries which are marked as finished get copied through and the corresponding outputs get zeroed out. This causes some slowdown at each time step, but ensures that the final state and outputs have the correct values and that backprop ignores time steps that were marked as finished. maximum_iterations: `int32` scalar, maximum allowed number of decoding steps. Default is `None` (decode until the decoder is fully done). parallel_iterations: Argument passed to `tf.while_loop`. swap_memory: Argument passed to `tf.while_loop`. scope: Optional variable scope to use. Returns: `(final_outputs, final_state, final_sequence_lengths)`. Raises: TypeError: if `decoder` is not an instance of `Decoder`. ValueError: if `maximum_iterations` is provided but is not a scalar. """ if not isinstance(decoder, Decoder): raise TypeError("Expected decoder to be type Decoder, but saw: %s" % type(decoder)) with variable_scope.variable_scope(scope, "decoder") as varscope: # Properly cache variable values inside the while_loop if varscope.caching_device is None: varscope.set_caching_device(lambda op: op.device) if maximum_iterations is not None: maximum_iterations = ops.convert_to_tensor( maximum_iterations, dtype=dtypes.int32, name="maximum_iterations") if maximum_iterations.get_shape().ndims != 0: raise ValueError("maximum_iterations must be a scalar") initial_finished, initial_inputs, initial_state = decoder.initialize() zero_outputs = _create_zero_outputs(decoder.output_size, decoder.output_dtype, decoder.batch_size) if maximum_iterations is not None: initial_finished = math_ops.logical_or( initial_finished, 0 >= maximum_iterations) initial_sequence_lengths = array_ops.zeros_like( initial_finished, dtype=dtypes.int32) initial_time = constant_op.constant(0, dtype=dtypes.int32) def _shape(batch_size, from_shape): if not isinstance(from_shape, tensor_shape.TensorShape): return tensor_shape.TensorShape(None) else: batch_size = tensor_util.constant_value( ops.convert_to_tensor( batch_size, name="batch_size")) return tensor_shape.TensorShape([batch_size]).concatenate(from_shape) def _create_ta(s, d): return tensor_array_ops.TensorArray( dtype=d, size=0, dynamic_size=True, element_shape=_shape(decoder.batch_size, s)) initial_outputs_ta = nest.map_structure(_create_ta, decoder.output_size, decoder.output_dtype) def condition(unused_time, unused_outputs_ta, unused_state, unused_inputs, finished, unused_sequence_lengths): return math_ops.logical_not(math_ops.reduce_all(finished)) def body(time, outputs_ta, state, inputs, finished, sequence_lengths): """Internal while_loop body. Args: time: scalar int32 tensor. outputs_ta: structure of TensorArray. state: (structure of) state tensors and TensorArrays. inputs: (structure of) input tensors. finished: bool tensor (keeping track of what's finished). sequence_lengths: int32 tensor (keeping track of time of finish). Returns: `(time + 1, outputs_ta, next_state, next_inputs, next_finished, next_sequence_lengths)`. ``` """ (next_outputs, decoder_state, next_inputs, decoder_finished) = decoder.step(time, inputs, state) next_finished = math_ops.logical_or(decoder_finished, finished) if maximum_iterations is not None: next_finished = math_ops.logical_or( next_finished, time + 1 >= maximum_iterations) next_sequence_lengths = array_ops.where( math_ops.logical_and(math_ops.logical_not(finished), next_finished), array_ops.fill(array_ops.shape(sequence_lengths), time + 1), sequence_lengths) nest.assert_same_structure(state, decoder_state) nest.assert_same_structure(outputs_ta, next_outputs) nest.assert_same_structure(inputs, next_inputs) # Zero out output values past finish if impute_finished: emit = nest.map_structure( lambda out, zero: array_ops.where(finished, zero, out), next_outputs, zero_outputs) else: emit = next_outputs # Copy through states past finish def _maybe_copy_state(new, cur): # TensorArrays and scalar states get passed through. if isinstance(cur, tensor_array_ops.TensorArray): pass_through = True else: new.set_shape(cur.shape) pass_through = (new.shape.ndims == 0) return new if pass_through else array_ops.where(finished, cur, new) if impute_finished: next_state = nest.map_structure( _maybe_copy_state, decoder_state, state) else: next_state = decoder_state outputs_ta = nest.map_structure(lambda ta, out: ta.write(time, out), outputs_ta, emit) return (time + 1, outputs_ta, next_state, next_inputs, next_finished, next_sequence_lengths) res = control_flow_ops.while_loop( condition, body, loop_vars=[ initial_time, initial_outputs_ta, initial_state, initial_inputs, initial_finished, initial_sequence_lengths, ], parallel_iterations=parallel_iterations, swap_memory=swap_memory) final_outputs_ta = res[1] final_state = res[2] final_sequence_lengths = res[5] final_outputs = nest.map_structure(lambda ta: ta.stack(), final_outputs_ta) try: final_outputs, final_state = decoder.finalize( final_outputs, final_state, final_sequence_lengths) except NotImplementedError: pass if not output_time_major: final_outputs = nest.map_structure(_transpose_batch_time, final_outputs) return final_outputs, final_state, final_sequence_lengths
unnikrishnankgs/va
venv/lib/python3.5/site-packages/tensorflow/contrib/seq2seq/python/ops/decoder.py
Python
bsd-2-clause
11,345
#!/usr/bin/env python # -*- coding: UTF-8 -*- __author__="Josh Montague" __license__="MIT License" """ This script is designed to run inline (%run 3d-example.py) in the corresponding IPython notebook. It generates a 3d scatter plot using scikit-learn data generation and with a number of samples and clusters determined by the variables near the top. """ import argparse import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn.datasets import make_blobs import seaborn as sns from gap_stats import gap_statistics from gap_stats import plot_gap_statistics def make_example_plot(args): """ Create artificial data (blobs) and color them according to the appropriate blob center. """ # read args samples = args.samples clusters = args.clusters # create some data X, y = make_blobs(n_samples=samples, centers=clusters, n_features=3, # increase variance for illustration cluster_std=1.5, # fix random_state if you believe in determinism #random_state=42 ) # seaborn display settings sns.set(style='whitegrid', palette=sns.color_palette("Set2", clusters)) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for i in range(clusters): # for each center, add data to the figure w/ appropriate label ax.plot(X[y==i,0], X[y==i,1], X[y==i,2], 'o', alpha=0.6, label='cluster {}'.format(i) ) ax.set_title('{} labeled clusters (ground truth)'.format(clusters)) ax.legend(loc='upper left') # seaborn settings - no, really set these things this time, please sns.set(style='whitegrid', palette=sns.color_palette("Set2", clusters)) #plt.show() # potentially return the data for later use data = None if args.gap: data = (X, y) return data if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-s","--samples" , dest="samples" , type=int , default=100 ) parser.add_argument("-c","--clusters" , dest="clusters" , type=int , default=5 ) parser.add_argument("-g","--gap" , dest="gap" , type=bool , default=False ) args = parser.parse_args() data = make_example_plot(args) if args.gap: # i just really prefer the dark theme sns.set(style='darkgrid', palette='deep') # unpack X, y = data # run the gap statistic algorithm gaps, errs, difs = gap_statistics(X, ks=range(1, args.clusters+5)) # plot (intended for %matplotlib inline) plot_gap_statistics(gaps, errs, difs)
mhdella/Data-Science-45min-Intros
choosing-k-in-kmeans/3d-example.py
Python
unlicense
2,925
# -*- coding: utf-8 -*- """ pygments.styles.default ~~~~~~~~~~~~~~~~~~~~~~~ The default highlighting style. :copyright: 2007 by Tiberius Teng. :copyright: 2006 by Georg Brandl. :license: BSD, see LICENSE for more details. """ from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace class DefaultStyle(Style): """ The default style (inspired by Emacs 22). """ background_color = "#f8f8f8" default_style = "" styles = { Whitespace: "#bbbbbb", Comment: "italic #408080", Comment.Preproc: "noitalic #BC7A00", #Keyword: "bold #AA22FF", Keyword: "bold #008000", Keyword.Pseudo: "nobold", Keyword.Type: "nobold #B00040", Operator: "#666666", Operator.Word: "bold #AA22FF", Name.Builtin: "#008000", Name.Function: "#0000FF", Name.Class: "bold #0000FF", Name.Namespace: "bold #0000FF", Name.Exception: "bold #D2413A", Name.Variable: "#19177C", Name.Constant: "#880000", Name.Label: "#A0A000", Name.Entity: "bold #999999", Name.Attribute: "#7D9029", Name.Tag: "bold #008000", Name.Decorator: "#AA22FF", String: "#BA2121", String.Doc: "italic", String.Interpol: "bold #BB6688", String.Escape: "bold #BB6622", String.Regex: "#BB6688", #String.Symbol: "#B8860B", String.Symbol: "#19177C", String.Other: "#008000", Number: "#666666", Generic.Heading: "bold #000080", Generic.Subheading: "bold #800080", Generic.Deleted: "#A00000", Generic.Inserted: "#00A000", Generic.Error: "#FF0000", Generic.Emph: "italic", Generic.Strong: "bold", Generic.Prompt: "bold #000080", Generic.Output: "#888", Generic.Traceback: "#04D", Error: "border:#FF0000" }
alon/polinax
libs/external_libs/Pygments-0.11.1/pygments/styles/default.py
Python
gpl-2.0
2,543
#!/usr/bin/python #coding: utf-8 -*- # (c) 2013, David Stygstra <david.stygstra@gmail.com> # Portions copyright @ 2015 VMware, 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': 'network'} DOCUMENTATION = ''' --- module: openvswitch_bridge version_added: 1.4 author: "David Stygstra (@stygstra)" short_description: Manage Open vSwitch bridges requirements: [ ovs-vsctl ] description: - Manage Open vSwitch bridges options: bridge: required: true description: - Name of bridge or fake bridge to manage parent: version_added: "2.3" required: false default: None description: - Bridge parent of the fake bridge to manage vlan: version_added: "2.3" required: false default: None description: - The VLAN id of the fake bridge to manage (must be between 0 and 4095). This parameter is required if I(parent) parameter is set. state: required: false default: "present" choices: [ present, absent ] description: - Whether the bridge should exist timeout: required: false default: 5 description: - How long to wait for ovs-vswitchd to respond external_ids: version_added: 2.0 required: false default: None description: - A dictionary of external-ids. Omitting this parameter is a No-op. To clear all external-ids pass an empty value. fail_mode: version_added: 2.0 default: None required: false choices : [secure, standalone] description: - Set bridge fail-mode. The default value (None) is a No-op. set: version_added: 2.3 required: false default: None description: - Run set command after bridge configuration. This parameter is non-idempotent, play will always return I(changed) state if present ''' EXAMPLES = ''' # Create a bridge named br-int - openvswitch_bridge: bridge: br-int state: present # Create a fake bridge named br-int within br-parent on the VLAN 405 - openvswitch_bridge: bridge: br-int parent: br-parent vlan: 405 state: present # Create an integration bridge - openvswitch_bridge: bridge: br-int state: present fail_mode: secure args: external_ids: bridge-id: br-int ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six import iteritems def _fail_mode_to_str(text): if not text: return None else: return text.strip() def _external_ids_to_dict(text): if not text: return None else: d = {} for l in text.splitlines(): if l: k, v = l.split('=') d[k] = v return d def map_obj_to_commands(want, have, module): commands = list() if module.params['state'] == 'absent': if have: templatized_command = ("%(ovs-vsctl)s -t %(timeout)s del-br" " %(bridge)s") command = templatized_command % module.params commands.append(command) else: if have: if want['fail_mode'] != have['fail_mode']: templatized_command = ("%(ovs-vsctl)s -t %(timeout)s" " set-fail-mode %(bridge)s" " %(fail_mode)s") command = templatized_command % module.params commands.append(command) if want['external_ids'] != have['external_ids']: templatized_command = ("%(ovs-vsctl)s -t %(timeout)s" " br-set-external-id %(bridge)s") command = templatized_command % module.params if want['external_ids']: for k, v in iteritems(want['external_ids']): if (k not in have['external_ids'] or want['external_ids'][k] != have['external_ids'][k]): command += " " + k + " " + v commands.append(command) else: templatized_command = ("%(ovs-vsctl)s -t %(timeout)s add-br" " %(bridge)s") command = templatized_command % module.params if want['parent']: templatized_command = "%(parent)s %(vlan)s" command += " " + templatized_command % module.params if want['set']: templatized_command = " -- set %(set)s" command += templatized_command % module.params commands.append(command) if want['fail_mode']: templatized_command = ("%(ovs-vsctl)s -t %(timeout)s" " set-fail-mode %(bridge)s" " %(fail_mode)s") command = templatized_command % module.params commands.append(command) if want['external_ids']: for k, v in iteritems(want['external_ids']): templatized_command = ("%(ovs-vsctl)s -t %(timeout)s" " br-set-external-id %(bridge)s") command = templatized_command % module.params command += " " + k + " " + v commands.append(command) return commands def map_config_to_obj(module): templatized_command = "%(ovs-vsctl)s -t %(timeout)s list-br" command = templatized_command % module.params rc, out, err = module.run_command(command, check_rc=True) if rc != 0: module.fail_json(msg=err) obj = {} if module.params['bridge'] in out.splitlines(): obj['bridge'] = module.params['bridge'] templatized_command = ("%(ovs-vsctl)s -t %(timeout)s br-to-parent" " %(bridge)s") command = templatized_command % module.params rc, out, err = module.run_command(command, check_rc=True) obj['parent'] = out.strip() templatized_command = ("%(ovs-vsctl)s -t %(timeout)s br-to-vlan" " %(bridge)s") command = templatized_command % module.params rc, out, err = module.run_command(command, check_rc=True) obj['vlan'] = out.strip() templatized_command = ("%(ovs-vsctl)s -t %(timeout)s get-fail-mode" " %(bridge)s") command = templatized_command % module.params rc, out, err = module.run_command(command, check_rc=True) obj['fail_mode'] = _fail_mode_to_str(out) templatized_command = ("%(ovs-vsctl)s -t %(timeout)s br-get-external-id" " %(bridge)s") command = templatized_command % module.params rc, out, err = module.run_command(command, check_rc=True) obj['external_ids'] = _external_ids_to_dict(out) return obj def map_params_to_obj(module): obj = { 'bridge': module.params['bridge'], 'parent': module.params['parent'], 'vlan': module.params['vlan'], 'fail_mode': module.params['fail_mode'], 'external_ids': module.params['external_ids'], 'set': module.params['set'] } return obj def main(): """ Entry point. """ argument_spec = { 'bridge': {'required': True}, 'parent': {'default': None}, 'vlan': {'default': None, 'type': 'int'}, 'state': {'default': 'present', 'choices': ['present', 'absent']}, 'timeout': {'default': 5, 'type': 'int'}, 'external_ids': {'default': None, 'type': 'dict'}, 'fail_mode': {'default': None}, 'set': {'required': False, 'default': None} } required_if = [('parent', not None, ('vlan',))] module = AnsibleModule(argument_spec=argument_spec, required_if=required_if, supports_check_mode=True) result = {'changed': False} # We add ovs-vsctl to module_params to later build up templatized commands module.params["ovs-vsctl"] = module.get_bin_path("ovs-vsctl", True) want = map_params_to_obj(module) have = map_config_to_obj(module) commands = map_obj_to_commands(want, have, module) result['commands'] = commands if commands: if not module.check_mode: for c in commands: module.run_command(c, check_rc=True) result['changed'] = True module.exit_json(**result) if __name__ == '__main__': main()
e-gob/plataforma-kioscos-autoatencion
scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/network/ovs/openvswitch_bridge.py
Python
bsd-3-clause
8,968
# # This file is part of pyasn1 software. # # Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com> # License: http://snmplabs.com/pyasn1/license.html # import time from datetime import datetime from sys import version_info __all__ = ['strptime'] if version_info[:2] <= (2, 4): def strptime(text, dateFormat): return datetime(*(time.strptime(text, dateFormat)[0:6])) else: def strptime(text, dateFormat): return datetime.strptime(text, dateFormat)
endlessm/chromium-browser
tools/swarming_client/third_party/pyasn1/pyasn1/compat/dateandtime.py
Python
bsd-3-clause
482
# Hermite polynomials H_n(x) on the real line for n=0,1,2,3,4 f0 = lambda x: hermite(0,x) f1 = lambda x: hermite(1,x) f2 = lambda x: hermite(2,x) f3 = lambda x: hermite(3,x) f4 = lambda x: hermite(4,x) plot([f0,f1,f2,f3,f4],[-2,2],[-25,25])
pducks32/intergrala
python/sympy/doc/src/modules/mpmath/plots/hermite.py
Python
mit
240
# Copyright (C) 2010-2014 Free Software Foundation, Inc. # 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 traceback import os import sys import _gdb if sys.version_info[0] > 2: # Python 3 moved "reload" from imp import reload from _gdb import * class _GdbFile (object): # These two are needed in Python 3 encoding = "UTF-8" errors = "strict" def close(self): # Do nothing. return None def isatty(self): return False def writelines(self, iterable): for line in iterable: self.write(line) def flush(self): flush() class GdbOutputFile (_GdbFile): def write(self, s): write(s, stream=STDOUT) sys.stdout = GdbOutputFile() class GdbOutputErrorFile (_GdbFile): def write(self, s): write(s, stream=STDERR) sys.stderr = GdbOutputErrorFile() # Default prompt hook does nothing. prompt_hook = None # Ensure that sys.argv is set to something. # We do not use PySys_SetArgvEx because it did not appear until 2.6.6. sys.argv = [''] # Initial pretty printers. pretty_printers = [] # Initial type printers. type_printers = [] # Initial xmethod matchers. xmethods = [] # Initial frame filters. frame_filters = {} # Convenience variable to GDB's python directory PYTHONDIR = os.path.dirname(os.path.dirname(__file__)) # Auto-load all functions/commands. # Packages to auto-load. packages = [ 'function', 'command' ] # pkgutil.iter_modules is not available prior to Python 2.6. Instead, # manually iterate the list, collating the Python files in each module # path. Construct the module name, and import. def auto_load_packages(): for package in packages: location = os.path.join(os.path.dirname(__file__), package) if os.path.exists(location): py_files = filter(lambda x: x.endswith('.py') and x != '__init__.py', os.listdir(location)) for py_file in py_files: # Construct from foo.py, gdb.module.foo modname = "%s.%s.%s" % ( __name__, package, py_file[:-3] ) try: if modname in sys.modules: # reload modules with duplicate names reload(__import__(modname)) else: __import__(modname) except: sys.stderr.write (traceback.format_exc() + "\n") auto_load_packages() def GdbSetPythonDirectory(dir): """Update sys.path, reload gdb and auto-load packages.""" global PYTHONDIR try: sys.path.remove(PYTHONDIR) except ValueError: pass sys.path.insert(0, dir) PYTHONDIR = dir # note that reload overwrites the gdb module without deleting existing # attributes reload(__import__(__name__)) auto_load_packages()
ExploreEmbedded/Tit-Windows
tools/share/gdb/python/gdb/__init__.py
Python
bsd-3-clause
3,494
for x in undefined(): # ty<caret>pe: int pass
smmribeiro/intellij-community
python/testData/intentions/PyConvertTypeCommentToVariableAnnotationIntentionTest/simpleForLoop.py
Python
apache-2.0
50
from framework.routing import Rule, json_renderer from addons.s3 import views api_routes = { 'rules': [ Rule( [ '/settings/s3/accounts/', ], 'post', views.s3_add_user_account, json_renderer, ), Rule( [ '/settings/s3/accounts/', ], 'get', views.s3_account_list, json_renderer, ), Rule( [ '/project/<pid>/s3/settings/', '/project/<pid>/node/<nid>/s3/settings/', ], 'put', views.s3_set_config, json_renderer, ), Rule( [ '/project/<pid>/s3/settings/', '/project/<pid>/node/<nid>/s3/settings/', ], 'get', views.s3_get_config, json_renderer, ), Rule( [ '/project/<pid>/s3/user-auth/', '/project/<pid>/node/<nid>/s3/user-auth/', ], 'put', views.s3_import_auth, json_renderer, ), Rule( [ '/project/<pid>/s3/user-auth/', '/project/<pid>/node/<nid>/s3/user-auth/', ], 'delete', views.s3_deauthorize_node, json_renderer, ), Rule( [ '/project/<pid>/s3/buckets/', '/project/<pid>/node/<nid>/s3/buckets/', ], 'get', views.s3_folder_list, json_renderer, ), Rule( [ '/project/<pid>/s3/newbucket/', '/project/<pid>/node/<nid>/s3/newbucket/', ], 'post', views.create_bucket, json_renderer ), ], 'prefix': '/api/v1', }
mluo613/osf.io
addons/s3/routes.py
Python
apache-2.0
1,947
from django.test import TestCase from readthedocs.builds.constants import LATEST from readthedocs.projects.models import Project from readthedocs.restapi.views.footer_views import get_version_compare_data class VersionCompareTests(TestCase): fixtures = ['eric.json', 'test_data.json'] def test_not_highest(self): project = Project.objects.get(slug='read-the-docs') version = project.versions.get(slug='0.2.1') data = get_version_compare_data(project, version) self.assertEqual(data['is_highest'], False) def test_latest_version_highest(self): project = Project.objects.get(slug='read-the-docs') data = get_version_compare_data(project) self.assertEqual(data['is_highest'], True) version = project.versions.get(slug=LATEST) data = get_version_compare_data(project, version) self.assertEqual(data['is_highest'], True) def test_real_highest(self): project = Project.objects.get(slug='read-the-docs') version = project.versions.get(slug='0.2.2') data = get_version_compare_data(project, version) self.assertEqual(data['is_highest'], True)
SteveViss/readthedocs.org
readthedocs/rtd_tests/tests/test_api_version_compare.py
Python
mit
1,173
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt # Event # ------------- from __future__ import unicode_literals import frappe @frappe.whitelist() def get_cal_events(m_st, m_end): # load owned events res1 = frappe.db.sql("""select name from `tabEvent` WHERE ifnull(event_date,'2000-01-01') between %s and %s and owner = %s and event_type != 'Public' and event_type != 'Cancel'""", (m_st, m_end, frappe.user.name)) # load individual events res2 = frappe.db.sql("""select t1.name from `tabEvent` t1, `tabEvent User` t2 where ifnull(t1.event_date,'2000-01-01') between %s and %s and t2.person = %s and t1.name = t2.parent and t1.event_type != 'Cancel'""", (m_st, m_end, frappe.user.name)) # load role events roles = frappe.user.get_roles() myroles = ['t2.role = "%s"' % r.replace('"', '\"') for r in roles] myroles = '(' + (' OR '.join(myroles)) + ')' res3 = frappe.db.sql("""select t1.name from `tabEvent` t1, `tabEvent Role` t2 where ifnull(t1.event_date,'2000-01-01') between %s and %s and t1.name = t2.parent and t1.event_type != 'Cancel' and %s""" % ('%s', '%s', myroles), (m_st, m_end)) # load public events res4 = frappe.db.sql("select name from `tabEvent` \ where ifnull(event_date,'2000-01-01') between %s and %s and event_type='Public'", (m_st, m_end)) doclist, rl = [], [] for r in res1 + res2 + res3 + res4: if not r in rl: doclist += frappe.get_doc('Event', r[0]) rl.append(r) return doclist
gangadharkadam/shfr
frappe/widgets/event.py
Python
mit
1,523
from time import sleep class TestPyTest: def testOne(self): sleep(1.5) # To check duration assert 4 == 2*2 def testTwo(self): assert True def testThree(): assert 4 == 2*2
paplorinc/intellij-community
python/testData/testRunner/env/pytest/test1.py
Python
apache-2.0
209
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.click', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## log.h (module 'core'): ns3::LogLevel [enumeration] module.add_enum('LogLevel', ['LOG_NONE', 'LOG_ERROR', 'LOG_LEVEL_ERROR', 'LOG_WARN', 'LOG_LEVEL_WARN', 'LOG_DEBUG', 'LOG_LEVEL_DEBUG', 'LOG_INFO', 'LOG_LEVEL_INFO', 'LOG_FUNCTION', 'LOG_LEVEL_FUNCTION', 'LOG_LOGIC', 'LOG_LEVEL_LOGIC', 'LOG_ALL', 'LOG_LEVEL_ALL', 'LOG_PREFIX_FUNC', 'LOG_PREFIX_TIME', 'LOG_PREFIX_NODE', 'LOG_PREFIX_LEVEL', 'LOG_PREFIX_ALL'], import_from_module='ns.core') ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] module.add_class('AttributeConstructionList', import_from_module='ns.core') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', import_from_module='ns.core') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] module.add_class('Inet6SocketAddress', import_from_module='ns.network') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] module.add_class('InetSocketAddress', import_from_module='ns.network') ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## int-to-type.h (module 'core'): ns3::IntToType<0> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['0']) ## int-to-type.h (module 'core'): ns3::IntToType<0>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 0 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<1> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['1']) ## int-to-type.h (module 'core'): ns3::IntToType<1>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 1 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<2> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['2']) ## int-to-type.h (module 'core'): ns3::IntToType<2>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 2 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<3> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['3']) ## int-to-type.h (module 'core'): ns3::IntToType<3>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 3 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<4> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['4']) ## int-to-type.h (module 'core'): ns3::IntToType<4>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 4 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<5> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['5']) ## int-to-type.h (module 'core'): ns3::IntToType<5>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 5 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<6> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['6']) ## int-to-type.h (module 'core'): ns3::IntToType<6>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 6 >'], import_from_module='ns.core') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class] module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration] module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## 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-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress [class] module.add_class('Ipv6InterfaceAddress', import_from_module='ns.internet') ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::State_e [enumeration] module.add_enum('State_e', ['TENTATIVE', 'DEPRECATED', 'PREFERRED', 'PERMANENT', 'HOMEADDRESS', 'TENTATIVE_OPTIMISTIC', 'INVALID'], outer_class=root_module['ns3::Ipv6InterfaceAddress'], import_from_module='ns.internet') ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Scope_e [enumeration] module.add_enum('Scope_e', ['HOST', 'LINKLOCAL', 'GLOBAL'], outer_class=root_module['ns3::Ipv6InterfaceAddress'], import_from_module='ns.internet') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## log.h (module 'core'): ns3::LogComponent [class] module.add_class('LogComponent', import_from_module='ns.core') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData_e [enumeration] module.add_enum('TagData_e', ['MAX_SIZE'], outer_class=root_module['ns3::PacketTagList::TagData'], import_from_module='ns.network') ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simulator.h (module 'core'): ns3::Simulator [class] module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core') ## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs [class] module.add_class('SystemWallClockMs', 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') ## 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::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## 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') ## ipv6-header.h (module 'internet'): ns3::Ipv6Header [class] module.add_class('Ipv6Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) ## ipv6-header.h (module 'internet'): ns3::Ipv6Header::NextHeader_e [enumeration] module.add_enum('NextHeader_e', ['IPV6_EXT_HOP_BY_HOP', 'IPV6_IPV4', 'IPV6_TCP', 'IPV6_UDP', 'IPV6_IPV6', 'IPV6_EXT_ROUTING', 'IPV6_EXT_FRAGMENTATION', 'IPV6_EXT_CONFIDENTIALITY', 'IPV6_EXT_AUTHENTIFICATION', 'IPV6_ICMPV6', 'IPV6_EXT_END', 'IPV6_EXT_DESTINATION', 'IPV6_SCTP', 'IPV6_EXT_MOBILITY', 'IPV6_UDP_LITE'], outer_class=root_module['ns3::Ipv6Header'], 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']) ## 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::SocketAddressTag [class] module.add_class('SocketAddressTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## 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::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', ['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']) ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## 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> >']) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol [class] module.add_class('IpL4Protocol', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus [enumeration] module.add_enum('RxStatus', ['RX_OK', 'RX_CSUM_FAILED', 'RX_ENDPOINT_CLOSED', 'RX_ENDPOINT_UNREACH'], outer_class=root_module['ns3::IpL4Protocol'], import_from_module='ns.internet') ## 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-click-protocol.h (module 'click'): ns3::Ipv4L3ClickProtocol [class] module.add_class('Ipv4L3ClickProtocol', parent=root_module['ns3::Ipv4']) ## 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-interface.h (module 'internet'): ns3::Ipv6Interface [class] module.add_class('Ipv6Interface', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## 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> >']) ## 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> >']) ## 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']) ## ipv4-click-routing.h (module 'click'): ns3::Ipv4ClickRouting [class] module.add_class('Ipv4ClickRouting', parent=root_module['ns3::Ipv4RoutingProtocol']) module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type='map') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) *', 'ns3::LogTimePrinter') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) **', 'ns3::LogTimePrinter*') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) *&', 'ns3::LogTimePrinter&') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) *', 'ns3::LogNodePrinter') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) **', 'ns3::LogNodePrinter*') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) *&', 'ns3::LogNodePrinter&') ## 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) 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('uint32_t ( * ) ( char const *, size_t ) *', 'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) **', 'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) *&', 'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) *', 'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) **', 'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) *&', '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_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress']) register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress']) register_Ns3IntToType__0_methods(root_module, root_module['ns3::IntToType< 0 >']) register_Ns3IntToType__1_methods(root_module, root_module['ns3::IntToType< 1 >']) register_Ns3IntToType__2_methods(root_module, root_module['ns3::IntToType< 2 >']) register_Ns3IntToType__3_methods(root_module, root_module['ns3::IntToType< 3 >']) register_Ns3IntToType__4_methods(root_module, root_module['ns3::IntToType< 4 >']) register_Ns3IntToType__5_methods(root_module, root_module['ns3::IntToType< 5 >']) register_Ns3IntToType__6_methods(root_module, root_module['ns3::IntToType< 6 >']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6InterfaceAddress_methods(root_module, root_module['ns3::Ipv6InterfaceAddress']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3LogComponent_methods(root_module, root_module['ns3::LogComponent']) 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_Ns3SystemWallClockMs_methods(root_module, root_module['ns3::SystemWallClockMs']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) 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_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header']) register_Ns3Ipv6Header_methods(root_module, root_module['ns3::Ipv6Header']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__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_Ns3SocketAddressTag_methods(root_module, root_module['ns3::SocketAddressTag']) 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_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_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3IpL4Protocol_methods(root_module, root_module['ns3::IpL4Protocol']) 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_Ns3Ipv4L3ClickProtocol_methods(root_module, root_module['ns3::Ipv4L3ClickProtocol']) 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_Ns3Ipv6Interface_methods(root_module, root_module['ns3::Ipv6Interface']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) 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_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_Ns3Ipv4ClickRouting_methods(root_module, root_module['ns3::Ipv4ClickRouting']) register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation']) register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a']) register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32']) register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64']) register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'bool', [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'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'bool', [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'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function] cls.add_method('CreateFullCopy', 'ns3::Buffer', [], 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'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function] cls.add_method('GetCurrentEndOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function] cls.add_method('GetCurrentStartOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::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'): 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'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t adjustment, int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') ## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('==') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hasher const &', 'arg0')]) ## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor] cls.add_constructor([]) ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function] cls.add_method('GetHash32', 'uint32_t', [param('std::string const', 's')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_Ns3Inet6SocketAddress_methods(root_module, cls): ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Inet6SocketAddress const & arg0) [copy constructor] cls.add_constructor([param('ns3::Inet6SocketAddress const &', 'arg0')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6) [constructor] cls.add_constructor([param('char const *', 'ipv6')]) ## inet6-socket-address.h (module 'network'): static ns3::Inet6SocketAddress ns3::Inet6SocketAddress::ConvertFrom(ns3::Address const & addr) [member function] cls.add_method('ConvertFrom', 'ns3::Inet6SocketAddress', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): ns3::Ipv6Address ns3::Inet6SocketAddress::GetIpv6() const [member function] cls.add_method('GetIpv6', 'ns3::Ipv6Address', [], is_const=True) ## inet6-socket-address.h (module 'network'): uint16_t ns3::Inet6SocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet6-socket-address.h (module 'network'): static bool ns3::Inet6SocketAddress::IsMatchingType(ns3::Address const & addr) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetIpv6(ns3::Ipv6Address ipv6) [member function] cls.add_method('SetIpv6', 'void', [param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) return def register_Ns3InetSocketAddress_methods(root_module, cls): ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::InetSocketAddress const & arg0) [copy constructor] cls.add_constructor([param('ns3::InetSocketAddress const &', 'arg0')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4) [constructor] cls.add_constructor([param('char const *', 'ipv4')]) ## inet-socket-address.h (module 'network'): static ns3::InetSocketAddress ns3::InetSocketAddress::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::InetSocketAddress', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): ns3::Ipv4Address ns3::InetSocketAddress::GetIpv4() const [member function] cls.add_method('GetIpv4', 'ns3::Ipv4Address', [], is_const=True) ## inet-socket-address.h (module 'network'): uint16_t ns3::InetSocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet-socket-address.h (module 'network'): 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')]) return def register_Ns3IntToType__0_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType(ns3::IntToType<0> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 0 > const &', 'arg0')]) return def register_Ns3IntToType__1_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType(ns3::IntToType<1> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 1 > const &', 'arg0')]) return def register_Ns3IntToType__2_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType(ns3::IntToType<2> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 2 > const &', 'arg0')]) return def register_Ns3IntToType__3_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType(ns3::IntToType<3> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 3 > const &', 'arg0')]) return def register_Ns3IntToType__4_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType(ns3::IntToType<4> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 4 > const &', 'arg0')]) return def register_Ns3IntToType__5_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType(ns3::IntToType<5> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 5 > const &', 'arg0')]) return def register_Ns3IntToType__6_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType(ns3::IntToType<6> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 6 > const &', 'arg0')]) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4InterfaceAddress_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress() [constructor] cls.add_constructor([]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4Address local, ns3::Ipv4Mask mask) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'local'), param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4InterfaceAddress const & o) [copy constructor] cls.add_constructor([param('ns3::Ipv4InterfaceAddress const &', 'o')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetLocal() const [member function] cls.add_method('GetLocal', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Mask ns3::Ipv4InterfaceAddress::GetMask() const [member function] cls.add_method('GetMask', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e ns3::Ipv4InterfaceAddress::GetScope() const [member function] cls.add_method('GetScope', 'ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): bool ns3::Ipv4InterfaceAddress::IsSecondary() const [member function] cls.add_method('IsSecondary', 'bool', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetBroadcast(ns3::Ipv4Address broadcast) [member function] cls.add_method('SetBroadcast', 'void', [param('ns3::Ipv4Address', 'broadcast')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetLocal(ns3::Ipv4Address local) [member function] cls.add_method('SetLocal', 'void', [param('ns3::Ipv4Address', 'local')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetMask(ns3::Ipv4Mask mask) [member function] cls.add_method('SetMask', 'void', [param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetPrimary() [member function] cls.add_method('SetPrimary', 'void', []) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetScope(ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SetScope', 'void', [param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetSecondary() [member function] cls.add_method('SetSecondary', 'void', []) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function] cls.add_method('GetIpv4MappedAddress', 'ns3::Ipv4Address', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] cls.add_method('IsAllHostsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function] cls.add_method('IsDocumentation', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() [member function] cls.add_method('IsIpv4MappedAddress', 'bool', []) ## 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_Ns3Ipv6InterfaceAddress_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress() [constructor] cls.add_constructor([]) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6Address address) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'address')]) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6Address address, ns3::Ipv6Prefix prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6Prefix', 'prefix')]) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6InterfaceAddress const & o) [copy constructor] cls.add_constructor([param('ns3::Ipv6InterfaceAddress const &', 'o')]) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6InterfaceAddress::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): uint32_t ns3::Ipv6InterfaceAddress::GetNsDadUid() const [member function] cls.add_method('GetNsDadUid', 'uint32_t', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6Prefix ns3::Ipv6InterfaceAddress::GetPrefix() const [member function] cls.add_method('GetPrefix', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Scope_e ns3::Ipv6InterfaceAddress::GetScope() const [member function] cls.add_method('GetScope', 'ns3::Ipv6InterfaceAddress::Scope_e', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::State_e ns3::Ipv6InterfaceAddress::GetState() const [member function] cls.add_method('GetState', 'ns3::Ipv6InterfaceAddress::State_e', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetAddress(ns3::Ipv6Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Ipv6Address', 'address')]) ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetNsDadUid(uint32_t uid) [member function] cls.add_method('SetNsDadUid', 'void', [param('uint32_t', 'uid')]) ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetScope(ns3::Ipv6InterfaceAddress::Scope_e scope) [member function] cls.add_method('SetScope', 'void', [param('ns3::Ipv6InterfaceAddress::Scope_e', 'scope')]) ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetState(ns3::Ipv6InterfaceAddress::State_e state) [member function] cls.add_method('SetState', 'void', [param('ns3::Ipv6InterfaceAddress::State_e', 'state')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3LogComponent_methods(root_module, cls): ## log.h (module 'core'): ns3::LogComponent::LogComponent(ns3::LogComponent const & arg0) [copy constructor] cls.add_constructor([param('ns3::LogComponent const &', 'arg0')]) ## log.h (module 'core'): ns3::LogComponent::LogComponent(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## log.h (module 'core'): void ns3::LogComponent::Disable(ns3::LogLevel level) [member function] cls.add_method('Disable', 'void', [param('ns3::LogLevel', 'level')]) ## log.h (module 'core'): void ns3::LogComponent::Enable(ns3::LogLevel level) [member function] cls.add_method('Enable', 'void', [param('ns3::LogLevel', 'level')]) ## log.h (module 'core'): void ns3::LogComponent::EnvVarCheck(char const * name) [member function] cls.add_method('EnvVarCheck', 'void', [param('char const *', 'name')]) ## log.h (module 'core'): std::string ns3::LogComponent::GetLevelLabel(ns3::LogLevel const level) const [member function] cls.add_method('GetLevelLabel', 'std::string', [param('ns3::LogLevel const', 'level')], is_const=True) ## log.h (module 'core'): bool ns3::LogComponent::IsEnabled(ns3::LogLevel level) const [member function] cls.add_method('IsEnabled', 'bool', [param('ns3::LogLevel', 'level')], is_const=True) ## log.h (module 'core'): bool ns3::LogComponent::IsNoneEnabled() const [member function] cls.add_method('IsNoneEnabled', 'bool', [], is_const=True) ## log.h (module 'core'): char const * ns3::LogComponent::Name() const [member function] cls.add_method('Name', 'char const *', [], is_const=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function] cls.add_method('Replace', 'bool', [param('ns3::Tag &', 'tag')]) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 20 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Simulator_methods(root_module, cls): ## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Simulator const &', 'arg0')]) ## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function] cls.add_method('Cancel', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function] cls.add_method('Destroy', 'void', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function] cls.add_method('GetContext', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function] cls.add_method('GetImplementation', 'ns3::Ptr< ns3::SimulatorImpl >', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function] cls.add_method('GetMaximumSimulationTime', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function] cls.add_method('IsExpired', 'bool', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function] cls.add_method('IsFinished', 'bool', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function] cls.add_method('Now', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function] cls.add_method('Remove', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function] cls.add_method('SetImplementation', 'void', [param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function] cls.add_method('SetScheduler', 'void', [param('ns3::ObjectFactory', 'schedulerFactory')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function] cls.add_method('Stop', 'void', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & time) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'time')], is_static=True) return def register_Ns3SystemWallClockMs_methods(root_module, cls): ## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs(ns3::SystemWallClockMs const & arg0) [copy constructor] cls.add_constructor([param('ns3::SystemWallClockMs const &', 'arg0')]) ## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs() [constructor] cls.add_constructor([]) ## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::End() [member function] cls.add_method('End', 'int64_t', []) ## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedReal() const [member function] cls.add_method('GetElapsedReal', 'int64_t', [], is_const=True) ## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedSystem() const [member function] cls.add_method('GetElapsedSystem', 'int64_t', [], is_const=True) ## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedUser() const [member function] cls.add_method('GetElapsedUser', 'int64_t', [], is_const=True) ## system-wall-clock-ms.h (module 'core'): void ns3::SystemWallClockMs::Start() [member function] cls.add_method('Start', 'void', []) return def register_Ns3Tag_methods(root_module, cls): ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] cls.add_constructor([]) ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor] cls.add_constructor([param('ns3::Tag const &', 'arg0')]) ## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_virtual=True) ## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TagBuffer_methods(root_module, cls): ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor] cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')]) ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor] cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function] cls.add_method('CopyFrom', 'void', [param('ns3::TagBuffer', 'o')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function] cls.add_method('ReadDouble', 'double', []) ## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function] cls.add_method('TrimAtEnd', 'void', [param('uint32_t', 'trim')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function] cls.add_method('WriteDouble', 'void', [param('double', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'v')]) return def register_Ns3Timer_methods(root_module, cls): ## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Timer const &', 'arg0')]) ## timer.h (module 'core'): ns3::Timer::Timer() [constructor] cls.add_constructor([]) ## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer::DestroyPolicy destroyPolicy) [constructor] cls.add_constructor([param('ns3::Timer::DestroyPolicy', 'destroyPolicy')]) ## timer.h (module 'core'): void ns3::Timer::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelay() const [member function] cls.add_method('GetDelay', 'ns3::Time', [], is_const=True) ## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelayLeft() const [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [], is_const=True) ## timer.h (module 'core'): ns3::Timer::State ns3::Timer::GetState() const [member function] cls.add_method('GetState', 'ns3::Timer::State', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsSuspended() const [member function] cls.add_method('IsSuspended', 'bool', [], is_const=True) ## timer.h (module 'core'): void ns3::Timer::Remove() [member function] cls.add_method('Remove', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Resume() [member function] cls.add_method('Resume', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Schedule() [member function] cls.add_method('Schedule', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Schedule(ns3::Time delay) [member function] cls.add_method('Schedule', 'void', [param('ns3::Time', 'delay')]) ## timer.h (module 'core'): void ns3::Timer::SetDelay(ns3::Time const & delay) [member function] cls.add_method('SetDelay', 'void', [param('ns3::Time const &', 'delay')]) ## timer.h (module 'core'): void ns3::Timer::Suspend() [member function] cls.add_method('Suspend', 'void', []) return def register_Ns3TimerImpl_methods(root_module, cls): ## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl() [constructor] cls.add_constructor([]) ## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl(ns3::TimerImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimerImpl const &', 'arg0')]) ## timer-impl.h (module 'core'): void ns3::TimerImpl::Invoke() [member function] cls.add_method('Invoke', 'void', [], is_pure_virtual=True, is_virtual=True) ## timer-impl.h (module 'core'): ns3::EventId ns3::TimerImpl::Schedule(ns3::Time const & delay) [member function] cls.add_method('Schedule', 'ns3::EventId', [param('ns3::Time const &', 'delay')], is_pure_virtual=True, is_virtual=True) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function] cls.add_method('LookupByHash', 'ns3::TypeId', [param('uint32_t', 'hash')], is_static=True) ## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function] cls.add_method('LookupByHashFailSafe', 'bool', [param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')], is_static=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'tid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', 'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Ipv4Header_methods(root_module, cls): ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header(ns3::Ipv4Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Header const &', 'arg0')]) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header() [constructor] cls.add_constructor([]) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::DscpTypeToString(ns3::Ipv4Header::DscpType dscp) const [member function] cls.add_method('DscpTypeToString', 'std::string', [param('ns3::Ipv4Header::DscpType', 'dscp')], is_const=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::EcnTypeToString(ns3::Ipv4Header::EcnType ecn) const [member function] cls.add_method('EcnTypeToString', 'std::string', [param('ns3::Ipv4Header::EcnType', 'ecn')], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::EnableChecksum() [member function] cls.add_method('EnableChecksum', 'void', []) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType ns3::Ipv4Header::GetDscp() const [member function] cls.add_method('GetDscp', 'ns3::Ipv4Header::DscpType', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType ns3::Ipv4Header::GetEcn() const [member function] cls.add_method('GetEcn', 'ns3::Ipv4Header::EcnType', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetFragmentOffset() const [member function] cls.add_method('GetFragmentOffset', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetIdentification() const [member function] cls.add_method('GetIdentification', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::TypeId ns3::Ipv4Header::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetPayloadSize() const [member function] cls.add_method('GetPayloadSize', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetProtocol() const [member function] cls.add_method('GetProtocol', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): static ns3::TypeId ns3::Ipv4Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsChecksumOk() const [member function] cls.add_method('IsChecksumOk', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsDontFragment() const [member function] cls.add_method('IsDontFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsLastFragment() const [member function] cls.add_method('IsLastFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDestination(ns3::Ipv4Address destination) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'destination')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDontFragment() [member function] cls.add_method('SetDontFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDscp(ns3::Ipv4Header::DscpType dscp) [member function] cls.add_method('SetDscp', 'void', [param('ns3::Ipv4Header::DscpType', 'dscp')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetEcn(ns3::Ipv4Header::EcnType ecn) [member function] cls.add_method('SetEcn', 'void', [param('ns3::Ipv4Header::EcnType', 'ecn')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetFragmentOffset(uint16_t offsetBytes) [member function] cls.add_method('SetFragmentOffset', 'void', [param('uint16_t', 'offsetBytes')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetIdentification(uint16_t identification) [member function] cls.add_method('SetIdentification', 'void', [param('uint16_t', 'identification')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetLastFragment() [member function] cls.add_method('SetLastFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMayFragment() [member function] cls.add_method('SetMayFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMoreFragments() [member function] cls.add_method('SetMoreFragments', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetPayloadSize(uint16_t size) [member function] cls.add_method('SetPayloadSize', 'void', [param('uint16_t', 'size')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetProtocol(uint8_t num) [member function] cls.add_method('SetProtocol', 'void', [param('uint8_t', 'num')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetSource(ns3::Ipv4Address source) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'source')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3Ipv6Header_methods(root_module, cls): ## ipv6-header.h (module 'internet'): ns3::Ipv6Header::Ipv6Header(ns3::Ipv6Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6Header const &', 'arg0')]) ## ipv6-header.h (module 'internet'): ns3::Ipv6Header::Ipv6Header() [constructor] cls.add_constructor([]) ## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ipv6-header.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6Header::GetDestinationAddress() const [member function] cls.add_method('GetDestinationAddress', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::GetFlowLabel() const [member function] cls.add_method('GetFlowLabel', 'uint32_t', [], is_const=True) ## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## ipv6-header.h (module 'internet'): ns3::TypeId ns3::Ipv6Header::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetNextHeader() const [member function] cls.add_method('GetNextHeader', 'uint8_t', [], is_const=True) ## ipv6-header.h (module 'internet'): uint16_t ns3::Ipv6Header::GetPayloadLength() const [member function] cls.add_method('GetPayloadLength', 'uint16_t', [], is_const=True) ## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv6-header.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6Header::GetSourceAddress() const [member function] cls.add_method('GetSourceAddress', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetTrafficClass() const [member function] cls.add_method('GetTrafficClass', 'uint8_t', [], is_const=True) ## ipv6-header.h (module 'internet'): static ns3::TypeId ns3::Ipv6Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetDestinationAddress(ns3::Ipv6Address dst) [member function] cls.add_method('SetDestinationAddress', 'void', [param('ns3::Ipv6Address', 'dst')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetFlowLabel(uint32_t flow) [member function] cls.add_method('SetFlowLabel', 'void', [param('uint32_t', 'flow')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetHopLimit(uint8_t limit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'limit')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetNextHeader(uint8_t next) [member function] cls.add_method('SetNextHeader', 'void', [param('uint8_t', 'next')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetPayloadLength(uint16_t len) [member function] cls.add_method('SetPayloadLength', 'void', [param('uint16_t', 'len')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetSourceAddress(ns3::Ipv6Address src) [member function] cls.add_method('SetSourceAddress', 'void', [param('ns3::Ipv6Address', 'src')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetTrafficClass(uint8_t traffic) [member function] cls.add_method('SetTrafficClass', 'void', [param('uint8_t', 'traffic')]) return def register_Ns3Object_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::Object() [constructor] cls.add_constructor([]) ## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function] cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) ## object.h (module 'core'): void ns3::Object::Dispose() [member function] cls.add_method('Dispose', 'void', []) ## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function] cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) ## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object.h (module 'core'): void ns3::Object::Initialize() [member function] cls.add_method('Initialize', 'void', []) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor] cls.add_constructor([param('ns3::Object const &', 'o')], visibility='protected') ## object.h (module 'core'): void ns3::Object::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectAggregateIterator_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')]) ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor] cls.add_constructor([]) ## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4MulticastRoute > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4Route > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount(ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Socket_methods(root_module, cls): ## socket.h (module 'network'): ns3::Socket::Socket(ns3::Socket const & arg0) [copy constructor] cls.add_constructor([param('ns3::Socket const &', 'arg0')]) ## socket.h (module 'network'): ns3::Socket::Socket() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): int ns3::Socket::Bind(ns3::Address const & address) [member function] cls.add_method('Bind', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind() [member function] cls.add_method('Bind', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind6() [member function] cls.add_method('Bind6', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::BindToNetDevice(ns3::Ptr<ns3::NetDevice> netdevice) [member function] cls.add_method('BindToNetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'netdevice')], is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Close() [member function] cls.add_method('Close', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Connect(ns3::Address const & address) [member function] cls.add_method('Connect', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): static ns3::Ptr<ns3::Socket> ns3::Socket::CreateSocket(ns3::Ptr<ns3::Node> node, ns3::TypeId tid) [member function] cls.add_method('CreateSocket', 'ns3::Ptr< ns3::Socket >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::TypeId', 'tid')], is_static=True) ## socket.h (module 'network'): bool ns3::Socket::GetAllowBroadcast() const [member function] cls.add_method('GetAllowBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Socket::GetBoundNetDevice() [member function] cls.add_method('GetBoundNetDevice', 'ns3::Ptr< ns3::NetDevice >', []) ## socket.h (module 'network'): ns3::Socket::SocketErrno ns3::Socket::GetErrno() const [member function] cls.add_method('GetErrno', 'ns3::Socket::SocketErrno', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTos() const [member function] cls.add_method('GetIpTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTtl() const [member function] cls.add_method('GetIpTtl', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6HopLimit() const [member function] cls.add_method('GetIpv6HopLimit', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6Tclass() const [member function] cls.add_method('GetIpv6Tclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Socket::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): 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'): bool ns3::Socket::IsIpRecvTos() const [member function] cls.add_method('IsIpRecvTos', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTtl() const [member function] cls.add_method('IsIpRecvTtl', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvHopLimit() const [member function] cls.add_method('IsIpv6RecvHopLimit', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvTclass() const [member function] cls.add_method('IsIpv6RecvTclass', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsRecvPktInfo() const [member function] cls.add_method('IsRecvPktInfo', 'bool', [], is_const=True) ## socket.h (module 'network'): int ns3::Socket::Listen() [member function] cls.add_method('Listen', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv(uint32_t maxSize, uint32_t flags) [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', []) ## socket.h (module 'network'): int ns3::Socket::Recv(uint8_t * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Recv', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::RecvFrom(uint8_t * buf, uint32_t size, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## socket.h (module 'network'): int ns3::Socket::Send(uint8_t const * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): int ns3::Socket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function] cls.add_method('SendTo', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::SendTo(uint8_t const * buf, uint32_t size, uint32_t flags, ns3::Address const & address) [member function] cls.add_method('SendTo', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address const &', 'address')]) ## socket.h (module 'network'): void ns3::Socket::SetAcceptCallback(ns3::Callback<bool, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionRequest, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> newConnectionCreated) [member function] cls.add_method('SetAcceptCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionRequest'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'newConnectionCreated')]) ## socket.h (module 'network'): bool ns3::Socket::SetAllowBroadcast(bool allowBroadcast) [member function] cls.add_method('SetAllowBroadcast', 'bool', [param('bool', 'allowBroadcast')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetCloseCallbacks(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> normalClose, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> errorClose) [member function] cls.add_method('SetCloseCallbacks', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'normalClose'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'errorClose')]) ## socket.h (module 'network'): void ns3::Socket::SetConnectCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionSucceeded, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionFailed) [member function] cls.add_method('SetConnectCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionSucceeded'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionFailed')]) ## socket.h (module 'network'): void ns3::Socket::SetDataSentCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> dataSent) [member function] cls.add_method('SetDataSentCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'dataSent')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTos(bool ipv4RecvTos) [member function] cls.add_method('SetIpRecvTos', 'void', [param('bool', 'ipv4RecvTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTtl(bool ipv4RecvTtl) [member function] cls.add_method('SetIpRecvTtl', 'void', [param('bool', 'ipv4RecvTtl')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTos(uint8_t ipTos) [member function] cls.add_method('SetIpTos', 'void', [param('uint8_t', 'ipTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTtl(uint8_t ipTtl) [member function] cls.add_method('SetIpTtl', 'void', [param('uint8_t', 'ipTtl')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6HopLimit(uint8_t ipHopLimit) [member function] cls.add_method('SetIpv6HopLimit', 'void', [param('uint8_t', 'ipHopLimit')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvHopLimit(bool ipv6RecvHopLimit) [member function] cls.add_method('SetIpv6RecvHopLimit', 'void', [param('bool', 'ipv6RecvHopLimit')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvTclass(bool ipv6RecvTclass) [member function] cls.add_method('SetIpv6RecvTclass', 'void', [param('bool', 'ipv6RecvTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6Tclass(int ipTclass) [member function] cls.add_method('SetIpv6Tclass', 'void', [param('int', 'ipTclass')]) ## socket.h (module 'network'): void ns3::Socket::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::IsManualIpTos() const [member function] cls.add_method('IsManualIpTos', 'bool', [], is_const=True, visibility='protected') ## 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_Ns3SocketAddressTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketAddressTag::SocketAddressTag(ns3::SocketAddressTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketAddressTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketAddressTag::SocketAddressTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketAddressTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::Address ns3::SocketAddressTag::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketAddressTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketAddressTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketAddressTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketAddressTag::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::SocketAddressTag::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::SocketAddressTag::SetAddress(ns3::Address addr) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'addr')]) return def register_Ns3SocketIpTosTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag(ns3::SocketIpTosTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpTosTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTosTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTosTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTosTag::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTosTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) return def register_Ns3SocketIpTtlTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag(ns3::SocketIpTtlTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpTtlTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTtlTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTtlTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTtlTag::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTtlTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3SocketIpv6HopLimitTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag(ns3::SocketIpv6HopLimitTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpv6HopLimitTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6HopLimitTag::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6HopLimitTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6HopLimitTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6HopLimitTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::SetHopLimit(uint8_t hopLimit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'hopLimit')]) return def register_Ns3SocketIpv6TclassTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag(ns3::SocketIpv6TclassTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpv6TclassTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6TclassTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6TclassTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6TclassTag::GetTclass() const [member function] cls.add_method('GetTclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6TclassTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::SetTclass(uint8_t tclass) [member function] cls.add_method('SetTclass', 'void', [param('uint8_t', 'tclass')]) return def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Disable() [member function] cls.add_method('Disable', 'void', []) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Enable() [member function] cls.add_method('Enable', 'void', []) ## socket.h (module 'network'): ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function] cls.add_method('IsEnabled', 'bool', [], is_const=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) return def register_Ns3Time_methods(root_module, cls): cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', 'right')) cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', 'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & value) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'value')]) ## 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 & from, ns3::Time::Unit timeUnit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'from'), param('ns3::Time::Unit', 'timeUnit')], is_static=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::FromDouble(double value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=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'): 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'): 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'): 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 timeUnit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function] cls.add_method('CreateValidValue', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::AttributeValue const &', 'value')], is_const=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')]) return def register_Ns3CallbackImplBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) ## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_Ns3EmptyAttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, visibility='private', is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], visibility='private', is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3EventImpl_methods(root_module, cls): ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventImpl const &', 'arg0')]) ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor] cls.add_constructor([]) ## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function] cls.add_method('Invoke', 'void', []) ## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function] cls.add_method('IsCancelled', 'bool', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function] cls.add_method('Notify', 'void', [], is_pure_virtual=True, visibility='protected', is_virtual=True) return def register_Ns3IpL4Protocol_methods(root_module, cls): ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::IpL4Protocol() [constructor] cls.add_constructor([]) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::IpL4Protocol(ns3::IpL4Protocol const & arg0) [copy constructor] cls.add_constructor([param('ns3::IpL4Protocol const &', 'arg0')]) ## ip-l4-protocol.h (module 'internet'): ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv4Address,ns3::Ipv4Address,unsigned char,ns3::Ptr<ns3::Ipv4Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::IpL4Protocol::GetDownTarget() const [member function] cls.add_method('GetDownTarget', 'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv4Address, ns3::Ipv4Address, unsigned char, ns3::Ptr< ns3::Ipv4Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv6Address,ns3::Ipv6Address,unsigned char,ns3::Ptr<ns3::Ipv6Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::IpL4Protocol::GetDownTarget6() const [member function] cls.add_method('GetDownTarget6', 'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv6Address, ns3::Ipv6Address, unsigned char, ns3::Ptr< ns3::Ipv6Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): int ns3::IpL4Protocol::GetProtocolNumber() const [member function] cls.add_method('GetProtocolNumber', 'int', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): static ns3::TypeId ns3::IpL4Protocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::IpL4Protocol::Receive(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::Ipv4Interface> incomingInterface) [member function] cls.add_method('Receive', 'ns3::IpL4Protocol::RxStatus', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::Ipv4Interface >', 'incomingInterface')], is_pure_virtual=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::IpL4Protocol::Receive(ns3::Ptr<ns3::Packet> p, ns3::Ipv6Header const & header, ns3::Ptr<ns3::Ipv6Interface> incomingInterface) [member function] cls.add_method('Receive', 'ns3::IpL4Protocol::RxStatus', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv6Header const &', 'header'), param('ns3::Ptr< ns3::Ipv6Interface >', 'incomingInterface')], is_pure_virtual=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::ReceiveIcmp(ns3::Ipv4Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, ns3::Ipv4Address payloadSource, ns3::Ipv4Address payloadDestination, uint8_t const * payload) [member function] cls.add_method('ReceiveIcmp', 'void', [param('ns3::Ipv4Address', 'icmpSource'), param('uint8_t', 'icmpTtl'), param('uint8_t', 'icmpType'), param('uint8_t', 'icmpCode'), param('uint32_t', 'icmpInfo'), param('ns3::Ipv4Address', 'payloadSource'), param('ns3::Ipv4Address', 'payloadDestination'), param('uint8_t const *', 'payload')], is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::ReceiveIcmp(ns3::Ipv6Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, ns3::Ipv6Address payloadSource, ns3::Ipv6Address payloadDestination, uint8_t const * payload) [member function] cls.add_method('ReceiveIcmp', 'void', [param('ns3::Ipv6Address', 'icmpSource'), param('uint8_t', 'icmpTtl'), param('uint8_t', 'icmpType'), param('uint8_t', 'icmpCode'), param('uint32_t', 'icmpInfo'), param('ns3::Ipv6Address', 'payloadSource'), param('ns3::Ipv6Address', 'payloadDestination'), param('uint8_t const *', 'payload')], is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::SetDownTarget(ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv4Address,ns3::Ipv4Address,unsigned char,ns3::Ptr<ns3::Ipv4Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetDownTarget', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv4Address, ns3::Ipv4Address, unsigned char, ns3::Ptr< ns3::Ipv4Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::SetDownTarget6(ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv6Address,ns3::Ipv6Address,unsigned char,ns3::Ptr<ns3::Ipv6Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetDownTarget6', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv6Address, ns3::Ipv6Address, unsigned char, ns3::Ptr< ns3::Ipv6Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) return def register_Ns3Ipv4_methods(root_module, cls): ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4(ns3::Ipv4 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4 const &', 'arg0')]) ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4() [constructor] cls.add_constructor([]) ## ipv4.h (module 'internet'): bool ns3::Ipv4::AddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', [], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4::GetAddress(uint32_t interface, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForAddress(ns3::Ipv4Address address) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv4Address', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForPrefix(ns3::Ipv4Address address, ns3::Ipv4Mask mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv4Address', 'address'), param('ns3::Ipv4Mask', 'mask')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMetric(uint32_t interface) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMtu(uint32_t interface) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4::GetNetDevice(uint32_t interface) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::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'): 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'): 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::Ipv4::IF_ANY [variable] cls.add_static_attribute('IF_ANY', 'uint32_t const', is_const=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::GetWeakEsModel() const [member function] cls.add_method('GetWeakEsModel', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], is_pure_virtual=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetWeakEsModel(bool model) [member function] cls.add_method('SetWeakEsModel', 'void', [param('bool', 'model')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3Ipv4AddressChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')]) return def register_Ns3Ipv4AddressValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Address const &', 'value')]) return def register_Ns3Ipv4Interface_methods(root_module, cls): ## ipv4-interface.h (module 'internet'): ns3::Ipv4Interface::Ipv4Interface(ns3::Ipv4Interface const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Interface const &', 'arg0')]) ## ipv4-interface.h (module 'internet'): ns3::Ipv4Interface::Ipv4Interface() [constructor] cls.add_constructor([]) ## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::AddAddress(ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('ns3::Ipv4InterfaceAddress', 'address')]) ## ipv4-interface.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4Interface::GetAddress(uint32_t index) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'index')], is_const=True) ## ipv4-interface.h (module 'internet'): ns3::Ptr<ns3::ArpCache> ns3::Ipv4Interface::GetArpCache() const [member function] cls.add_method('GetArpCache', 'ns3::Ptr< ns3::ArpCache >', [], is_const=True) ## ipv4-interface.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Interface::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## ipv4-interface.h (module 'internet'): uint16_t ns3::Ipv4Interface::GetMetric() const [member function] cls.add_method('GetMetric', 'uint16_t', [], is_const=True) ## ipv4-interface.h (module 'internet'): uint32_t ns3::Ipv4Interface::GetNAddresses() const [member function] cls.add_method('GetNAddresses', 'uint32_t', [], is_const=True) ## ipv4-interface.h (module 'internet'): static ns3::TypeId ns3::Ipv4Interface::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::IsDown() const [member function] cls.add_method('IsDown', 'bool', [], is_const=True) ## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::IsForwarding() const [member function] cls.add_method('IsForwarding', 'bool', [], is_const=True) ## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::IsUp() const [member function] cls.add_method('IsUp', 'bool', [], is_const=True) ## ipv4-interface.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4Interface::RemoveAddress(uint32_t index) [member function] cls.add_method('RemoveAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'index')]) ## ipv4-interface.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4Interface::RemoveAddress(ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'ns3::Ipv4InterfaceAddress', [param('ns3::Ipv4Address', 'address')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::Send(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Address dest) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Address', 'dest')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetArpCache(ns3::Ptr<ns3::ArpCache> arg0) [member function] cls.add_method('SetArpCache', 'void', [param('ns3::Ptr< ns3::ArpCache >', 'arg0')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetDown() [member function] cls.add_method('SetDown', 'void', []) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetForwarding(bool val) [member function] cls.add_method('SetForwarding', 'void', [param('bool', 'val')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetMetric(uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint16_t', 'metric')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetUp() [member function] cls.add_method('SetUp', 'void', []) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3Ipv4L3ClickProtocol_methods(root_module, cls): ## ipv4-l3-click-protocol.h (module 'click'): ns3::Ipv4L3ClickProtocol::Ipv4L3ClickProtocol() [constructor] cls.add_constructor([]) ## ipv4-l3-click-protocol.h (module 'click'): ns3::Ipv4L3ClickProtocol::Ipv4L3ClickProtocol(ns3::Ipv4L3ClickProtocol const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4L3ClickProtocol const &', 'arg0')]) return def register_Ns3Ipv4MaskChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')]) return def register_Ns3Ipv4MaskValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Mask const &', 'value')]) return def register_Ns3Ipv4MulticastRoute_methods(root_module, cls): ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute(ns3::Ipv4MulticastRoute const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MulticastRoute const &', 'arg0')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute() [constructor] cls.add_constructor([]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetGroup() const [member function] cls.add_method('GetGroup', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetOrigin() const [member function] cls.add_method('GetOrigin', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetOutputTtl(uint32_t oif) [member function] cls.add_method('GetOutputTtl', 'uint32_t', [param('uint32_t', 'oif')], deprecated=True) ## ipv4-route.h (module 'internet'): std::map<unsigned int, unsigned int, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, unsigned int> > > ns3::Ipv4MulticastRoute::GetOutputTtlMap() const [member function] cls.add_method('GetOutputTtlMap', 'std::map< unsigned int, unsigned int >', [], is_const=True) ## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetParent() const [member function] cls.add_method('GetParent', 'uint32_t', [], is_const=True) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetGroup(ns3::Ipv4Address const group) [member function] cls.add_method('SetGroup', 'void', [param('ns3::Ipv4Address const', 'group')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOrigin(ns3::Ipv4Address const origin) [member function] cls.add_method('SetOrigin', 'void', [param('ns3::Ipv4Address const', 'origin')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOutputTtl(uint32_t oif, uint32_t ttl) [member function] cls.add_method('SetOutputTtl', 'void', [param('uint32_t', 'oif'), param('uint32_t', 'ttl')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetParent(uint32_t iif) [member function] cls.add_method('SetParent', 'void', [param('uint32_t', 'iif')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_INTERFACES [variable] cls.add_static_attribute('MAX_INTERFACES', 'uint32_t const', is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_TTL [variable] cls.add_static_attribute('MAX_TTL', 'uint32_t const', is_const=True) return def register_Ns3Ipv4Route_methods(root_module, cls): cls.add_output_stream_operator() ## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route(ns3::Ipv4Route const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Route const &', 'arg0')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route() [constructor] cls.add_constructor([]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetGateway() const [member function] cls.add_method('GetGateway', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Route::GetOutputDevice() const [member function] cls.add_method('GetOutputDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetDestination(ns3::Ipv4Address dest) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'dest')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetGateway(ns3::Ipv4Address gw) [member function] cls.add_method('SetGateway', 'void', [param('ns3::Ipv4Address', 'gw')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetOutputDevice(ns3::Ptr<ns3::NetDevice> outputDevice) [member function] cls.add_method('SetOutputDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'outputDevice')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetSource(ns3::Ipv4Address src) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'src')]) return def register_Ns3Ipv4RoutingProtocol_methods(root_module, cls): ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol() [constructor] cls.add_constructor([]) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol(ns3::Ipv4RoutingProtocol const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4RoutingProtocol const &', 'arg0')]) ## ipv4-routing-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4RoutingProtocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): bool ns3::Ipv4RoutingProtocol::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, 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> ucb, ns3::Callback<void,ns3::Ptr<ns3::Ipv4MulticastRoute>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> mcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,unsigned int,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> lcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::Socket::SocketErrno,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ecb) [member function] cls.add_method('RouteInput', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv4Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], is_pure_virtual=True, is_virtual=True) return def register_Ns3Ipv6AddressChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')]) return def register_Ns3Ipv6AddressValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Address const &', 'value')]) return def register_Ns3Ipv6Interface_methods(root_module, cls): ## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface::Ipv6Interface(ns3::Ipv6Interface const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6Interface const &', 'arg0')]) ## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface::Ipv6Interface() [constructor] cls.add_constructor([]) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::AddAddress(ns3::Ipv6InterfaceAddress iface) [member function] cls.add_method('AddAddress', 'bool', [param('ns3::Ipv6InterfaceAddress', 'iface')]) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetAddress(uint32_t index) const [member function] cls.add_method('GetAddress', 'ns3::Ipv6InterfaceAddress', [param('uint32_t', 'index')], is_const=True) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetAddressMatchingDestination(ns3::Ipv6Address dst) [member function] cls.add_method('GetAddressMatchingDestination', 'ns3::Ipv6InterfaceAddress', [param('ns3::Ipv6Address', 'dst')]) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetBaseReachableTime() const [member function] cls.add_method('GetBaseReachableTime', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint8_t ns3::Ipv6Interface::GetCurHopLimit() const [member function] cls.add_method('GetCurHopLimit', 'uint8_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv6Interface::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True, is_virtual=True) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetLinkLocalAddress() const [member function] cls.add_method('GetLinkLocalAddress', 'ns3::Ipv6InterfaceAddress', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetMetric() const [member function] cls.add_method('GetMetric', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint32_t ns3::Ipv6Interface::GetNAddresses() const [member function] cls.add_method('GetNAddresses', 'uint32_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetReachableTime() const [member function] cls.add_method('GetReachableTime', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetRetransTimer() const [member function] cls.add_method('GetRetransTimer', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): static ns3::TypeId ns3::Ipv6Interface::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsDown() const [member function] cls.add_method('IsDown', 'bool', [], is_const=True) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsForwarding() const [member function] cls.add_method('IsForwarding', 'bool', [], is_const=True) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsUp() const [member function] cls.add_method('IsUp', 'bool', [], is_const=True) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::RemoveAddress(uint32_t index) [member function] cls.add_method('RemoveAddress', 'ns3::Ipv6InterfaceAddress', [param('uint32_t', 'index')]) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::RemoveAddress(ns3::Ipv6Address address) [member function] cls.add_method('RemoveAddress', 'ns3::Ipv6InterfaceAddress', [param('ns3::Ipv6Address', 'address')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::Send(ns3::Ptr<ns3::Packet> p, ns3::Ipv6Address dest) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv6Address', 'dest')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetBaseReachableTime(uint16_t baseReachableTime) [member function] cls.add_method('SetBaseReachableTime', 'void', [param('uint16_t', 'baseReachableTime')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetCurHopLimit(uint8_t curHopLimit) [member function] cls.add_method('SetCurHopLimit', 'void', [param('uint8_t', 'curHopLimit')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetDown() [member function] cls.add_method('SetDown', 'void', []) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetForwarding(bool forward) [member function] cls.add_method('SetForwarding', 'void', [param('bool', 'forward')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetMetric(uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint16_t', 'metric')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetNsDadUid(ns3::Ipv6Address address, uint32_t uid) [member function] cls.add_method('SetNsDadUid', 'void', [param('ns3::Ipv6Address', 'address'), param('uint32_t', 'uid')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetReachableTime(uint16_t reachableTime) [member function] cls.add_method('SetReachableTime', 'void', [param('uint16_t', 'reachableTime')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetRetransTimer(uint16_t retransTimer) [member function] cls.add_method('SetRetransTimer', 'void', [param('uint16_t', 'retransTimer')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetState(ns3::Ipv6Address address, ns3::Ipv6InterfaceAddress::State_e state) [member function] cls.add_method('SetState', 'void', [param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6InterfaceAddress::State_e', 'state')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetUp() [member function] cls.add_method('SetUp', 'void', []) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3Ipv6PrefixChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')]) return def register_Ns3Ipv6PrefixValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Prefix const &', 'value')]) return def register_Ns3NetDevice_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDevice const &', 'arg0')]) ## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,const ns3::Address&,ns3::NetDevice::PacketType,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor] cls.add_constructor([param('ns3::NixVector const &', 'o')]) ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] cls.add_method('AddNeighborIndex', 'void', [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] cls.add_method('BitCount', 'uint32_t', [param('uint32_t', 'numberOfNeighbors')], is_const=True) ## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] cls.add_method('ExtractNeighborIndex', 'uint32_t', [param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] cls.add_method('GetRemainingBits', 'uint32_t', []) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_Ns3OutputStreamWrapper_methods(root_module, cls): ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(ns3::OutputStreamWrapper const & arg0) [copy constructor] cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::_Ios_Openmode filemode) [constructor] cls.add_constructor([param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor] cls.add_constructor([param('std::ostream *', 'os')]) ## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function] cls.add_method('GetStream', 'std::ostream *', []) return def register_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor] cls.add_constructor([param('ns3::Packet const &', 'o')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] cls.add_constructor([param('uint32_t', 'size')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<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'): uint8_t const * ns3::Packet::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], deprecated=True, 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> arg0) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'arg0')]) return def register_Ns3TimeValue_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor] cls.add_constructor([param('ns3::Time const &', 'value')]) ## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function] cls.add_method('Get', 'ns3::Time', [], is_const=True) ## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Time const &', 'value')]) return def register_Ns3TypeIdChecker_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')]) return def register_Ns3TypeIdValue_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function] cls.add_method('Get', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function] cls.add_method('Set', 'void', [param('ns3::TypeId const &', 'value')]) return def register_Ns3AddressChecker_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')]) return def register_Ns3AddressValue_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor] cls.add_constructor([param('ns3::Address const &', 'value')]) ## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Address', [], is_const=True) ## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Address const &', 'value')]) return def register_Ns3Ipv4ClickRouting_methods(root_module, cls): ## ipv4-click-routing.h (module 'click'): ns3::Ipv4ClickRouting::Ipv4ClickRouting() [constructor] cls.add_constructor([]) ## ipv4-click-routing.h (module 'click'): ns3::Ipv4ClickRouting::Ipv4ClickRouting(ns3::Ipv4ClickRouting const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4ClickRouting const &', 'arg0')]) return def register_Ns3HashImplementation_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Implementation const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation() [constructor] cls.add_constructor([]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Implementation::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_pure_virtual=True, is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Implementation::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Implementation::clear() [member function] cls.add_method('clear', 'void', [], is_pure_virtual=True, is_virtual=True) return def register_Ns3HashFunctionFnv1a_methods(root_module, cls): ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a(ns3::Hash::Function::Fnv1a const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')]) ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a() [constructor] cls.add_constructor([]) ## hash-fnv.h (module 'core'): uint32_t ns3::Hash::Function::Fnv1a::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): uint64_t ns3::Hash::Function::Fnv1a::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): void ns3::Hash::Function::Fnv1a::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash32_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Function::Hash32 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash32 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Hash32Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash32Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash32::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash32::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash64_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Function::Hash64 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash64 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Hash64Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash64Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash64::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash64::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionMurmur3_methods(root_module, cls): ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3(ns3::Hash::Function::Murmur3 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')]) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor] cls.add_constructor([]) ## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_functions(root_module): module = root_module register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_Hash(module.get_submodule('Hash'), root_module) 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 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()
mcgee/ns-3
src/click/bindings/modulegen__gcc_LP64.py
Python
gpl-2.0
362,122
from flask import Blueprint auth = Blueprint('auth', __name__) from . import views
federicoviola/alpha
wsgi/app/auth/__init__.py
Python
mit
84
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, 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. from collections import Sequence # noqa import logging from django.conf import settings from horizon import exceptions import six __all__ = ('APIResourceWrapper', 'APIDictWrapper', 'get_service_from_catalog', 'url_for',) LOG = logging.getLogger(__name__) class APIVersionManager(object): """Object to store and manage API versioning data and utility methods.""" SETTINGS_KEY = "OPENSTACK_API_VERSIONS" def __init__(self, service_type, preferred_version=None): self.service_type = service_type self.preferred = preferred_version self._active = None self.supported = {} # As a convenience, we can drop in a placeholder for APIs that we # have not yet needed to version. This is useful, for example, when # panels such as the admin metadata_defs wants to check the active # version even though it's not explicitly defined. Previously # this caused a KeyError. if self.preferred: self.supported[self.preferred] = {"version": self.preferred} @property def active(self): if self._active is None: self.get_active_version() return self._active def load_supported_version(self, version, data): self.supported[version] = data def get_active_version(self): if self._active is not None: return self.supported[self._active] key = getattr(settings, self.SETTINGS_KEY, {}).get(self.service_type) if key is None: # TODO(gabriel): support API version discovery here; we'll leave # the setting in as a way of overriding the latest available # version. key = self.preferred # Since we do a key lookup in the supported dict the type matters, # let's ensure people know if they use a string when the key isn't. if isinstance(key, six.string_types): msg = ('The version "%s" specified for the %s service should be ' 'either an integer or a float, not a string.' % (key, self.service_type)) raise exceptions.ConfigurationError(msg) # Provide a helpful error message if the specified version isn't in the # supported list. if key not in self.supported: choices = ", ".join(str(k) for k in six.iterkeys(self.supported)) msg = ('%s is not a supported API version for the %s service, ' ' choices are: %s' % (key, self.service_type, choices)) raise exceptions.ConfigurationError(msg) self._active = key return self.supported[self._active] def clear_active_cache(self): self._active = None class APIResourceWrapper(object): """Simple wrapper for api objects. Define _attrs on the child class and pass in the api object as the only argument to the constructor """ _attrs = [] _apiresource = None # Make sure _apiresource is there even in __init__. def __init__(self, apiresource): self._apiresource = apiresource def __getattribute__(self, attr): try: return object.__getattribute__(self, attr) except AttributeError: if attr not in self._attrs: raise # __getattr__ won't find properties return getattr(self._apiresource, attr) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, dict((attr, getattr(self, attr)) for attr in self._attrs if hasattr(self, attr))) def to_dict(self): obj = {} for key in self._attrs: obj[key] = getattr(self._apiresource, key, None) return obj class APIDictWrapper(object): """Simple wrapper for api dictionaries Some api calls return dictionaries. This class provides identical behavior as APIResourceWrapper, except that it will also behave as a dictionary, in addition to attribute accesses. Attribute access is the preferred method of access, to be consistent with api resource objects from novaclient. """ _apidict = {} # Make sure _apidict is there even in __init__. def __init__(self, apidict): self._apidict = apidict def __getattribute__(self, attr): try: return object.__getattribute__(self, attr) except AttributeError: if attr not in self._apidict: raise return self._apidict[attr] def __getitem__(self, item): try: return getattr(self, item) except (AttributeError, TypeError) as e: # caller is expecting a KeyError raise KeyError(e) def __contains__(self, item): try: return hasattr(self, item) except TypeError: return False def get(self, item, default=None): try: return getattr(self, item) except (AttributeError, TypeError): return default def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self._apidict) def to_dict(self): return self._apidict class Quota(object): """Wrapper for individual limits in a quota.""" def __init__(self, name, limit): self.name = name self.limit = limit def __repr__(self): return "<Quota: (%s, %s)>" % (self.name, self.limit) class QuotaSet(Sequence): """Wrapper for client QuotaSet objects which turns the individual quotas into Quota objects for easier handling/iteration. `QuotaSet` objects support a mix of `list` and `dict` methods; you can use the bracket notation (`qs["my_quota"] = 0`) to add new quota values, and use the `get` method to retrieve a specific quota, but otherwise it behaves much like a list or tuple, particularly in supporting iteration. """ def __init__(self, apiresource=None): self.items = [] if apiresource: if hasattr(apiresource, '_info'): items = apiresource._info.items() else: items = apiresource.items() for k, v in items: if k == 'id': continue self[k] = v def __setitem__(self, k, v): v = int(v) if v is not None else v q = Quota(k, v) self.items.append(q) def __getitem__(self, index): return self.items[index] def __add__(self, other): """Merge another QuotaSet into this one. Existing quotas are not overridden. """ if not isinstance(other, QuotaSet): msg = "Can only add QuotaSet to QuotaSet, " \ "but received %s instead" % type(other) raise ValueError(msg) for item in other: if self.get(item.name).limit is None: self.items.append(item) return self def __len__(self): return len(self.items) def __repr__(self): return repr(self.items) def get(self, key, default=None): match = [quota for quota in self.items if quota.name == key] return match.pop() if len(match) else Quota(key, default) def add(self, other): return self.__add__(other) def get_service_from_catalog(catalog, service_type): if catalog: for service in catalog: if 'type' not in service: continue if service['type'] == service_type: return service return None def get_version_from_service(service): if service and service.get('endpoints'): endpoint = service['endpoints'][0] if 'interface' in endpoint: return 3 else: return 2.0 return 2.0 # Mapping of V2 Catalog Endpoint_type to V3 Catalog Interfaces ENDPOINT_TYPE_TO_INTERFACE = { 'publicURL': 'public', 'internalURL': 'internal', 'adminURL': 'admin', } def get_url_for_service(service, region, endpoint_type): if 'type' not in service: return None identity_version = get_version_from_service(service) service_endpoints = service.get('endpoints', []) available_endpoints = [endpoint for endpoint in service_endpoints if region == _get_endpoint_region(endpoint)] """if we are dealing with the identity service and there is no endpoint in the current region, it is okay to use the first endpoint for any identity service endpoints and we can assume that it is global """ if service['type'] == 'identity' and not available_endpoints: available_endpoints = [endpoint for endpoint in service_endpoints] for endpoint in available_endpoints: try: if identity_version < 3: return endpoint.get(endpoint_type) else: interface = \ ENDPOINT_TYPE_TO_INTERFACE.get(endpoint_type, '') if endpoint.get('interface') == interface: return endpoint.get('url') except (IndexError, KeyError): """it could be that the current endpoint just doesn't match the type, continue trying the next one """ pass return None def url_for(request, service_type, endpoint_type=None, region=None): endpoint_type = endpoint_type or getattr(settings, 'OPENSTACK_ENDPOINT_TYPE', 'publicURL') fallback_endpoint_type = getattr(settings, 'SECONDARY_ENDPOINT_TYPE', None) catalog = request.user.service_catalog service = get_service_from_catalog(catalog, service_type) if service: if not region: region = request.user.services_region url = get_url_for_service(service, region, endpoint_type) if not url and fallback_endpoint_type: url = get_url_for_service(service, region, fallback_endpoint_type) if url: return url raise exceptions.ServiceCatalogException(service_type) def is_service_enabled(request, service_type, service_name=None): service = get_service_from_catalog(request.user.service_catalog, service_type) if service: region = request.user.services_region for endpoint in service.get('endpoints', []): if 'type' not in service: continue # ignore region for identity if service['type'] == 'identity' or \ _get_endpoint_region(endpoint) == region: if service_name: return service.get('name') == service_name else: return True return False def _get_endpoint_region(endpoint): """Common function for getting the region from endpoint. In Keystone V3, region has been deprecated in favor of region_id. This method provides a way to get region that works for both Keystone V2 and V3. """ return endpoint.get('region_id') or endpoint.get('region')
Daniex/horizon
openstack_dashboard/api/base.py
Python
apache-2.0
12,076
from mod_pywebsocket import handshake from mod_pywebsocket.handshake.hybi import compute_accept def web_socket_do_extra_handshake(request): message = 'HTTP/1.1 101 Switching Protocols\r\n' message += 'Upgrade: websocket\r\n' message += 'Connection: Upgrade\r\n' message += 'Sec-WebSocket-Accept: %s\r\n' % compute_accept(request.headers_in['Sec-WebSocket-Key'])[0] message += 'foo: bar, baz\r\n' message += 'foo: hoge\r\n' message += 'FOO: FUGA\r\n' message += 'xxx: yyy\r\n' message += '\r\n' request.connection.write(message) # Prevents pywebsocket from sending its own handshake message. raise handshake.AbortedByUserException('Abort the connection') def web_socket_transfer_data(request): pass
axinging/chromium-crosswalk
third_party/WebKit/LayoutTests/http/tests/websocket/duplicated-headers_wsh.py
Python
bsd-3-clause
754
#!/usr/bin/python # (c) 2017, NetApp, 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: na_cdot_qtree short_description: Manage qtrees extends_documentation_fragment: - netapp.ontap version_added: '2.3' author: Sumit Kumar (sumit4@netapp.com) description: - Create or destroy Qtrees. options: state: description: - Whether the specified Qtree should exist or not. required: true choices: ['present', 'absent'] name: description: - The name of the Qtree to manage. required: true flexvol_name: description: - The name of the FlexVol the Qtree should exist on. Required when C(state=present). vserver: description: - The name of the vserver to use. required: true ''' EXAMPLES = """ - name: Create QTree na_cdot_qtree: state: present name: ansibleQTree flexvol_name: ansibleVolume vserver: ansibleVServer hostname: "{{ netapp_hostname }}" username: "{{ netapp_username }}" password: "{{ netapp_password }}" - name: Rename QTree na_cdot_qtree: state: present name: ansibleQTree flexvol_name: ansibleVolume vserver: ansibleVServer hostname: "{{ netapp_hostname }}" username: "{{ netapp_username }}" password: "{{ netapp_password }}" """ RETURN = """ """ import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native import ansible.module_utils.netapp as netapp_utils HAS_NETAPP_LIB = netapp_utils.has_netapp_lib() class NetAppCDOTQTree(object): def __init__(self): self.argument_spec = netapp_utils.ontap_sf_host_argument_spec() self.argument_spec.update(dict( state=dict(required=True, choices=['present', 'absent']), name=dict(required=True, type='str'), flexvol_name=dict(type='str'), vserver=dict(required=True, type='str'), )) self.module = AnsibleModule( argument_spec=self.argument_spec, required_if=[ ('state', 'present', ['flexvol_name']) ], supports_check_mode=True ) p = self.module.params # set up state variables self.state = p['state'] self.name = p['name'] self.flexvol_name = p['flexvol_name'] self.vserver = p['vserver'] if HAS_NETAPP_LIB is False: self.module.fail_json(msg="the python NetApp-Lib module is required") else: self.server = netapp_utils.setup_ontap_zapi(module=self.module, vserver=self.vserver) def get_qtree(self): """ Checks if the qtree exists. :return: True if qtree found False if qtree is not found :rtype: bool """ qtree_list_iter = netapp_utils.zapi.NaElement('qtree-list-iter') query_details = netapp_utils.zapi.NaElement.create_node_with_children( 'qtree-info', **{'vserver': self.vserver, 'volume': self.flexvol_name, 'qtree': self.name}) query = netapp_utils.zapi.NaElement('query') query.add_child_elem(query_details) qtree_list_iter.add_child_elem(query) result = self.server.invoke_successfully(qtree_list_iter, enable_tunneling=True) if (result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) >= 1): return True else: return False def create_qtree(self): qtree_create = netapp_utils.zapi.NaElement.create_node_with_children( 'qtree-create', **{'volume': self.flexvol_name, 'qtree': self.name}) try: self.server.invoke_successfully(qtree_create, enable_tunneling=True) except netapp_utils.zapi.NaApiError as e: self.module.fail_json(msg="Error provisioning qtree %s: %s" % (self.name, to_native(e)), exception=traceback.format_exc()) def delete_qtree(self): path = '/vol/%s/%s' % (self.flexvol_name, self.name) qtree_delete = netapp_utils.zapi.NaElement.create_node_with_children( 'qtree-delete', **{'qtree': path}) try: self.server.invoke_successfully(qtree_delete, enable_tunneling=True) except netapp_utils.zapi.NaApiError as e: self.module.fail_json(msg="Error deleting qtree %s: %s" % (path, to_native(e)), exception=traceback.format_exc()) def rename_qtree(self): path = '/vol/%s/%s' % (self.flexvol_name, self.name) new_path = '/vol/%s/%s' % (self.flexvol_name, self.name) qtree_rename = netapp_utils.zapi.NaElement.create_node_with_children( 'qtree-rename', **{'qtree': path, 'new-qtree-name': new_path}) try: self.server.invoke_successfully(qtree_rename, enable_tunneling=True) except netapp_utils.zapi.NaApiError as e: self.module.fail_json(msg="Error renaming qtree %s: %s" % (self.name, to_native(e)), exception=traceback.format_exc()) def apply(self): changed = False qtree_exists = False rename_qtree = False qtree_detail = self.get_qtree() if qtree_detail: qtree_exists = True if self.state == 'absent': # Qtree exists, but requested state is 'absent'. changed = True elif self.state == 'present': if self.name is not None and not self.name == \ self.name: changed = True rename_qtree = True else: if self.state == 'present': # Qtree does not exist, but requested state is 'present'. changed = True if changed: if self.module.check_mode: pass else: if self.state == 'present': if not qtree_exists: self.create_qtree() else: if rename_qtree: self.rename_qtree() elif self.state == 'absent': self.delete_qtree() self.module.exit_json(changed=changed) def main(): v = NetAppCDOTQTree() v.apply() if __name__ == '__main__': main()
hryamzik/ansible
lib/ansible/modules/storage/netapp/na_cdot_qtree.py
Python
gpl-3.0
6,978
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2015, Maciej Delmanowski <drybjed@gmail.com> # 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: virt_pool author: "Maciej Delmanowski (@drybjed)" version_added: "2.0" short_description: Manage libvirt storage pools description: - Manage I(libvirt) storage pools. options: name: required: false aliases: [ "pool" ] description: - name of the storage pool being managed. Note that pool must be previously defined with xml. state: required: false choices: [ "active", "inactive", "present", "absent", "undefined", "deleted" ] description: - specify which state you want a storage pool to be in. If 'active', pool will be started. If 'present', ensure that pool is present but do not change its state; if it's missing, you need to specify xml argument. If 'inactive', pool will be stopped. If 'undefined' or 'absent', pool will be removed from I(libvirt) configuration. If 'deleted', pool contents will be deleted and then pool undefined. command: required: false choices: [ "define", "build", "create", "start", "stop", "destroy", "delete", "undefine", "get_xml", "list_pools", "facts", "info", "status" ] description: - in addition to state management, various non-idempotent commands are available. See examples. autostart: required: false type: bool description: - Specify if a given storage pool should be started automatically on system boot. uri: required: false default: "qemu:///system" description: - I(libvirt) connection uri. xml: required: false description: - XML document used with the define command. mode: required: false choices: [ 'new', 'repair', 'resize', 'no_overwrite', 'overwrite', 'normal', 'zeroed' ] description: - Pass additional parameters to 'build' or 'delete' commands. requirements: - "python >= 2.6" - "python-libvirt" - "python-lxml" ''' EXAMPLES = ''' # Define a new storage pool - virt_pool: command: define name: vms xml: '{{ lookup("template", "pool/dir.xml.j2") }}' # Build a storage pool if it does not exist - virt_pool: command: build name: vms # Start a storage pool - virt_pool: command: create name: vms # List available pools - virt_pool: command: list_pools # Get XML data of a specified pool - virt_pool: command: get_xml name: vms # Stop a storage pool - virt_pool: command: destroy name: vms # Delete a storage pool (destroys contents) - virt_pool: command: delete name: vms # Undefine a storage pool - virt_pool: command: undefine name: vms # Gather facts about storage pools # Facts will be available as 'ansible_libvirt_pools' - virt_pool: command: facts # Gather information about pools managed by 'libvirt' remotely using uri - virt_pool: command: info uri: '{{ item }}' with_items: '{{ libvirt_uris }}' register: storage_pools # Ensure that a pool is active (needs to be defined and built first) - virt_pool: state: active name: vms # Ensure that a pool is inactive - virt_pool: state: inactive name: vms # Ensure that a given pool will be started at boot - virt_pool: autostart: yes name: vms # Disable autostart for a given pool - virt_pool: autostart: no name: vms ''' try: import libvirt except ImportError: HAS_VIRT = False else: HAS_VIRT = True try: from lxml import etree except ImportError: HAS_XML = False else: HAS_XML = True from ansible.module_utils.basic import AnsibleModule VIRT_FAILED = 1 VIRT_SUCCESS = 0 VIRT_UNAVAILABLE = 2 ALL_COMMANDS = [] ENTRY_COMMANDS = ['create', 'status', 'start', 'stop', 'build', 'delete', 'undefine', 'destroy', 'get_xml', 'define', 'refresh'] HOST_COMMANDS = ['list_pools', 'facts', 'info'] ALL_COMMANDS.extend(ENTRY_COMMANDS) ALL_COMMANDS.extend(HOST_COMMANDS) ENTRY_STATE_ACTIVE_MAP = { 0: "inactive", 1: "active" } ENTRY_STATE_AUTOSTART_MAP = { 0: "no", 1: "yes" } ENTRY_STATE_PERSISTENT_MAP = { 0: "no", 1: "yes" } ENTRY_STATE_INFO_MAP = { 0: "inactive", 1: "building", 2: "running", 3: "degraded", 4: "inaccessible" } ENTRY_BUILD_FLAGS_MAP = { "new": 0, "repair": 1, "resize": 2, "no_overwrite": 4, "overwrite": 8 } ENTRY_DELETE_FLAGS_MAP = { "normal": 0, "zeroed": 1 } ALL_MODES = [] ALL_MODES.extend(ENTRY_BUILD_FLAGS_MAP.keys()) ALL_MODES.extend(ENTRY_DELETE_FLAGS_MAP.keys()) class EntryNotFound(Exception): pass class LibvirtConnection(object): def __init__(self, uri, module): self.module = module conn = libvirt.open(uri) if not conn: raise Exception("hypervisor connection failure") self.conn = conn def find_entry(self, entryid): # entryid = -1 returns a list of everything results = [] # Get active entries for name in self.conn.listStoragePools(): entry = self.conn.storagePoolLookupByName(name) results.append(entry) # Get inactive entries for name in self.conn.listDefinedStoragePools(): entry = self.conn.storagePoolLookupByName(name) results.append(entry) if entryid == -1: return results for entry in results: if entry.name() == entryid: return entry raise EntryNotFound("storage pool %s not found" % entryid) def create(self, entryid): if not self.module.check_mode: return self.find_entry(entryid).create() else: try: state = self.find_entry(entryid).isActive() except Exception: return self.module.exit_json(changed=True) if not state: return self.module.exit_json(changed=True) def destroy(self, entryid): if not self.module.check_mode: return self.find_entry(entryid).destroy() else: if self.find_entry(entryid).isActive(): return self.module.exit_json(changed=True) def undefine(self, entryid): if not self.module.check_mode: return self.find_entry(entryid).undefine() else: if not self.find_entry(entryid): return self.module.exit_json(changed=True) def get_status2(self, entry): state = entry.isActive() return ENTRY_STATE_ACTIVE_MAP.get(state, "unknown") def get_status(self, entryid): if not self.module.check_mode: state = self.find_entry(entryid).isActive() return ENTRY_STATE_ACTIVE_MAP.get(state, "unknown") else: try: state = self.find_entry(entryid).isActive() return ENTRY_STATE_ACTIVE_MAP.get(state, "unknown") except Exception: return ENTRY_STATE_ACTIVE_MAP.get("inactive", "unknown") def get_uuid(self, entryid): return self.find_entry(entryid).UUIDString() def get_xml(self, entryid): return self.find_entry(entryid).XMLDesc(0) def get_info(self, entryid): return self.find_entry(entryid).info() def get_volume_count(self, entryid): return self.find_entry(entryid).numOfVolumes() def get_volume_names(self, entryid): return self.find_entry(entryid).listVolumes() def get_devices(self, entryid): xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0)) if xml.xpath('/pool/source/device'): result = [] for device in xml.xpath('/pool/source/device'): result.append(device.get('path')) try: return result except Exception: raise ValueError('No devices specified') def get_format(self, entryid): xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0)) try: result = xml.xpath('/pool/source/format')[0].get('type') except Exception: raise ValueError('Format not specified') return result def get_host(self, entryid): xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0)) try: result = xml.xpath('/pool/source/host')[0].get('name') except Exception: raise ValueError('Host not specified') return result def get_source_path(self, entryid): xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0)) try: result = xml.xpath('/pool/source/dir')[0].get('path') except Exception: raise ValueError('Source path not specified') return result def get_path(self, entryid): xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0)) return xml.xpath('/pool/target/path')[0].text def get_type(self, entryid): xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0)) return xml.get('type') def build(self, entryid, flags): if not self.module.check_mode: return self.find_entry(entryid).build(flags) else: try: state = self.find_entry(entryid) except Exception: return self.module.exit_json(changed=True) if not state: return self.module.exit_json(changed=True) def delete(self, entryid, flags): if not self.module.check_mode: return self.find_entry(entryid).delete(flags) else: try: state = self.find_entry(entryid) except Exception: return self.module.exit_json(changed=True) if state: return self.module.exit_json(changed=True) def get_autostart(self, entryid): state = self.find_entry(entryid).autostart() return ENTRY_STATE_AUTOSTART_MAP.get(state, "unknown") def get_autostart2(self, entryid): if not self.module.check_mode: return self.find_entry(entryid).autostart() else: try: return self.find_entry(entryid).autostart() except Exception: return self.module.exit_json(changed=True) def set_autostart(self, entryid, val): if not self.module.check_mode: return self.find_entry(entryid).setAutostart(val) else: try: state = self.find_entry(entryid).autostart() except Exception: return self.module.exit_json(changed=True) if bool(state) != val: return self.module.exit_json(changed=True) def refresh(self, entryid): return self.find_entry(entryid).refresh() def get_persistent(self, entryid): state = self.find_entry(entryid).isPersistent() return ENTRY_STATE_PERSISTENT_MAP.get(state, "unknown") def define_from_xml(self, entryid, xml): if not self.module.check_mode: return self.conn.storagePoolDefineXML(xml) else: try: self.find_entry(entryid) except Exception: return self.module.exit_json(changed=True) class VirtStoragePool(object): def __init__(self, uri, module): self.module = module self.uri = uri self.conn = LibvirtConnection(self.uri, self.module) def get_pool(self, entryid): return self.conn.find_entry(entryid) def list_pools(self, state=None): results = [] for entry in self.conn.find_entry(-1): if state: if state == self.conn.get_status2(entry): results.append(entry.name()) else: results.append(entry.name()) return results def state(self): results = [] for entry in self.list_pools(): state_blurb = self.conn.get_status(entry) results.append("%s %s" % (entry, state_blurb)) return results def autostart(self, entryid): return self.conn.set_autostart(entryid, True) def get_autostart(self, entryid): return self.conn.get_autostart2(entryid) def set_autostart(self, entryid, state): return self.conn.set_autostart(entryid, state) def create(self, entryid): return self.conn.create(entryid) def start(self, entryid): return self.conn.create(entryid) def stop(self, entryid): return self.conn.destroy(entryid) def destroy(self, entryid): return self.conn.destroy(entryid) def undefine(self, entryid): return self.conn.undefine(entryid) def status(self, entryid): return self.conn.get_status(entryid) def get_xml(self, entryid): return self.conn.get_xml(entryid) def define(self, entryid, xml): return self.conn.define_from_xml(entryid, xml) def build(self, entryid, flags): return self.conn.build(entryid, ENTRY_BUILD_FLAGS_MAP.get(flags, 0)) def delete(self, entryid, flags): return self.conn.delete(entryid, ENTRY_DELETE_FLAGS_MAP.get(flags, 0)) def refresh(self, entryid): return self.conn.refresh(entryid) def info(self): return self.facts(facts_mode='info') def facts(self, facts_mode='facts'): results = dict() for entry in self.list_pools(): results[entry] = dict() if self.conn.find_entry(entry): data = self.conn.get_info(entry) # libvirt returns maxMem, memory, and cpuTime as long()'s, which # xmlrpclib tries to convert to regular int's during serialization. # This throws exceptions, so convert them to strings here and # assume the other end of the xmlrpc connection can figure things # out or doesn't care. results[entry] = { "status": ENTRY_STATE_INFO_MAP.get(data[0], "unknown"), "size_total": str(data[1]), "size_used": str(data[2]), "size_available": str(data[3]), } results[entry]["autostart"] = self.conn.get_autostart(entry) results[entry]["persistent"] = self.conn.get_persistent(entry) results[entry]["state"] = self.conn.get_status(entry) results[entry]["path"] = self.conn.get_path(entry) results[entry]["type"] = self.conn.get_type(entry) results[entry]["uuid"] = self.conn.get_uuid(entry) if self.conn.find_entry(entry).isActive(): results[entry]["volume_count"] = self.conn.get_volume_count(entry) results[entry]["volumes"] = list() for volume in self.conn.get_volume_names(entry): results[entry]["volumes"].append(volume) else: results[entry]["volume_count"] = -1 try: results[entry]["host"] = self.conn.get_host(entry) except ValueError: pass try: results[entry]["source_path"] = self.conn.get_source_path(entry) except ValueError: pass try: results[entry]["format"] = self.conn.get_format(entry) except ValueError: pass try: devices = self.conn.get_devices(entry) results[entry]["devices"] = devices except ValueError: pass else: results[entry]["state"] = self.conn.get_status(entry) facts = dict() if facts_mode == 'facts': facts["ansible_facts"] = dict() facts["ansible_facts"]["ansible_libvirt_pools"] = results elif facts_mode == 'info': facts['pools'] = results return facts def core(module): state = module.params.get('state', None) name = module.params.get('name', None) command = module.params.get('command', None) uri = module.params.get('uri', None) xml = module.params.get('xml', None) autostart = module.params.get('autostart', None) mode = module.params.get('mode', None) v = VirtStoragePool(uri, module) res = {} if state and command == 'list_pools': res = v.list_pools(state=state) if not isinstance(res, dict): res = {command: res} return VIRT_SUCCESS, res if state: if not name: module.fail_json(msg="state change requires a specified name") res['changed'] = False if state in ['active']: if v.status(name) != 'active': res['changed'] = True res['msg'] = v.start(name) elif state in ['present']: try: v.get_pool(name) except EntryNotFound: if not xml: module.fail_json(msg="storage pool '" + name + "' not present, but xml not specified") v.define(name, xml) res = {'changed': True, 'created': name} elif state in ['inactive']: entries = v.list_pools() if name in entries: if v.status(name) != 'inactive': res['changed'] = True res['msg'] = v.destroy(name) elif state in ['undefined', 'absent']: entries = v.list_pools() if name in entries: if v.status(name) != 'inactive': v.destroy(name) res['changed'] = True res['msg'] = v.undefine(name) elif state in ['deleted']: entries = v.list_pools() if name in entries: if v.status(name) != 'inactive': v.destroy(name) v.delete(name, mode) res['changed'] = True res['msg'] = v.undefine(name) else: module.fail_json(msg="unexpected state") return VIRT_SUCCESS, res if command: if command in ENTRY_COMMANDS: if not name: module.fail_json(msg="%s requires 1 argument: name" % command) if command == 'define': if not xml: module.fail_json(msg="define requires xml argument") try: v.get_pool(name) except EntryNotFound: v.define(name, xml) res = {'changed': True, 'created': name} return VIRT_SUCCESS, res elif command == 'build': res = v.build(name, mode) if not isinstance(res, dict): res = {'changed': True, command: res} return VIRT_SUCCESS, res elif command == 'delete': res = v.delete(name, mode) if not isinstance(res, dict): res = {'changed': True, command: res} return VIRT_SUCCESS, res res = getattr(v, command)(name) if not isinstance(res, dict): res = {command: res} return VIRT_SUCCESS, res elif hasattr(v, command): res = getattr(v, command)() if not isinstance(res, dict): res = {command: res} return VIRT_SUCCESS, res else: module.fail_json(msg="Command %s not recognized" % command) if autostart is not None: if not name: module.fail_json(msg="state change requires a specified name") res['changed'] = False if autostart: if not v.get_autostart(name): res['changed'] = True res['msg'] = v.set_autostart(name, True) else: if v.get_autostart(name): res['changed'] = True res['msg'] = v.set_autostart(name, False) return VIRT_SUCCESS, res module.fail_json(msg="expected state or command parameter to be specified") def main(): module = AnsibleModule( argument_spec=dict( name=dict(aliases=['pool']), state=dict(choices=['active', 'inactive', 'present', 'absent', 'undefined', 'deleted']), command=dict(choices=ALL_COMMANDS), uri=dict(default='qemu:///system'), xml=dict(), autostart=dict(type='bool'), mode=dict(choices=ALL_MODES), ), supports_check_mode=True ) if not HAS_VIRT: module.fail_json( msg='The `libvirt` module is not importable. Check the requirements.' ) if not HAS_XML: module.fail_json( msg='The `lxml` module is not importable. Check the requirements.' ) rc = VIRT_SUCCESS try: rc, result = core(module) except Exception as e: module.fail_json(msg=str(e)) if rc != 0: # something went wrong emit the msg module.fail_json(rc=rc, msg=result) else: module.exit_json(**result) if __name__ == '__main__': main()
alxgu/ansible
lib/ansible/modules/cloud/misc/virt_pool.py
Python
gpl-3.0
21,816
# <hr>Calculates the tangents and bitangents for the imported meshes. # # Does nothing if a mesh does not have normals. You might want this post # processing step to be executed if you plan to use tangent space calculations # such as normal mapping applied to the meshes. There's a config setting, # <tt>#AI_CONFIG_PP_CT_MAX_SMOOTHING_ANGLE<tt>, which allows you to specify # a maximum smoothing angle for the algorithm. However, usually you'll # want to leave it at the default value. # aiProcess_CalcTangentSpace = 0x1 ## <hr>Identifies and joins identical vertex data sets within all # imported meshes. # # After this step is run, each mesh contains unique vertices, # so a vertex may be used by multiple faces. You usually want # to use this post processing step. If your application deals with # indexed geometry, this step is compulsory or you'll just waste rendering # time. <b>If this flag is not specified<b>, no vertices are referenced by # more than one face and <b>no index buffer is required<b> for rendering. # aiProcess_JoinIdenticalVertices = 0x2 ## <hr>Converts all the imported data to a left-handed coordinate space. # # By default the data is returned in a right-handed coordinate space (which # OpenGL prefers). In this space, +X points to the right, # +Z points towards the viewer, and +Y points upwards. In the DirectX # coordinate space +X points to the right, +Y points upwards, and +Z points # away from the viewer. # # You'll probably want to consider this flag if you use Direct3D for # rendering. The #aiProcess_ConvertToLeftHanded flag supersedes this # setting and bundles all conversions typically required for D3D-based # applications. # aiProcess_MakeLeftHanded = 0x4 ## <hr>Triangulates all faces of all meshes. # # By default the imported mesh data might contain faces with more than 3 # indices. For rendering you'll usually want all faces to be triangles. # This post processing step splits up faces with more than 3 indices into # triangles. Line and point primitives are #not# modified! If you want # 'triangles only' with no other kinds of primitives, try the following # solution: # <ul> # <li>Specify both #aiProcess_Triangulate and #aiProcess_SortByPType <li> # <li>Ignore all point and line meshes when you process assimp's output<li> # <ul> # aiProcess_Triangulate = 0x8 ## <hr>Removes some parts of the data structure (animations, materials, # light sources, cameras, textures, vertex components). # # The components to be removed are specified in a separate # configuration option, <tt>#AI_CONFIG_PP_RVC_FLAGS<tt>. This is quite useful # if you don't need all parts of the output structure. Vertex colors # are rarely used today for example... Calling this step to remove unneeded # data from the pipeline as early as possible results in increased # performance and a more optimized output data structure. # This step is also useful if you want to force Assimp to recompute # normals or tangents. The corresponding steps don't recompute them if # they're already there (loaded from the source asset). By using this # step you can make sure they are NOT there. # # This flag is a poor one, mainly because its purpose is usually # misunderstood. Consider the following case: a 3D model has been exported # from a CAD app, and it has per-face vertex colors. Vertex positions can't be # shared, thus the #aiProcess_JoinIdenticalVertices step fails to # optimize the data because of these nasty little vertex colors. # Most apps don't even process them, so it's all for nothing. By using # this step, unneeded components are excluded as early as possible # thus opening more room for internal optimizations. # aiProcess_RemoveComponent = 0x10 ## <hr>Generates normals for all faces of all meshes. # # This is ignored if normals are already there at the time this flag # is evaluated. Model importers try to load them from the source file, so # they're usually already there. Face normals are shared between all points # of a single face, so a single point can have multiple normals, which # forces the library to duplicate vertices in some cases. # #aiProcess_JoinIdenticalVertices is #senseless# then. # # This flag may not be specified together with #aiProcess_GenSmoothNormals. # aiProcess_GenNormals = 0x20 ## <hr>Generates smooth normals for all vertices in the mesh. # # This is ignored if normals are already there at the time this flag # is evaluated. Model importers try to load them from the source file, so # they're usually already there. # # This flag may not be specified together with # #aiProcess_GenNormals. There's a configuration option, # <tt>#AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE<tt> which allows you to specify # an angle maximum for the normal smoothing algorithm. Normals exceeding # this limit are not smoothed, resulting in a 'hard' seam between two faces. # Using a decent angle here (e.g. 80 degrees) results in very good visual # appearance. # aiProcess_GenSmoothNormals = 0x40 ## <hr>Splits large meshes into smaller sub-meshes. # # This is quite useful for real-time rendering, where the number of triangles # which can be maximally processed in a single draw-call is limited # by the video driverhardware. The maximum vertex buffer is usually limited # too. Both requirements can be met with this step: you may specify both a # triangle and vertex limit for a single mesh. # # The split limits can (and should!) be set through the # <tt>#AI_CONFIG_PP_SLM_VERTEX_LIMIT<tt> and <tt>#AI_CONFIG_PP_SLM_TRIANGLE_LIMIT<tt> # settings. The default values are <tt>#AI_SLM_DEFAULT_MAX_VERTICES<tt> and # <tt>#AI_SLM_DEFAULT_MAX_TRIANGLES<tt>. # # Note that splitting is generally a time-consuming task, but only if there's # something to split. The use of this step is recommended for most users. # aiProcess_SplitLargeMeshes = 0x80 ## <hr>Removes the node graph and pre-transforms all vertices with # the local transformation matrices of their nodes. # # The output scene still contains nodes, however there is only a # root node with children, each one referencing only one mesh, # and each mesh referencing one material. For rendering, you can # simply render all meshes in order - you don't need to pay # attention to local transformations and the node hierarchy. # Animations are removed during this step. # This step is intended for applications without a scenegraph. # The step CAN cause some problems: if e.g. a mesh of the asset # contains normals and another, using the same material index, does not, # they will be brought together, but the first meshes's part of # the normal list is zeroed. However, these artifacts are rare. # @note The <tt>#AI_CONFIG_PP_PTV_NORMALIZE<tt> configuration property # can be set to normalize the scene's spatial dimension to the -1...1 # range. # aiProcess_PreTransformVertices = 0x100 ## <hr>Limits the number of bones simultaneously affecting a single vertex # to a maximum value. # # If any vertex is affected by more than the maximum number of bones, the least # important vertex weights are removed and the remaining vertex weights are # renormalized so that the weights still sum up to 1. # The default bone weight limit is 4 (defined as <tt>#AI_LMW_MAX_WEIGHTS<tt> in # config.h), but you can use the <tt>#AI_CONFIG_PP_LBW_MAX_WEIGHTS<tt> setting to # supply your own limit to the post processing step. # # If you intend to perform the skinning in hardware, this post processing # step might be of interest to you. # aiProcess_LimitBoneWeights = 0x200 ## <hr>Validates the imported scene data structure. # This makes sure that all indices are valid, all animations and # bones are linked correctly, all material references are correct .. etc. # # It is recommended that you capture Assimp's log output if you use this flag, # so you can easily find out what's wrong if a file fails the # validation. The validator is quite strict and will find #all# # inconsistencies in the data structure... It is recommended that plugin # developers use it to debug their loaders. There are two types of # validation failures: # <ul> # <li>Error: There's something wrong with the imported data. Further # postprocessing is not possible and the data is not usable at all. # The import fails. #Importer::GetErrorString() or #aiGetErrorString() # carry the error message around.<li> # <li>Warning: There are some minor issues (e.g. 1000000 animation # keyframes with the same time), but further postprocessing and use # of the data structure is still safe. Warning details are written # to the log file, <tt>#AI_SCENE_FLAGS_VALIDATION_WARNING<tt> is set # in #aiScene::mFlags<li> # <ul> # # This post-processing step is not time-consuming. Its use is not # compulsory, but recommended. # aiProcess_ValidateDataStructure = 0x400 ## <hr>Reorders triangles for better vertex cache locality. # # The step tries to improve the ACMR (average post-transform vertex cache # miss ratio) for all meshes. The implementation runs in O(n) and is # roughly based on the 'tipsify' algorithm (see <a href=" # http:www.cs.princeton.edugfxpubsSander_2007_%3ETRtipsy.pdf">this # paper<a>). # # If you intend to render huge models in hardware, this step might # be of interest to you. The <tt>#AI_CONFIG_PP_ICL_PTCACHE_SIZE<tt>config # setting can be used to fine-tune the cache optimization. # aiProcess_ImproveCacheLocality = 0x800 ## <hr>Searches for redundantunreferenced materials and removes them. # # This is especially useful in combination with the # #aiProcess_PretransformVertices and #aiProcess_OptimizeMeshes flags. # Both join small meshes with equal characteristics, but they can't do # their work if two meshes have different materials. Because several # material settings are lost during Assimp's import filters, # (and because many exporters don't check for redundant materials), huge # models often have materials which are are defined several times with # exactly the same settings. # # Several material settings not contributing to the final appearance of # a surface are ignored in all comparisons (e.g. the material name). # So, if you're passing additional information through the # content pipeline (probably using #magic# material names), don't # specify this flag. Alternatively take a look at the # <tt>#AI_CONFIG_PP_RRM_EXCLUDE_LIST<tt> setting. # aiProcess_RemoveRedundantMaterials = 0x1000 ## <hr>This step tries to determine which meshes have normal vectors # that are facing inwards and inverts them. # # The algorithm is simple but effective: # the bounding box of all vertices + their normals is compared against # the volume of the bounding box of all vertices without their normals. # This works well for most objects, problems might occur with planar # surfaces. However, the step tries to filter such cases. # The step inverts all in-facing normals. Generally it is recommended # to enable this step, although the result is not always correct. # aiProcess_FixInfacingNormals = 0x2000 ## <hr>This step splits meshes with more than one primitive type in # homogeneous sub-meshes. # # The step is executed after the triangulation step. After the step # returns, just one bit is set in aiMesh::mPrimitiveTypes. This is # especially useful for real-time rendering where point and line # primitives are often ignored or rendered separately. # You can use the <tt>#AI_CONFIG_PP_SBP_REMOVE<tt> option to specify which # primitive types you need. This can be used to easily exclude # lines and points, which are rarely used, from the import. # aiProcess_SortByPType = 0x8000 ## <hr>This step searches all meshes for degenerate primitives and # converts them to proper lines or points. # # A face is 'degenerate' if one or more of its points are identical. # To have the degenerate stuff not only detected and collapsed but # removed, try one of the following procedures: # <br><b>1.<b> (if you support lines and points for rendering but don't # want the degenerates)<br> # <ul> # <li>Specify the #aiProcess_FindDegenerates flag. # <li> # <li>Set the <tt>AI_CONFIG_PP_FD_REMOVE<tt> option to 1. This will # cause the step to remove degenerate triangles from the import # as soon as they're detected. They won't pass any further # pipeline steps. # <li> # <ul> # <br><b>2.<b>(if you don't support lines and points at all)<br> # <ul> # <li>Specify the #aiProcess_FindDegenerates flag. # <li> # <li>Specify the #aiProcess_SortByPType flag. This moves line and # point primitives to separate meshes. # <li> # <li>Set the <tt>AI_CONFIG_PP_SBP_REMOVE<tt> option to # @code aiPrimitiveType_POINTS | aiPrimitiveType_LINES # @endcode to cause SortByPType to reject point # and line meshes from the scene. # <li> # <ul> # @note Degenerate polygons are not necessarily evil and that's why # they're not removed by default. There are several file formats which # don't support lines or points, and some exporters bypass the # format specification and write them as degenerate triangles instead. # aiProcess_FindDegenerates = 0x10000 ## <hr>This step searches all meshes for invalid data, such as zeroed # normal vectors or invalid UV coords and removesfixes them. This is # intended to get rid of some common exporter errors. # # This is especially useful for normals. If they are invalid, and # the step recognizes this, they will be removed and can later # be recomputed, i.e. by the #aiProcess_GenSmoothNormals flag.<br> # The step will also remove meshes that are infinitely small and reduce # animation tracks consisting of hundreds if redundant keys to a single # key. The <tt>AI_CONFIG_PP_FID_ANIM_ACCURACY<tt> config property decides # the accuracy of the check for duplicate animation tracks. # aiProcess_FindInvalidData = 0x20000 ## <hr>This step converts non-UV mappings (such as spherical or # cylindrical mapping) to proper texture coordinate channels. # # Most applications will support UV mapping only, so you will # probably want to specify this step in every case. Note that Assimp is not # always able to match the original mapping implementation of the # 3D app which produced a model perfectly. It's always better to let the # modelling app compute the UV channels - 3ds max, Maya, Blender, # LightWave, and Modo do this for example. # # @note If this step is not requested, you'll need to process the # <tt>#AI_MATKEY_MAPPING<tt> material property in order to display all assets # properly. # aiProcess_GenUVCoords = 0x40000 ## <hr>This step applies per-texture UV transformations and bakes # them into stand-alone vtexture coordinate channels. # # UV transformations are specified per-texture - see the # <tt>#AI_MATKEY_UVTRANSFORM<tt> material key for more information. # This step processes all textures with # transformed input UV coordinates and generates a new (pre-transformed) UV channel # which replaces the old channel. Most applications won't support UV # transformations, so you will probably want to specify this step. # # @note UV transformations are usually implemented in real-time apps by # transforming texture coordinates at vertex shader stage with a 3x3 # (homogenous) transformation matrix. # aiProcess_TransformUVCoords = 0x80000 ## <hr>This step searches for duplicate meshes and replaces them # with references to the first mesh. # # This step takes a while, so don't use it if speed is a concern. # Its main purpose is to workaround the fact that many export # file formats don't support instanced meshes, so exporters need to # duplicate meshes. This step removes the duplicates again. Please # note that Assimp does not currently support per-node material # assignment to meshes, which means that identical meshes with # different materials are currently #not# joined, although this is # planned for future versions. # aiProcess_FindInstances = 0x100000 ## <hr>A postprocessing step to reduce the number of meshes. # # This will, in fact, reduce the number of draw calls. # # This is a very effective optimization and is recommended to be used # together with #aiProcess_OptimizeGraph, if possible. The flag is fully # compatible with both #aiProcess_SplitLargeMeshes and #aiProcess_SortByPType. # aiProcess_OptimizeMeshes = 0x200000 ## <hr>A postprocessing step to optimize the scene hierarchy. # # Nodes without animations, bones, lights or cameras assigned are # collapsed and joined. # # Node names can be lost during this step. If you use special 'tag nodes' # to pass additional information through your content pipeline, use the # <tt>#AI_CONFIG_PP_OG_EXCLUDE_LIST<tt> setting to specify a list of node # names you want to be kept. Nodes matching one of the names in this list won't # be touched or modified. # # Use this flag with caution. Most simple files will be collapsed to a # single node, so complex hierarchies are usually completely lost. This is not # useful for editor environments, but probably a very effective # optimization if you just want to get the model data, convert it to your # own format, and render it as fast as possible. # # This flag is designed to be used with #aiProcess_OptimizeMeshes for best # results. # # @note 'Crappy' scenes with thousands of extremely small meshes packed # in deeply nested nodes exist for almost all file formats. # #aiProcess_OptimizeMeshes in combination with #aiProcess_OptimizeGraph # usually fixes them all and makes them renderable. # aiProcess_OptimizeGraph = 0x400000 ## <hr>This step flips all UV coordinates along the y-axis and adjusts # material settings and bitangents accordingly. # # <b>Output UV coordinate system:<b> # @code # 0y|0y ---------- 1x|0y # | | # | | # | | # 0x|1y ---------- 1x|1y # @endcode # # You'll probably want to consider this flag if you use Direct3D for # rendering. The #aiProcess_ConvertToLeftHanded flag supersedes this # setting and bundles all conversions typically required for D3D-based # applications. # aiProcess_FlipUVs = 0x800000 ## <hr>This step adjusts the output face winding order to be CW. # # The default face winding order is counter clockwise (CCW). # # <b>Output face order:<b> # @code # x2 # # x0 # x1 # @endcode # aiProcess_FlipWindingOrder = 0x1000000 ## <hr>This step splits meshes with many bones into sub-meshes so that each # su-bmesh has fewer or as many bones as a given limit. # aiProcess_SplitByBoneCount = 0x2000000 ## <hr>This step removes bones losslessly or according to some threshold. # # In some cases (i.e. formats that require it) exporters are forced to # assign dummy bone weights to otherwise static meshes assigned to # animated meshes. Full, weight-based skinning is expensive while # animating nodes is extremely cheap, so this step is offered to clean up # the data in that regard. # # Use <tt>#AI_CONFIG_PP_DB_THRESHOLD<tt> to control this. # Use <tt>#AI_CONFIG_PP_DB_ALL_OR_NONE<tt> if you want bones removed if and # only if all bones within the scene qualify for removal. # aiProcess_Debone = 0x4000000 aiProcess_GenEntityMeshes = 0x100000 aiProcess_OptimizeAnimations = 0x200000 aiProcess_FixTexturePaths = 0x200000 ## @def aiProcess_ConvertToLeftHanded # @brief Shortcut flag for Direct3D-based applications. # # Supersedes the #aiProcess_MakeLeftHanded and #aiProcess_FlipUVs and # #aiProcess_FlipWindingOrder flags. # The output data matches Direct3D's conventions: left-handed geometry, upper-left # origin for UV coordinates and finally clockwise face order, suitable for CCW culling. # # @deprecated # aiProcess_ConvertToLeftHanded = ( \ aiProcess_MakeLeftHanded | \ aiProcess_FlipUVs | \ aiProcess_FlipWindingOrder | \ 0 ) ## @def aiProcessPreset_TargetRealtimeUse_Fast # @brief Default postprocess configuration optimizing the data for real-time rendering. # # Applications would want to use this preset to load models on end-user PCs, # maybe for direct use in game. # # If you're using DirectX, don't forget to combine this value with # the #aiProcess_ConvertToLeftHanded step. If you don't support UV transformations # in your application apply the #aiProcess_TransformUVCoords step, too. # @note Please take the time to read the docs for the steps enabled by this preset. # Some of them offer further configurable properties, while some of them might not be of # use for you so it might be better to not specify them. # aiProcessPreset_TargetRealtime_Fast = ( \ aiProcess_CalcTangentSpace | \ aiProcess_GenNormals | \ aiProcess_JoinIdenticalVertices | \ aiProcess_Triangulate | \ aiProcess_GenUVCoords | \ aiProcess_SortByPType | \ 0 ) ## @def aiProcessPreset_TargetRealtime_Quality # @brief Default postprocess configuration optimizing the data for real-time rendering. # # Unlike #aiProcessPreset_TargetRealtime_Fast, this configuration # performs some extra optimizations to improve rendering speed and # to minimize memory usage. It could be a good choice for a level editor # environment where import speed is not so important. # # If you're using DirectX, don't forget to combine this value with # the #aiProcess_ConvertToLeftHanded step. If you don't support UV transformations # in your application apply the #aiProcess_TransformUVCoords step, too. # @note Please take the time to read the docs for the steps enabled by this preset. # Some of them offer further configurable properties, while some of them might not be # of use for you so it might be better to not specify them. # aiProcessPreset_TargetRealtime_Quality = ( \ aiProcess_CalcTangentSpace | \ aiProcess_GenSmoothNormals | \ aiProcess_JoinIdenticalVertices | \ aiProcess_ImproveCacheLocality | \ aiProcess_LimitBoneWeights | \ aiProcess_RemoveRedundantMaterials | \ aiProcess_SplitLargeMeshes | \ aiProcess_Triangulate | \ aiProcess_GenUVCoords | \ aiProcess_SortByPType | \ aiProcess_FindDegenerates | \ aiProcess_FindInvalidData | \ 0 ) ## @def aiProcessPreset_TargetRealtime_MaxQuality # @brief Default postprocess configuration optimizing the data for real-time rendering. # # This preset enables almost every optimization step to achieve perfectly # optimized data. It's your choice for level editor environments where import speed # is not important. # # If you're using DirectX, don't forget to combine this value with # the #aiProcess_ConvertToLeftHanded step. If you don't support UV transformations # in your application, apply the #aiProcess_TransformUVCoords step, too. # @note Please take the time to read the docs for the steps enabled by this preset. # Some of them offer further configurable properties, while some of them might not be # of use for you so it might be better to not specify them. # aiProcessPreset_TargetRealtime_MaxQuality = ( \ aiProcessPreset_TargetRealtime_Quality | \ aiProcess_FindInstances | \ aiProcess_ValidateDataStructure | \ aiProcess_OptimizeMeshes | \ 0 )
ivansoban/ILEngine
thirdparty/assimp/port/PyAssimp/pyassimp/postprocess.py
Python
mit
23,509
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from common_report_header import common_report_header from openerp.report import report_sxw class journal_print(report_sxw.rml_parse, common_report_header): def __init__(self, cr, uid, name, context=None): if context is None: context = {} super(journal_print, self).__init__(cr, uid, name, context=context) self.period_ids = [] self.last_move_id = False self.journal_ids = [] self.sort_selection = 'am.name' self.localcontext.update({ 'time': time, 'lines': self.lines, 'sum_debit': self._sum_debit, 'sum_credit': self._sum_credit, 'get_start_period': self.get_start_period, 'get_end_period': self.get_end_period, 'get_account': self._get_account, 'get_filter': self._get_filter, 'get_start_date': self._get_start_date, 'get_end_date': self._get_end_date, 'get_fiscalyear': self._get_fiscalyear, 'display_currency':self._display_currency, 'get_sortby': self._get_sortby, 'get_target_move': self._get_target_move, 'check_last_move_id': self.check_last_move_id, 'set_last_move_id': self.set_last_move_id, 'tax_codes': self.tax_codes, 'sum_vat': self._sum_vat, }) def set_context(self, objects, data, ids, report_type=None): obj_move = self.pool.get('account.move.line') new_ids = ids self.query_get_clause = '' self.target_move = data['form'].get('target_move', 'all') if (data['model'] == 'ir.ui.menu'): self.period_ids = tuple(data['form']['periods']) self.journal_ids = tuple(data['form']['journal_ids']) new_ids = data['form'].get('active_ids', []) self.query_get_clause = 'AND ' self.query_get_clause += obj_move._query_get(self.cr, self.uid, obj='l', context=data['form'].get('used_context', {})) self.sort_selection = data['form'].get('sort_selection', 'date') objects = self.pool.get('account.journal.period').browse(self.cr, self.uid, new_ids) elif new_ids: #in case of direct access from account.journal.period object, we need to set the journal_ids and periods_ids self.cr.execute('SELECT period_id, journal_id FROM account_journal_period WHERE id IN %s', (tuple(new_ids),)) res = self.cr.fetchall() self.period_ids, self.journal_ids = zip(*res) return super(journal_print, self).set_context(objects, data, ids, report_type=report_type) def set_last_move_id(self, move_id): self.last_move_id = move_id def check_last_move_id(self, move_id): ''' return True if we need to draw a gray line above this line, used to separate moves ''' if self.last_move_id: return not(self.last_move_id == move_id) return False def tax_codes(self, period_id, journal_id): ids_journal_period = self.pool.get('account.journal.period').search(self.cr, self.uid, [('journal_id', '=', journal_id), ('period_id', '=', period_id)]) self.cr.execute( 'select distinct tax_code_id from account_move_line ' \ 'where period_id=%s and journal_id=%s and tax_code_id is not null and state<>\'draft\'', (period_id, journal_id) ) ids = map(lambda x: x[0], self.cr.fetchall()) tax_code_ids = [] if ids: self.cr.execute('select id from account_tax_code where id in %s order by code', (tuple(ids),)) tax_code_ids = map(lambda x: x[0], self.cr.fetchall()) tax_codes = self.pool.get('account.tax.code').browse(self.cr, self.uid, tax_code_ids) return tax_codes def _sum_vat(self, period_id, journal_id, tax_code_id): self.cr.execute('select sum(tax_amount) from account_move_line where ' \ 'period_id=%s and journal_id=%s and tax_code_id=%s and state<>\'draft\'', (period_id, journal_id, tax_code_id)) return self.cr.fetchone()[0] or 0.0 def _sum_debit(self, period_id=False, journal_id=False): if journal_id and isinstance(journal_id, int): journal_id = [journal_id] if period_id and isinstance(period_id, int): period_id = [period_id] if not journal_id: journal_id = self.journal_ids if not period_id: period_id = self.period_ids if not (period_id and journal_id): return 0.0 move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted'] self.cr.execute('SELECT SUM(debit) FROM account_move_line l, account_move am ' 'WHERE l.move_id=am.id AND am.state IN %s AND l.period_id IN %s AND l.journal_id IN %s ' + self.query_get_clause + ' ', (tuple(move_state), tuple(period_id), tuple(journal_id))) return self.cr.fetchone()[0] or 0.0 def _sum_credit(self, period_id=False, journal_id=False): if journal_id and isinstance(journal_id, int): journal_id = [journal_id] if period_id and isinstance(period_id, int): period_id = [period_id] if not journal_id: journal_id = self.journal_ids if not period_id: period_id = self.period_ids if not (period_id and journal_id): return 0.0 move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted'] self.cr.execute('SELECT SUM(l.credit) FROM account_move_line l, account_move am ' 'WHERE l.move_id=am.id AND am.state IN %s AND l.period_id IN %s AND l.journal_id IN %s '+ self.query_get_clause+'', (tuple(move_state), tuple(period_id), tuple(journal_id))) return self.cr.fetchone()[0] or 0.0 def lines(self, period_id, journal_id=False): if not journal_id: journal_id = self.journal_ids else: journal_id = [journal_id] obj_mline = self.pool.get('account.move.line') self.cr.execute('update account_journal_period set state=%s where journal_id IN %s and period_id=%s and state=%s', ('printed', self.journal_ids, period_id, 'draft')) move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted'] self.cr.execute('SELECT l.id FROM account_move_line l, account_move am WHERE l.move_id=am.id AND am.state IN %s AND l.period_id=%s AND l.journal_id IN %s ' + self.query_get_clause + ' ORDER BY '+ self.sort_selection + ', l.move_id',(tuple(move_state), period_id, tuple(journal_id) )) ids = map(lambda x: x[0], self.cr.fetchall()) return obj_mline.browse(self.cr, self.uid, ids) def _set_get_account_currency_code(self, account_id): self.cr.execute("SELECT c.symbol AS code "\ "FROM res_currency c,account_account AS ac "\ "WHERE ac.id = %s AND ac.currency_id = c.id" % (account_id)) result = self.cr.fetchone() if result: self.account_currency = result[0] else: self.account_currency = False def _get_fiscalyear(self, data): if data['model'] == 'account.journal.period': return self.pool.get('account.journal.period').browse(self.cr, self.uid, data['id']).fiscalyear_id.name return super(journal_print, self)._get_fiscalyear(data) def _get_account(self, data): if data['model'] == 'account.journal.period': return self.pool.get('account.journal.period').browse(self.cr, self.uid, data['id']).company_id.name return super(journal_print, self)._get_account(data) def _display_currency(self, data): if data['model'] == 'account.journal.period': return True return data['form']['amount_currency'] def _get_sortby(self, data): # TODO: deprecated, to remove in trunk if self.sort_selection == 'date': return self._translate('Date') elif self.sort_selection == 'ref': return self._translate('Reference Number') return self._translate('Date') report_sxw.report_sxw('report.account.journal.period.print', 'account.journal.period', 'addons/account/report/account_journal.rml', parser=journal_print, header='external') report_sxw.report_sxw('report.account.journal.period.print.sale.purchase', 'account.journal.period', 'addons/account/report/account_journal_sale_purchase.rml', parser=journal_print, header='external') # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
inovtec-solutions/OpenERP
openerp/addons/account/report/account_journal.py
Python
agpl-3.0
9,777
# -*- coding: utf-8 -*- """ flask.testsuite.templating ~~~~~~~~~~~~~~~~~~~~~~~~~~ Template functionality :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import flask import unittest from flask.testsuite import FlaskTestCase class TemplatingTestCase(FlaskTestCase): def test_context_processing(self): app = flask.Flask(__name__) @app.context_processor def context_processor(): return {'injected_value': 42} @app.route('/') def index(): return flask.render_template('context_template.html', value=23) rv = app.test_client().get('/') self.assert_equal(rv.data, b'<p>23|42') def test_original_win(self): app = flask.Flask(__name__) @app.route('/') def index(): return flask.render_template_string('{{ config }}', config=42) rv = app.test_client().get('/') self.assert_equal(rv.data, b'42') def test_request_less_rendering(self): app = flask.Flask(__name__) app.config['WORLD_NAME'] = 'Special World' @app.context_processor def context_processor(): return dict(foo=42) with app.app_context(): rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} ' '{{ foo }}') self.assert_equal(rv, 'Hello Special World 42') def test_standard_context(self): app = flask.Flask(__name__) app.secret_key = 'development key' @app.route('/') def index(): flask.g.foo = 23 flask.session['test'] = 'aha' return flask.render_template_string(''' {{ request.args.foo }} {{ g.foo }} {{ config.DEBUG }} {{ session.test }} ''') rv = app.test_client().get('/?foo=42') self.assert_equal(rv.data.split(), [b'42', b'23', b'False', b'aha']) def test_escaping(self): text = '<p>Hello World!' app = flask.Flask(__name__) @app.route('/') def index(): return flask.render_template('escaping_template.html', text=text, html=flask.Markup(text)) lines = app.test_client().get('/').data.splitlines() self.assert_equal(lines, [ b'&lt;p&gt;Hello World!', b'<p>Hello World!', b'<p>Hello World!', b'<p>Hello World!', b'&lt;p&gt;Hello World!', b'<p>Hello World!' ]) def test_no_escaping(self): app = flask.Flask(__name__) with app.test_request_context(): self.assert_equal(flask.render_template_string('{{ foo }}', foo='<test>'), '<test>') self.assert_equal(flask.render_template('mail.txt', foo='<test>'), '<test> Mail') def test_macros(self): app = flask.Flask(__name__) with app.test_request_context(): macro = flask.get_template_attribute('_macro.html', 'hello') self.assert_equal(macro('World'), 'Hello World!') def test_template_filter(self): app = flask.Flask(__name__) @app.template_filter() def my_reverse(s): return s[::-1] self.assert_in('my_reverse', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse) self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') def test_add_template_filter(self): app = flask.Flask(__name__) def my_reverse(s): return s[::-1] app.add_template_filter(my_reverse) self.assert_in('my_reverse', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse) self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') def test_template_filter_with_name(self): app = flask.Flask(__name__) @app.template_filter('strrev') def my_reverse(s): return s[::-1] self.assert_in('strrev', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['strrev'], my_reverse) self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') def test_add_template_filter_with_name(self): app = flask.Flask(__name__) def my_reverse(s): return s[::-1] app.add_template_filter(my_reverse, 'strrev') self.assert_in('strrev', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['strrev'], my_reverse) self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') def test_template_filter_with_template(self): app = flask.Flask(__name__) @app.template_filter() def super_reverse(s): return s[::-1] @app.route('/') def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') self.assert_equal(rv.data, b'dcba') def test_add_template_filter_with_template(self): app = flask.Flask(__name__) def super_reverse(s): return s[::-1] app.add_template_filter(super_reverse) @app.route('/') def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') self.assert_equal(rv.data, b'dcba') def test_template_filter_with_name_and_template(self): app = flask.Flask(__name__) @app.template_filter('super_reverse') def my_reverse(s): return s[::-1] @app.route('/') def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') self.assert_equal(rv.data, b'dcba') def test_add_template_filter_with_name_and_template(self): app = flask.Flask(__name__) def my_reverse(s): return s[::-1] app.add_template_filter(my_reverse, 'super_reverse') @app.route('/') def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') self.assert_equal(rv.data, b'dcba') def test_template_test(self): app = flask.Flask(__name__) @app.template_test() def boolean(value): return isinstance(value, bool) self.assert_in('boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], boolean) self.assert_true(app.jinja_env.tests['boolean'](False)) def test_add_template_test(self): app = flask.Flask(__name__) def boolean(value): return isinstance(value, bool) app.add_template_test(boolean) self.assert_in('boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], boolean) self.assert_true(app.jinja_env.tests['boolean'](False)) def test_template_test_with_name(self): app = flask.Flask(__name__) @app.template_test('boolean') def is_boolean(value): return isinstance(value, bool) self.assert_in('boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], is_boolean) self.assert_true(app.jinja_env.tests['boolean'](False)) def test_add_template_test_with_name(self): app = flask.Flask(__name__) def is_boolean(value): return isinstance(value, bool) app.add_template_test(is_boolean, 'boolean') self.assert_in('boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], is_boolean) self.assert_true(app.jinja_env.tests['boolean'](False)) def test_template_test_with_template(self): app = flask.Flask(__name__) @app.template_test() def boolean(value): return isinstance(value, bool) @app.route('/') def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') self.assert_in(b'Success!', rv.data) def test_add_template_test_with_template(self): app = flask.Flask(__name__) def boolean(value): return isinstance(value, bool) app.add_template_test(boolean) @app.route('/') def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') self.assert_in(b'Success!', rv.data) def test_template_test_with_name_and_template(self): app = flask.Flask(__name__) @app.template_test('boolean') def is_boolean(value): return isinstance(value, bool) @app.route('/') def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') self.assert_in(b'Success!', rv.data) def test_add_template_test_with_name_and_template(self): app = flask.Flask(__name__) def is_boolean(value): return isinstance(value, bool) app.add_template_test(is_boolean, 'boolean') @app.route('/') def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') self.assert_in(b'Success!', rv.data) def test_add_template_global(self): app = flask.Flask(__name__) @app.template_global() def get_stuff(): return 42 self.assert_in('get_stuff', app.jinja_env.globals.keys()) self.assert_equal(app.jinja_env.globals['get_stuff'], get_stuff) self.assert_true(app.jinja_env.globals['get_stuff'](), 42) with app.app_context(): rv = flask.render_template_string('{{ get_stuff() }}') self.assert_equal(rv, '42') def test_custom_template_loader(self): class MyFlask(flask.Flask): def create_global_jinja_loader(self): from jinja2 import DictLoader return DictLoader({'index.html': 'Hello Custom World!'}) app = MyFlask(__name__) @app.route('/') def index(): return flask.render_template('index.html') c = app.test_client() rv = c.get('/') self.assert_equal(rv.data, b'Hello Custom World!') def test_iterable_loader(self): app = flask.Flask(__name__) @app.context_processor def context_processor(): return {'whiskey': 'Jameson'} @app.route('/') def index(): return flask.render_template( ['no_template.xml', # should skip this one 'simple_template.html', # should render this 'context_template.html'], value=23) rv = app.test_client().get('/') self.assert_equal(rv.data, b'<h1>Jameson</h1>') def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TemplatingTestCase)) return suite
zwChan/VATEC
~/eb-virt/Lib/site-packages/flask/testsuite/templating.py
Python
apache-2.0
11,237
# -*- coding: utf-8 -*- """ /*************************************************************************** Name : DB Manager Description : Database manager plugin for QGIS Date : May 23, 2011 copyright : (C) 2011 by Giuseppe Sucameli email : brush.tyler@gmail.com ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ """ from builtins import str from builtins import object class HtmlContent(object): def __init__(self, data): self.data = data if not isinstance(data, HtmlContent) else data.data def toHtml(self): if isinstance(self.data, list) or isinstance(self.data, tuple): html = u'' for item in self.data: html += HtmlContent(item).toHtml() return html if hasattr(self.data, 'toHtml'): return self.data.toHtml() html = str(self.data).replace("\n", "<br>") return html def hasContents(self): if isinstance(self.data, list) or isinstance(self.data, tuple): empty = True for item in self.data: if item.hasContents(): empty = False break return not empty if hasattr(self.data, 'hasContents'): return self.data.hasContents() return len(self.data) > 0 class HtmlElem(object): def __init__(self, tag, data, attrs=None): self.tag = tag self.data = data if isinstance(data, HtmlContent) else HtmlContent(data) self.attrs = attrs if attrs is not None else dict() if 'tag' in self.attrs: self.setTag(self.attrs['tag']) del self.attrs['tag'] def setTag(self, tag): self.tag = tag def getOriginalData(self): return self.data.data def setAttr(self, name, value): self.attrs[name] = value def getAttrsHtml(self): html = u'' for k, v in self.attrs.items(): html += u' %s="%s"' % (k, v) return html def openTagHtml(self): return u"<%s%s>" % (self.tag, self.getAttrsHtml()) def closeTagHtml(self): return u"</%s>" % self.tag def toHtml(self): return u"%s%s%s" % (self.openTagHtml(), self.data.toHtml(), self.closeTagHtml()) def hasContents(self): return self.data.toHtml() != "" class HtmlParagraph(HtmlElem): def __init__(self, data, attrs=None): HtmlElem.__init__(self, 'p', data, attrs) class HtmlListItem(HtmlElem): def __init__(self, data, attrs=None): HtmlElem.__init__(self, 'li', data, attrs) class HtmlList(HtmlElem): def __init__(self, items, attrs=None): # make sure to have HtmlListItem items items = list(items) for i, item in enumerate(items): if not isinstance(item, HtmlListItem): items[i] = HtmlListItem(item) HtmlElem.__init__(self, 'ul', items, attrs) class HtmlTableCol(HtmlElem): def __init__(self, data, attrs=None): HtmlElem.__init__(self, 'td', data, attrs) def closeTagHtml(self): # FIX INVALID BEHAVIOR: an empty cell as last table's cell break margins return u"&nbsp;%s" % HtmlElem.closeTagHtml(self) class HtmlTableRow(HtmlElem): def __init__(self, cols, attrs=None): # make sure to have HtmlTableCol items cols = list(cols) for i, c in enumerate(cols): if not isinstance(c, HtmlTableCol): cols[i] = HtmlTableCol(c) HtmlElem.__init__(self, 'tr', cols, attrs) class HtmlTableHeader(HtmlTableRow): def __init__(self, cols, attrs=None): HtmlTableRow.__init__(self, cols, attrs) for c in self.getOriginalData(): c.setTag('th') class HtmlTable(HtmlElem): def __init__(self, rows, attrs=None): # make sure to have HtmlTableRow items rows = list(rows) for i, r in enumerate(rows): if not isinstance(r, HtmlTableRow): rows[i] = HtmlTableRow(r) HtmlElem.__init__(self, 'table', rows, attrs) class HtmlWarning(HtmlContent): def __init__(self, data): data = ['<img src=":/icons/warning-20px.png">&nbsp;&nbsp; ', data] HtmlContent.__init__(self, data) class HtmlSection(HtmlContent): def __init__(self, title, content=None): data = ['<div class="section"><h2>', title, '</h2>'] if content is not None: data.extend(['<div>', content, '</div>']) data.append('</div>') HtmlContent.__init__(self, data)
uclaros/QGIS
python/plugins/db_manager/db_plugins/html_elems.py
Python
gpl-2.0
5,237
# -*- test-case-name: twisted.names.test.test_tap -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Domain Name Server """ import os, traceback from twisted.python import usage from twisted.names import dns from twisted.application import internet, service from twisted.names import server from twisted.names import authority from twisted.names import secondary class Options(usage.Options): optParameters = [ ["interface", "i", "", "The interface to which to bind"], ["port", "p", "53", "The port on which to listen"], ["resolv-conf", None, None, "Override location of resolv.conf (implies --recursive)"], ["hosts-file", None, None, "Perform lookups with a hosts file"], ] optFlags = [ ["cache", "c", "Enable record caching"], ["recursive", "r", "Perform recursive lookups"], ["verbose", "v", "Log verbosely"], ] compData = usage.Completions( optActions={"interface" : usage.CompleteNetInterfaces()} ) zones = None zonefiles = None def __init__(self): usage.Options.__init__(self) self['verbose'] = 0 self.bindfiles = [] self.zonefiles = [] self.secondaries = [] def opt_pyzone(self, filename): """Specify the filename of a Python syntax zone definition""" if not os.path.exists(filename): raise usage.UsageError(filename + ": No such file") self.zonefiles.append(filename) def opt_bindzone(self, filename): """Specify the filename of a BIND9 syntax zone definition""" if not os.path.exists(filename): raise usage.UsageError(filename + ": No such file") self.bindfiles.append(filename) def opt_secondary(self, ip_domain): """Act as secondary for the specified domain, performing zone transfers from the specified IP (IP/domain) """ args = ip_domain.split('/', 1) if len(args) != 2: raise usage.UsageError("Argument must be of the form IP[:port]/domain") address = args[0].split(':') if len(address) == 1: address = (address[0], dns.PORT) else: try: port = int(address[1]) except ValueError: raise usage.UsageError( "Specify an integer port number, not %r" % (address[1],)) address = (address[0], port) self.secondaries.append((address, [args[1]])) def opt_verbose(self): """Increment verbosity level""" self['verbose'] += 1 def postOptions(self): if self['resolv-conf']: self['recursive'] = True self.svcs = [] self.zones = [] for f in self.zonefiles: try: self.zones.append(authority.PySourceAuthority(f)) except Exception: traceback.print_exc() raise usage.UsageError("Invalid syntax in " + f) for f in self.bindfiles: try: self.zones.append(authority.BindAuthority(f)) except Exception: traceback.print_exc() raise usage.UsageError("Invalid syntax in " + f) for f in self.secondaries: svc = secondary.SecondaryAuthorityService.fromServerAddressAndDomains(*f) self.svcs.append(svc) self.zones.append(self.svcs[-1].getAuthority()) try: self['port'] = int(self['port']) except ValueError: raise usage.UsageError("Invalid port: %r" % (self['port'],)) def _buildResolvers(config): """ Build DNS resolver instances in an order which leaves recursive resolving as a last resort. @type config: L{Options} instance @param config: Parsed command-line configuration @return: Two-item tuple of a list of cache resovers and a list of client resolvers """ from twisted.names import client, cache, hosts ca, cl = [], [] if config['cache']: ca.append(cache.CacheResolver(verbose=config['verbose'])) if config['hosts-file']: cl.append(hosts.Resolver(file=config['hosts-file'])) if config['recursive']: cl.append(client.createResolver(resolvconf=config['resolv-conf'])) return ca, cl def makeService(config): ca, cl = _buildResolvers(config) f = server.DNSServerFactory(config.zones, ca, cl, config['verbose']) p = dns.DNSDatagramProtocol(f) f.noisy = 0 ret = service.MultiService() for (klass, arg) in [(internet.TCPServer, f), (internet.UDPServer, p)]: s = klass(config['port'], arg, interface=config['interface']) s.setServiceParent(ret) for svc in config.svcs: svc.setServiceParent(ret) return ret
skycucumber/Messaging-Gateway
webapp/venv/lib/python2.7/site-packages/twisted/names/tap.py
Python
gpl-2.0
4,832
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( int_or_none, float_or_none, unified_strdate, ) class PornoVoisinesIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?pornovoisines\.com/videos/show/(?P<id>\d+)/(?P<display_id>[^/.]+)' _TEST = { 'url': 'http://www.pornovoisines.com/videos/show/919/recherche-appartement.html', 'md5': '6f8aca6a058592ab49fe701c8ba8317b', 'info_dict': { 'id': '919', 'display_id': 'recherche-appartement', 'ext': 'mp4', 'title': 'Recherche appartement', 'description': 'md5:fe10cb92ae2dd3ed94bb4080d11ff493', 'thumbnail': r're:^https?://.*\.jpg$', 'upload_date': '20140925', 'duration': 120, 'view_count': int, 'average_rating': float, 'categories': ['Débutante', 'Débutantes', 'Scénario', 'Sodomie'], 'age_limit': 18, 'subtitles': { 'fr': [{ 'ext': 'vtt', }] }, } } def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') display_id = mobj.group('display_id') settings_url = self._download_json( 'http://www.pornovoisines.com/api/video/%s/getsettingsurl/' % video_id, video_id, note='Getting settings URL')['video_settings_url'] settings = self._download_json(settings_url, video_id)['data'] formats = [] for kind, data in settings['variants'].items(): if kind == 'HLS': formats.extend(self._extract_m3u8_formats( data, video_id, ext='mp4', entry_protocol='m3u8_native', m3u8_id='hls')) elif kind == 'MP4': for item in data: formats.append({ 'url': item['url'], 'height': item.get('height'), 'bitrate': item.get('bitrate'), }) self._sort_formats(formats) webpage = self._download_webpage(url, video_id) title = self._og_search_title(webpage) description = self._og_search_description(webpage) # The webpage has a bug - there's no space between "thumb" and src= thumbnail = self._html_search_regex( r'<img[^>]+class=([\'"])thumb\1[^>]*src=([\'"])(?P<url>[^"]+)\2', webpage, 'thumbnail', fatal=False, group='url') upload_date = unified_strdate(self._search_regex( r'Le\s*<b>([\d/]+)', webpage, 'upload date', fatal=False)) duration = settings.get('main', {}).get('duration') view_count = int_or_none(self._search_regex( r'(\d+) vues', webpage, 'view count', fatal=False)) average_rating = self._search_regex( r'Note\s*:\s*(\d+(?:,\d+)?)', webpage, 'average rating', fatal=False) if average_rating: average_rating = float_or_none(average_rating.replace(',', '.')) categories = self._html_search_regex( r'(?s)Catégories\s*:\s*<b>(.+?)</b>', webpage, 'categories', fatal=False) if categories: categories = [category.strip() for category in categories.split(',')] subtitles = {'fr': [{ 'url': subtitle, } for subtitle in settings.get('main', {}).get('vtt_tracks', {}).values()]} return { 'id': video_id, 'display_id': display_id, 'formats': formats, 'title': title, 'description': description, 'thumbnail': thumbnail, 'upload_date': upload_date, 'duration': duration, 'view_count': view_count, 'average_rating': average_rating, 'categories': categories, 'age_limit': 18, 'subtitles': subtitles, }
epitron/youtube-dl
youtube_dl/extractor/pornovoisines.py
Python
unlicense
4,003
""" DataSource is a wrapper for the OGR Data Source object, which provides an interface for reading vector geometry data from many different file formats (including ESRI shapefiles). When instantiating a DataSource object, use the filename of a GDAL-supported data source. For example, a SHP file or a TIGER/Line file from the government. The ds_driver keyword is used internally when a ctypes pointer is passed in directly. Example: ds = DataSource('/home/foo/bar.shp') for layer in ds: for feature in layer: # Getting the geometry for the feature. g = feature.geom # Getting the 'description' field for the feature. desc = feature['description'] # We can also increment through all of the fields # attached to this feature. for field in feature: # Get the name of the field (e.g. 'description') nm = field.name # Get the type (integer) of the field, e.g. 0 => OFTInteger t = field.type # Returns the value the field; OFTIntegers return ints, # OFTReal returns floats, all else returns string. val = field.value """ # ctypes prerequisites. from ctypes import byref, c_void_p # The GDAL C library, OGR exceptions, and the Layer object. from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.driver import Driver from django.contrib.gis.gdal.error import OGRException, OGRIndexError from django.contrib.gis.gdal.layer import Layer # Getting the ctypes prototypes for the DataSource. from django.contrib.gis.gdal.prototypes import ds as capi # For more information, see the OGR C API source code: # http://www.gdal.org/ogr/ogr__api_8h.html # # The OGR_DS_* routines are relevant here. class DataSource(GDALBase): "Wraps an OGR Data Source object." #### Python 'magic' routines #### def __init__(self, ds_input, ds_driver=False, write=False): # The write flag. if write: self._write = 1 else: self._write = 0 # Registering all the drivers, this needs to be done # _before_ we try to open up a data source. if not capi.get_driver_count(): capi.register_all() if isinstance(ds_input, basestring): # The data source driver is a void pointer. ds_driver = Driver.ptr_type() try: # OGROpen will auto-detect the data source type. ds = capi.open_ds(ds_input, self._write, byref(ds_driver)) except OGRException: # Making the error message more clear rather than something # like "Invalid pointer returned from OGROpen". raise OGRException('Could not open the datasource at "%s"' % ds_input) elif isinstance(ds_input, self.ptr_type) and isinstance(ds_driver, Driver.ptr_type): ds = ds_input else: raise OGRException('Invalid data source input type: %s' % type(ds_input)) if bool(ds): self.ptr = ds self.driver = Driver(ds_driver) else: # Raise an exception if the returned pointer is NULL raise OGRException('Invalid data source file "%s"' % ds_input) def __del__(self): "Destroys this DataStructure object." if self._ptr: capi.destroy_ds(self._ptr) def __iter__(self): "Allows for iteration over the layers in a data source." for i in xrange(self.layer_count): yield self[i] def __getitem__(self, index): "Allows use of the index [] operator to get a layer at the index." if isinstance(index, basestring): l = capi.get_layer_by_name(self.ptr, index) if not l: raise OGRIndexError('invalid OGR Layer name given: "%s"' % index) elif isinstance(index, int): if index < 0 or index >= self.layer_count: raise OGRIndexError('index out of range') l = capi.get_layer(self._ptr, index) else: raise TypeError('Invalid index type: %s' % type(index)) return Layer(l, self) def __len__(self): "Returns the number of layers within the data source." return self.layer_count def __str__(self): "Returns OGR GetName and Driver for the Data Source." return '%s (%s)' % (self.name, str(self.driver)) @property def layer_count(self): "Returns the number of layers in the data source." return capi.get_layer_count(self._ptr) @property def name(self): "Returns the name of the data source." return capi.get_ds_name(self._ptr)
ychen820/microblog
y/google-cloud-sdk/platform/google_appengine/lib/django-1.3/django/contrib/gis/gdal/datasource.py
Python
bsd-3-clause
4,734
# 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. # ============================================================================== """Tests for initializers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import importlib import numpy as np from tensorflow.python.client import session from tensorflow.python.framework import constant_op from tensorflow.python.ops import nn_ops from tensorflow.python.ops.distributions import exponential as exponential_lib from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging def try_import(name): # pylint: disable=invalid-name module = None try: module = importlib.import_module(name) except ImportError as e: tf_logging.warning("Could not import %s: %s" % (name, str(e))) return module stats = try_import("scipy.stats") class ExponentialTest(test.TestCase): def testExponentialLogPDF(self): with session.Session(): batch_size = 6 lam = constant_op.constant([2.0] * batch_size) lam_v = 2.0 x = np.array([2.5, 2.5, 4.0, 0.1, 1.0, 2.0], dtype=np.float32) exponential = exponential_lib.Exponential(rate=lam) log_pdf = exponential.log_prob(x) self.assertEqual(log_pdf.get_shape(), (6,)) pdf = exponential.prob(x) self.assertEqual(pdf.get_shape(), (6,)) if not stats: return expected_log_pdf = stats.expon.logpdf(x, scale=1 / lam_v) self.assertAllClose(log_pdf.eval(), expected_log_pdf) self.assertAllClose(pdf.eval(), np.exp(expected_log_pdf)) def testExponentialCDF(self): with session.Session(): batch_size = 6 lam = constant_op.constant([2.0] * batch_size) lam_v = 2.0 x = np.array([2.5, 2.5, 4.0, 0.1, 1.0, 2.0], dtype=np.float32) exponential = exponential_lib.Exponential(rate=lam) cdf = exponential.cdf(x) self.assertEqual(cdf.get_shape(), (6,)) if not stats: return expected_cdf = stats.expon.cdf(x, scale=1 / lam_v) self.assertAllClose(cdf.eval(), expected_cdf) def testExponentialMean(self): with session.Session(): lam_v = np.array([1.0, 4.0, 2.5]) exponential = exponential_lib.Exponential(rate=lam_v) self.assertEqual(exponential.mean().get_shape(), (3,)) if not stats: return expected_mean = stats.expon.mean(scale=1 / lam_v) self.assertAllClose(exponential.mean().eval(), expected_mean) def testExponentialVariance(self): with session.Session(): lam_v = np.array([1.0, 4.0, 2.5]) exponential = exponential_lib.Exponential(rate=lam_v) self.assertEqual(exponential.variance().get_shape(), (3,)) if not stats: return expected_variance = stats.expon.var(scale=1 / lam_v) self.assertAllClose(exponential.variance().eval(), expected_variance) def testExponentialEntropy(self): with session.Session(): lam_v = np.array([1.0, 4.0, 2.5]) exponential = exponential_lib.Exponential(rate=lam_v) self.assertEqual(exponential.entropy().get_shape(), (3,)) if not stats: return expected_entropy = stats.expon.entropy(scale=1 / lam_v) self.assertAllClose(exponential.entropy().eval(), expected_entropy) def testExponentialSample(self): with self.test_session(): lam = constant_op.constant([3.0, 4.0]) lam_v = [3.0, 4.0] n = constant_op.constant(100000) exponential = exponential_lib.Exponential(rate=lam) samples = exponential.sample(n, seed=137) sample_values = samples.eval() self.assertEqual(sample_values.shape, (100000, 2)) self.assertFalse(np.any(sample_values < 0.0)) if not stats: return for i in range(2): self.assertLess( stats.kstest( sample_values[:, i], stats.expon(scale=1.0 / lam_v[i]).cdf)[0], 0.01) def testExponentialSampleMultiDimensional(self): with self.test_session(): batch_size = 2 lam_v = [3.0, 22.0] lam = constant_op.constant([lam_v] * batch_size) exponential = exponential_lib.Exponential(rate=lam) n = 100000 samples = exponential.sample(n, seed=138) self.assertEqual(samples.get_shape(), (n, batch_size, 2)) sample_values = samples.eval() self.assertFalse(np.any(sample_values < 0.0)) if not stats: return for i in range(2): self.assertLess( stats.kstest( sample_values[:, 0, i], stats.expon(scale=1.0 / lam_v[i]).cdf)[0], 0.01) self.assertLess( stats.kstest( sample_values[:, 1, i], stats.expon(scale=1.0 / lam_v[i]).cdf)[0], 0.01) def testExponentialWithSoftplusRate(self): with self.test_session(): lam = [-2.2, -3.4] exponential = exponential_lib.ExponentialWithSoftplusRate(rate=lam) self.assertAllClose(nn_ops.softplus(lam).eval(), exponential.rate.eval()) if __name__ == "__main__": test.main()
npuichigo/ttsflow
third_party/tensorflow/tensorflow/python/kernel_tests/distributions/exponential_test.py
Python
apache-2.0
5,672
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Generate java source files from protobuf files. This is a helper file for the genproto_java action in protoc_java.gypi. It performs the following steps: 1. Deletes all old sources (ensures deleted classes are not part of new jars). 2. Creates source directory. 3. Generates Java files using protoc (output into either --java-out-dir or --srcjar). 4. Creates a new stamp file. """ import os import optparse import shutil import subprocess import sys sys.path.append(os.path.join(os.path.dirname(__file__), "android", "gyp")) from util import build_utils def main(argv): parser = optparse.OptionParser() build_utils.AddDepfileOption(parser) parser.add_option("--protoc", help="Path to protoc binary.") parser.add_option("--proto-path", help="Path to proto directory.") parser.add_option("--java-out-dir", help="Path to output directory for java files.") parser.add_option("--srcjar", help="Path to output srcjar.") parser.add_option("--stamp", help="File to touch on success.") options, args = parser.parse_args(argv) build_utils.CheckOptions(options, parser, ['protoc', 'proto_path']) if not options.java_out_dir and not options.srcjar: print 'One of --java-out-dir or --srcjar must be specified.' return 1 with build_utils.TempDir() as temp_dir: # Specify arguments to the generator. generator_args = ['optional_field_style=reftypes', 'store_unknown_fields=true'] out_arg = '--javanano_out=' + ','.join(generator_args) + ':' + temp_dir # Generate Java files using protoc. build_utils.CheckOutput( [options.protoc, '--proto_path', options.proto_path, out_arg] + args) if options.java_out_dir: build_utils.DeleteDirectory(options.java_out_dir) shutil.copytree(temp_dir, options.java_out_dir) else: build_utils.ZipDir(options.srcjar, temp_dir) if options.depfile: build_utils.WriteDepfile( options.depfile, args + [options.protoc] + build_utils.GetPythonDependencies()) if options.stamp: build_utils.Touch(options.stamp) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/build/protoc_java.py
Python
mit
2,330
# -*- coding: utf-8 -*- """ LucasArts Font parser. Author: Cyril Zorin Creation date: 1 January 2007 """ from lib.hachoir_parser import Parser from lib.hachoir_core.field import (FieldSet, UInt8, UInt16, UInt32, GenericVector) from lib.hachoir_core.endian import LITTLE_ENDIAN class CharData(FieldSet): def __init__(self, chars, *args): FieldSet.__init__(self, *args) self.chars = chars def createFields(self): for char in self.chars: yield CharBitmap(char, self, "char_bitmap[]") class CharBitmap(FieldSet): def __init__(self, char, *args): FieldSet.__init__(self, *args) self.char = char def createFields(self): width = self.char["width_pixels"].value for line in xrange(self.char["height_pixels"].value): yield GenericVector(self, "line[]", width, UInt8, "pixel") class CharInfo(FieldSet): static_size = 16 * 8 def createFields(self): yield UInt32(self, "data_offset") yield UInt8(self, "logical_width") yield UInt8(self, "unknown[]") yield UInt8(self, "unknown[]") yield UInt8(self, "unknown[]") yield UInt32(self, "width_pixels") yield UInt32(self, "height_pixels") class LafFile(Parser): PARSER_TAGS = { "id": "lucasarts_font", "category": "game", "file_ext" : ("laf",), "min_size" : 32*8, "description" : "LucasArts Font" } endian = LITTLE_ENDIAN def validate(self): if self["num_chars"].value != 256: return "Invalid number of characters (%u)" % self["num_chars"].value if self["first_char_code"].value != 0: return "Invalid of code of first character code (%u)" % self["first_char_code"].value if self["last_char_code"].value != 255: return "Invalid of code of last character code (%u)" % self["last_char_code"].value if self["char_codes/char[0]"].value != 0: return "Invalid character code #0 (%u)" % self["char_codes/char[0]"].value if self["chars/char[0]/data_offset"].value != 0: return "Invalid character #0 offset" return True def createFields(self): yield UInt32(self, "num_chars") yield UInt32(self, "raw_font_data_size") yield UInt32(self, "max_char_width") yield UInt32(self, "min_char_width") yield UInt32(self, "unknown[]", 4) yield UInt32(self, "unknown[]", 4) yield UInt32(self, "first_char_code") yield UInt32(self, "last_char_code") yield GenericVector(self, "char_codes", self["num_chars"].value, UInt16, "char") yield GenericVector(self, "chars", self["num_chars"].value, CharInfo, "char") # character data. we make an effort to provide # something more meaningful than "RawBytes: # character bitmap data" yield CharData(self["chars"], self, "char_data") # read to the end if self.current_size < self._size: yield self.seekBit(self._size, "unknown[]")
Branlala/docker-sickbeardfr
sickbeard/lib/hachoir_parser/game/laf.py
Python
mit
2,900
#!/usr/bin/env python # # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Gets and writes the configurations of the attached devices. This configuration is used by later build steps to determine which devices to install to and what needs to be installed to those devices. """ import optparse import sys from util import build_utils from util import build_device def main(argv): parser = optparse.OptionParser() parser.add_option('--stamp', action='store') parser.add_option('--output', action='store') options, _ = parser.parse_args(argv) devices = build_device.GetAttachedDevices() device_configurations = [] for d in devices: configuration, is_online, has_root = ( build_device.GetConfigurationForDevice(d)) if not is_online: build_utils.PrintBigWarning( '%s is not online. Skipping managed install for this device. ' 'Try rebooting the device to fix this warning.' % d) continue if not has_root: build_utils.PrintBigWarning( '"adb root" failed on device: %s\n' 'Skipping managed install for this device.' % configuration['description']) continue device_configurations.append(configuration) if len(device_configurations) == 0: build_utils.PrintBigWarning( 'No valid devices attached. Skipping managed install steps.') elif len(devices) > 1: # Note that this checks len(devices) and not len(device_configurations). # This way, any time there are multiple devices attached it is # explicitly stated which device we will install things to even if all but # one device were rejected for other reasons (e.g. two devices attached, # one w/o root). build_utils.PrintBigWarning( 'Multiple devices attached. ' 'Installing to the preferred device: ' '%(id)s (%(description)s)' % (device_configurations[0])) build_device.WriteConfigurations(device_configurations, options.output) if __name__ == '__main__': sys.exit(main(sys.argv))
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/build/android/gyp/get_device_configuration.py
Python
mit
2,134
"""Microsoft Internet Explorer cookie loading on Windows. Copyright 2002-2003 Johnny Lee <typo_pl@hotmail.com> (MSIE Perl code) Copyright 2002-2006 John J Lee <jjl@pobox.com> (The Python port) This code is free software; you can redistribute it and/or modify it under the terms of the BSD or ZPL 2.1 licenses (see the file COPYING.txt included with the distribution). """ # XXX names and comments are not great here import os, re, time, struct, logging if os.name == "nt": import _winreg from _clientcookie import FileCookieJar, CookieJar, Cookie, \ MISSING_FILENAME_TEXT, LoadError debug = logging.getLogger("mechanize").debug def regload(path, leaf): key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, path, 0, _winreg.KEY_ALL_ACCESS) try: value = _winreg.QueryValueEx(key, leaf)[0] except WindowsError: value = None return value WIN32_EPOCH = 0x019db1ded53e8000L # 1970 Jan 01 00:00:00 in Win32 FILETIME def epoch_time_offset_from_win32_filetime(filetime): """Convert from win32 filetime to seconds-since-epoch value. MSIE stores create and expire times as Win32 FILETIME, which is 64 bits of 100 nanosecond intervals since Jan 01 1601. mechanize expects time in 32-bit value expressed in seconds since the epoch (Jan 01 1970). """ if filetime < WIN32_EPOCH: raise ValueError("filetime (%d) is before epoch (%d)" % (filetime, WIN32_EPOCH)) return divmod((filetime - WIN32_EPOCH), 10000000L)[0] def binary_to_char(c): return "%02X" % ord(c) def binary_to_str(d): return "".join(map(binary_to_char, list(d))) class MSIEBase: magic_re = re.compile(r"Client UrlCache MMF Ver \d\.\d.*") padding = "\x0d\xf0\xad\x0b" msie_domain_re = re.compile(r"^([^/]+)(/.*)$") cookie_re = re.compile("Cookie\:.+\@([\x21-\xFF]+).*?" "(.+\@[\x21-\xFF]+\.txt)") # path under HKEY_CURRENT_USER from which to get location of index.dat reg_path = r"software\microsoft\windows" \ r"\currentversion\explorer\shell folders" reg_key = "Cookies" def __init__(self): self._delayload_domains = {} def _delayload_domain(self, domain): # if necessary, lazily load cookies for this domain delayload_info = self._delayload_domains.get(domain) if delayload_info is not None: cookie_file, ignore_discard, ignore_expires = delayload_info try: self.load_cookie_data(cookie_file, ignore_discard, ignore_expires) except (LoadError, IOError): debug("error reading cookie file, skipping: %s", cookie_file) else: del self._delayload_domains[domain] def _load_cookies_from_file(self, filename): debug("Loading MSIE cookies file: %s", filename) cookies = [] cookies_fh = open(filename) try: while 1: key = cookies_fh.readline() if key == "": break rl = cookies_fh.readline def getlong(rl=rl): return long(rl().rstrip()) def getstr(rl=rl): return rl().rstrip() key = key.rstrip() value = getstr() domain_path = getstr() flags = getlong() # 0x2000 bit is for secure I think lo_expire = getlong() hi_expire = getlong() lo_create = getlong() hi_create = getlong() sep = getstr() if "" in (key, value, domain_path, flags, hi_expire, lo_expire, hi_create, lo_create, sep) or (sep != "*"): break m = self.msie_domain_re.search(domain_path) if m: domain = m.group(1) path = m.group(2) cookies.append({"KEY": key, "VALUE": value, "DOMAIN": domain, "PATH": path, "FLAGS": flags, "HIXP": hi_expire, "LOXP": lo_expire, "HICREATE": hi_create, "LOCREATE": lo_create}) finally: cookies_fh.close() return cookies def load_cookie_data(self, filename, ignore_discard=False, ignore_expires=False): """Load cookies from file containing actual cookie data. Old cookies are kept unless overwritten by newly loaded ones. You should not call this method if the delayload attribute is set. I think each of these files contain all cookies for one user, domain, and path. filename: file containing cookies -- usually found in a file like C:\WINNT\Profiles\joe\Cookies\joe@blah[1].txt """ now = int(time.time()) cookie_data = self._load_cookies_from_file(filename) for cookie in cookie_data: flags = cookie["FLAGS"] secure = ((flags & 0x2000) != 0) filetime = (cookie["HIXP"] << 32) + cookie["LOXP"] expires = epoch_time_offset_from_win32_filetime(filetime) if expires < now: discard = True else: discard = False domain = cookie["DOMAIN"] initial_dot = domain.startswith(".") if initial_dot: domain_specified = True else: # MSIE 5 does not record whether the domain cookie-attribute # was specified. # Assuming it wasn't is conservative, because with strict # domain matching this will match less frequently; with regular # Netscape tail-matching, this will match at exactly the same # times that domain_specified = True would. It also means we # don't have to prepend a dot to achieve consistency with our # own & Mozilla's domain-munging scheme. domain_specified = False # assume path_specified is false # XXX is there other stuff in here? -- e.g. comment, commentURL? c = Cookie(0, cookie["KEY"], cookie["VALUE"], None, False, domain, domain_specified, initial_dot, cookie["PATH"], False, secure, expires, discard, None, None, {"flags": flags}) if not ignore_discard and c.discard: continue if not ignore_expires and c.is_expired(now): continue CookieJar.set_cookie(self, c) def load_from_registry(self, ignore_discard=False, ignore_expires=False, username=None): """ username: only required on win9x """ cookies_dir = regload(self.reg_path, self.reg_key) filename = os.path.normpath(os.path.join(cookies_dir, "INDEX.DAT")) self.load(filename, ignore_discard, ignore_expires, username) def _really_load(self, index, filename, ignore_discard, ignore_expires, username): now = int(time.time()) if username is None: username = os.environ['USERNAME'].lower() cookie_dir = os.path.dirname(filename) data = index.read(256) if len(data) != 256: raise LoadError("%s file is too short" % filename) # Cookies' index.dat file starts with 32 bytes of signature # followed by an offset to the first record, stored as a little- # endian DWORD. sig, size, data = data[:32], data[32:36], data[36:] size = struct.unpack("<L", size)[0] # check that sig is valid if not self.magic_re.match(sig) or size != 0x4000: raise LoadError("%s ['%s' %s] does not seem to contain cookies" % (str(filename), sig, size)) # skip to start of first record index.seek(size, 0) sector = 128 # size of sector in bytes while 1: data = "" # Cookies are usually in two contiguous sectors, so read in two # sectors and adjust if not a Cookie. to_read = 2 * sector d = index.read(to_read) if len(d) != to_read: break data = data + d # Each record starts with a 4-byte signature and a count # (little-endian DWORD) of sectors for the record. sig, size, data = data[:4], data[4:8], data[8:] size = struct.unpack("<L", size)[0] to_read = (size - 2) * sector ## from urllib import quote ## print "data", quote(data) ## print "sig", quote(sig) ## print "size in sectors", size ## print "size in bytes", size*sector ## print "size in units of 16 bytes", (size*sector) / 16 ## print "size to read in bytes", to_read ## print if sig != "URL ": assert sig in ("HASH", "LEAK", \ self.padding, "\x00\x00\x00\x00"), \ "unrecognized MSIE index.dat record: %s" % \ binary_to_str(sig) if sig == "\x00\x00\x00\x00": # assume we've got all the cookies, and stop break if sig == self.padding: continue # skip the rest of this record assert to_read >= 0 if size != 2: assert to_read != 0 index.seek(to_read, 1) continue # read in rest of record if necessary if size > 2: more_data = index.read(to_read) if len(more_data) != to_read: break data = data + more_data cookie_re = ("Cookie\:%s\@([\x21-\xFF]+).*?" % username + "(%s\@[\x21-\xFF]+\.txt)" % username) m = re.search(cookie_re, data, re.I) if m: cookie_file = os.path.join(cookie_dir, m.group(2)) if not self.delayload: try: self.load_cookie_data(cookie_file, ignore_discard, ignore_expires) except (LoadError, IOError): debug("error reading cookie file, skipping: %s", cookie_file) else: domain = m.group(1) i = domain.find("/") if i != -1: domain = domain[:i] self._delayload_domains[domain] = ( cookie_file, ignore_discard, ignore_expires) class MSIECookieJar(MSIEBase, FileCookieJar): """FileCookieJar that reads from the Windows MSIE cookies database. MSIECookieJar can read the cookie files of Microsoft Internet Explorer (MSIE) for Windows version 5 on Windows NT and version 6 on Windows XP and Windows 98. Other configurations may also work, but are untested. Saving cookies in MSIE format is NOT supported. If you save cookies, they'll be in the usual Set-Cookie3 format, which you can read back in using an instance of the plain old CookieJar class. Don't save using the same filename that you loaded cookies from, because you may succeed in clobbering your MSIE cookies index file! You should be able to have LWP share Internet Explorer's cookies like this (note you need to supply a username to load_from_registry if you're on Windows 9x or Windows ME): cj = MSIECookieJar(delayload=1) # find cookies index file in registry and load cookies from it cj.load_from_registry() opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cj)) response = opener.open("http://example.com/") Iterating over a delayloaded MSIECookieJar instance will not cause any cookies to be read from disk. To force reading of all cookies from disk, call read_all_cookies. Note that the following methods iterate over self: clear_temporary_cookies, clear_expired_cookies, __len__, __repr__, __str__ and as_string. Additional methods: load_from_registry(ignore_discard=False, ignore_expires=False, username=None) load_cookie_data(filename, ignore_discard=False, ignore_expires=False) read_all_cookies() """ def __init__(self, filename=None, delayload=False, policy=None): MSIEBase.__init__(self) FileCookieJar.__init__(self, filename, delayload, policy) def set_cookie(self, cookie): if self.delayload: self._delayload_domain(cookie.domain) CookieJar.set_cookie(self, cookie) def _cookies_for_request(self, request): """Return a list of cookies to be returned to server.""" domains = self._cookies.copy() domains.update(self._delayload_domains) domains = domains.keys() cookies = [] for domain in domains: cookies.extend(self._cookies_for_domain(domain, request)) return cookies def _cookies_for_domain(self, domain, request): if not self._policy.domain_return_ok(domain, request): return [] debug("Checking %s for cookies to return", domain) if self.delayload: self._delayload_domain(domain) return CookieJar._cookies_for_domain(self, domain, request) def read_all_cookies(self): """Eagerly read in all cookies.""" if self.delayload: for domain in self._delayload_domains.keys(): self._delayload_domain(domain) def load(self, filename, ignore_discard=False, ignore_expires=False, username=None): """Load cookies from an MSIE 'index.dat' cookies index file. filename: full path to cookie index file username: only required on win9x """ if filename is None: if self.filename is not None: filename = self.filename else: raise ValueError(MISSING_FILENAME_TEXT) index = open(filename, "rb") try: self._really_load(index, filename, ignore_discard, ignore_expires, username) finally: index.close()
openhatch/oh-mainline
vendor/packages/mechanize/mechanize/_msiecookiejar.py
Python
agpl-3.0
14,694
#!/usr/bin/env python import subprocess import re import os import errno import collections import sys class Platform(object): pass sdk_re = re.compile(r'.*-sdk ([a-zA-Z0-9.]*)') def sdkinfo(sdkname): ret = {} for line in subprocess.Popen(['xcodebuild', '-sdk', sdkname, '-version'], stdout=subprocess.PIPE).stdout: kv = line.strip().split(': ', 1) if len(kv) == 2: k,v = kv ret[k] = v return ret sim_sdk_info = sdkinfo('iphonesimulator') device_sdk_info = sdkinfo('iphoneos') def latest_sdks(): latest_sim = None latest_device = None for line in subprocess.Popen(['xcodebuild', '-showsdks'], stdout=subprocess.PIPE).stdout: match = sdk_re.match(line) if match: if 'Simulator' in line: latest_sim = match.group(1) elif 'iOS' in line: latest_device = match.group(1) return latest_sim, latest_device sim_sdk, device_sdk = latest_sdks() class simulator_platform(Platform): sdk='iphonesimulator' arch = 'i386' name = 'simulator' triple = 'i386-apple-darwin10' sdkroot = sim_sdk_info['Path'] prefix = "#if !defined(__arm__) && defined(__i386__)\n\n" suffix = "\n\n#endif" class device_platform(Platform): sdk='iphoneos' name = 'ios' arch = 'armv7' triple = 'arm-apple-darwin10' sdkroot = device_sdk_info['Path'] prefix = "#ifdef __arm__\n\n" suffix = "\n\n#endif" def move_file(src_dir, dst_dir, filename, file_suffix=None, prefix='', suffix=''): if not os.path.exists(dst_dir): os.makedirs(dst_dir) out_filename = filename if file_suffix: split_name = os.path.splitext(filename) out_filename = "%s_%s%s" % (split_name[0], file_suffix, split_name[1]) with open(os.path.join(src_dir, filename)) as in_file: with open(os.path.join(dst_dir, out_filename), 'w') as out_file: if prefix: out_file.write(prefix) out_file.write(in_file.read()) if suffix: out_file.write(suffix) headers_seen = collections.defaultdict(set) def move_source_tree(src_dir, dest_dir, dest_include_dir, arch=None, prefix=None, suffix=None): for root, dirs, files in os.walk(src_dir, followlinks=True): relroot = os.path.relpath(root,src_dir) def move_dir(arch, prefix='', suffix='', files=[]): for file in files: file_suffix = None if file.endswith('.h'): if dest_include_dir: file_suffix = arch if arch: headers_seen[file].add(arch) move_file(root, dest_include_dir, file, arch, prefix=prefix, suffix=suffix) elif dest_dir: outroot = os.path.join(dest_dir, relroot) move_file(root, outroot, file, prefix=prefix, suffix=suffix) if relroot == '.': move_dir(arch=arch, files=files, prefix=prefix, suffix=suffix) elif relroot == 'arm': move_dir(arch='arm', prefix="#ifdef __arm__\n\n", suffix="\n\n#endif", files=files) elif relroot == 'x86': move_dir(arch='i386', prefix="#if !defined(__arm__) && defined(__i386__)\n\n", suffix="\n\n#endif", files=files) def build_target(platform): def xcrun_cmd(cmd): return subprocess.check_output(['xcrun', '-sdk', platform.sdkroot, '-find', cmd]).strip() build_dir = 'build_' + platform.name if not os.path.exists(build_dir): os.makedirs(build_dir) env = dict(CC=xcrun_cmd('clang'), LD=xcrun_cmd('ld'), CFLAGS='-arch %s -isysroot %s -miphoneos-version-min=4.0' % (platform.arch, platform.sdkroot)) working_dir=os.getcwd() try: os.chdir(build_dir) subprocess.check_call(['../configure', '-host', platform.triple], env=env) move_source_tree('.', None, '../ios/include', arch=platform.arch, prefix=platform.prefix, suffix=platform.suffix) move_source_tree('./include', None, '../ios/include', arch=platform.arch, prefix=platform.prefix, suffix=platform.suffix) finally: os.chdir(working_dir) for header_name, archs in headers_seen.iteritems(): basename, suffix = os.path.splitext(header_name) def main(): move_source_tree('src', 'ios/src', 'ios/include') move_source_tree('include', None, 'ios/include') build_target(simulator_platform) build_target(device_platform) for header_name, archs in headers_seen.iteritems(): basename, suffix = os.path.splitext(header_name) with open(os.path.join('ios/include', header_name), 'w') as header: for arch in archs: header.write('#include <%s_%s%s>\n' % (basename, arch, suffix)) if __name__ == '__main__': main()
teeple/pns_server
work/install/Python-2.7.4/Modules/_ctypes/libffi/generate-ios-source-and-headers.py
Python
gpl-2.0
5,303
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com> # # Author: Sylvain Afchain <sylvain.afchain@enovance.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License.
shakamunyi/neutron-vrrp
neutron/tests/unit/services/metering/drivers/__init__.py
Python
apache-2.0
665
from todoman import version # type: ignore __version__ = version.version __documentation__ = "https://todoman.rtfd.org/en/latest/"
pimutils/todoman
todoman/__init__.py
Python
isc
133
""" Interface definition. """ from zope import interface class IMailer(interface.Interface): """ An object that sends e-mail. """ def send(sender, recipient, content): """ Sends the content to the recipient as the sender. """ class ITemplate(interface.Interface): """ An e-mail template. """ def evaluate(context): """ Evaluates a template given a context. Returns a pair of headers and parts that can be used to build a MIME message. """
lvh/txeasymail
txeasymail/interface.py
Python
isc
541
# # (C)opyright 2015 Signal Processing Devices Sweden AB # # This script showcases in Python # - How to connect to ADQ devices in Python # - Upload of waveforms to the SDR14 # - Using a playlist on the SDR14 # - How to setup an acquisition of data # - How to read data by GetData API in Python # - How to plot data in Python # # Note: The example is intended to use the SDR14 device connected in loopback mode (i.e. connect DAC output to ADC input) import numpy as np import ctypes as ct import matplotlib.pyplot as plt def set_playlist( adq_cu, adq_num, dac_id, tcstr ): tc = {} if (tcstr == 'basic1'): ns = 2 # Number of items tc["ns"] = ns # 1 2 3 4 5 6 7 8 9 tc["index"] = (ct.c_uint32 * ns)( 1, 2) tc["segment"] = (ct.c_uint32 * ns)( 1, 2) tc["next"] = (ct.c_uint32 * ns)( 2, 1) tc["wrap"] = (ct.c_uint32 * ns)( 4, 3) tc["ulsign"] = (ct.c_uint32 * ns)( 0, 0) tc["trigtype"] = (ct.c_uint32 * ns)( 1, 1) tc["triglength"] = (ct.c_uint32 * ns)( 50, 50) tc["trigpolarity"]=(ct.c_uint32 * ns)( 0, 0) tc["trigsample"]= (ct.c_uint32 * ns)( 1, 1) tc["writemask"]= (ct.c_uint32 * ns)( 15, 15) # Transfer playlist to device ADQAPI.ADQ_AWGWritePlaylist( adq_cu, adq_num, dac_id, tc['ns'], ct.byref(tc['index']), ct.byref(tc['writemask']), ct.byref(tc['segment']), ct.byref(tc['wrap']), ct.byref(tc['next']), ct.byref(tc['trigtype']), ct.byref(tc['triglength']), ct.byref(tc['trigpolarity']), ct.byref(tc['trigsample']), ct.byref(tc['ulsign']) ) # Select the Playlist mode ADQAPI.ADQ_AWGPlaylistMode( adq_cu, adq_num, dac_id, 1) return tc def lessen_to_14bits( databuf ): for x in range(0,4096): databuf[x] = databuf[x] & 0x3FFF; return databuf def define_and_upload_segments( adq_cu, adq_num, dac_id ): # Setup target buffers for upload of data number_of_data_segments = 3 data_length = 4096 data_buffers=(ct.POINTER(ct.c_int16*data_length)*number_of_data_segments)() databuf = np.zeros((number_of_data_segments,data_length)) for bufp in data_buffers: bufp.contents = (ct.c_int16*data_length)() # Re-arrange data in numpy arrays databuf = np.frombuffer(data_buffers[0].contents,dtype=np.int16) #Create sawtooth for x in range(0, 1024): databuf[x] = x databuf[x+1024] = 1024 - x databuf[x+2048] = -x databuf[x+2048+1024] = -1024 + x databuf = lessen_to_14bits(databuf) databuf = np.frombuffer(data_buffers[1].contents,dtype=np.int16) #Create positive pulse for x in range(0, 128): databuf[x] = 1024+x databuf[x+128] = 1300+x databuf[x+256] = 1300+128-x for x in range(384, 4096): databuf[x] = 0 databuf = lessen_to_14bits(databuf) #Create negative pulse (one level) databuf = np.frombuffer(data_buffers[2].contents,dtype=np.int16) for x in range(0, 256): databuf[x] = -512 for x in range(256, 4096): databuf[x] = 0 databuf = lessen_to_14bits(databuf) length_np = (ct.c_uint32 * number_of_data_segments)(data_length, data_length, data_length) segId_np = (ct.c_uint32 * number_of_data_segments)(1, 2, 3) NofLaps_np = (ct.c_uint32 * number_of_data_segments)(3, 3, 3) for idx,bufp in enumerate(data_buffers): ADQAPI.ADQ_AWGSegmentMalloc( adq_cu, adq_num, dac_id, idx+1, length_np[idx], 0) ADQAPI.ADQ_AWGWriteSegments( adq_cu, adq_num, dac_id, number_of_data_segments, ct.byref(segId_np), ct.byref(NofLaps_np), ct.byref(length_np), data_buffers ) # Note: In playlist mode, all used segments must be in the enabled range, otherwise plaqyback will stop ADQAPI.ADQ_AWGEnableSegments( adq_cu, adq_num, dac_id, number_of_data_segments ) return # For Python under Linux (uncomment in Linux) #ADQAPI = ct.cdll.LoadLibrary("libadq.so") # For Python under Windows ADQAPI = ct.cdll.LoadLibrary("ADQAPI.dll") ADQAPI.ADQAPI_GetRevision() # Manually set return type from some ADQAPI functions ADQAPI.CreateADQControlUnit.restype = ct.c_void_p ADQAPI.ADQ_GetRevision.restype = ct.c_void_p ADQAPI.ADQ_GetPtrStream.restype = ct.POINTER(ct.c_int16) ADQAPI.ADQControlUnit_FindDevices.argtypes = [ct.c_void_p] # Create ADQControlUnit adq_cu = ct.c_void_p(ADQAPI.CreateADQControlUnit()) ADQAPI.ADQControlUnit_EnableErrorTrace(adq_cu, 3, '.') adq_num = 1 dac_id = 1 bypass_analog = 1 # Convenience function def adq_status(status): if (status==0): return 'FAILURE' else: return 'OK' # Find ADQ devices ADQAPI.ADQControlUnit_FindDevices(adq_cu) n_of_ADQ = ADQAPI.ADQControlUnit_NofADQ(adq_cu) print('Number of ADQ found: {}'.format(n_of_ADQ)) if n_of_ADQ > 0: # Get revision info from ADQ rev = ADQAPI.ADQ_GetRevision(adq_cu, adq_num) revision = ct.cast(rev,ct.POINTER(ct.c_int)) print('\nConnected to ADQ #1') # Print revision information print('FPGA Revision: {}'.format(revision[0])) if (revision[1]): print('Local copy') else : print('SVN Managed') if (revision[2]): print('Mixed Revision') else : print('SVN Updated') print('') # Choose whether to bypass_analog ADQAPI.ADQ_WriteRegister(adq_cu, adq_num, 10240, 0, 2*bypass_analog); # Upload data to SDR14 define_and_upload_segments(adq_cu, adq_num, dac_id) set_playlist(adq_cu, adq_num, dac_id, 'basic1') ADQAPI.ADQ_AWGAutoRearm(adq_cu, adq_num, dac_id, 1) ADQAPI.ADQ_AWGContinuous(adq_cu, adq_num, dac_id, 0) ADQAPI.ADQ_AWGSetTriggerEnable(adq_cu, adq_num, 31) ADQAPI.ADQ_AWGArm(adq_cu, adq_num, dac_id) #ADQAPI.ADQ_AWGTrig(adq_cu, adq_num, dac_id) # Set clock source ADQ_CLOCK_INT_INTREF = 0 ADQAPI.ADQ_SetClockSource(adq_cu, adq_num, ADQ_CLOCK_INT_INTREF); # Set trig mode SW_TRIG = 1 EXT_TRIG_1 = 2 EXT_TRIG_2 = 7 EXT_TRIG_3 = 8 LVL_TRIG = 3 INT_TRIG = 4 LVL_FALLING = 0 LVL_RISING = 1 trigger = SW_TRIG success = ADQAPI.ADQ_SetTriggerMode(adq_cu, adq_num, trigger) if (success == 0): print('ADQ_SetTriggerMode failed.') number_of_records = 1 samples_per_record = 65536 # Start acquisition ADQAPI.ADQ_MultiRecordSetup(adq_cu, adq_num, number_of_records, samples_per_record) ADQAPI.ADQ_DisarmTrigger(adq_cu, adq_num) ADQAPI.ADQ_ArmTrigger(adq_cu, adq_num) while(ADQAPI.ADQ_GetAcquiredAll(adq_cu,adq_num) == 0): if (trigger == SW_TRIG): ADQAPI.ADQ_SWTrig(adq_cu, adq_num) print('Waiting for trigger') # Setup target buffers for data max_number_of_channels = 2 target_buffers=(ct.POINTER(ct.c_int16*samples_per_record*number_of_records)*max_number_of_channels)() for bufp in target_buffers: bufp.contents = (ct.c_int16*samples_per_record*number_of_records)() # Get data from ADQ ADQ_TRANSFER_MODE_NORMAL = 0 ADQ_CHANNELS_MASK = 0x3 status = ADQAPI.ADQ_GetData(adq_cu, adq_num, target_buffers, samples_per_record*number_of_records, 2, 0, number_of_records, ADQ_CHANNELS_MASK, 0, samples_per_record, ADQ_TRANSFER_MODE_NORMAL); print('ADQ_GetData returned {}'.format(adq_status(status))) # Re-arrange data in numpy arrays data_16bit_ch0 = np.frombuffer(target_buffers[0].contents[0],dtype=np.int16) data_16bit_ch1 = np.frombuffer(target_buffers[1].contents[0],dtype=np.int16) # Plot data if True: plt.figure(1) plt.clf() plt.plot(data_16bit_ch0, '.-') plt.plot(data_16bit_ch1, '.--') plt.show() # Only disarm trigger after data is collected ADQAPI.ADQ_DisarmTrigger(adq_cu, adq_num) ADQAPI.ADQ_MultiRecordClose(adq_cu, adq_num); # Delete ADQControlunit ADQAPI.DeleteADQControlUnit(adq_cu); print('Done') else: print('No ADQ connected.') # This can be used to completely unload the DLL in Windows #ct.windll.kernel32.FreeLibrary(ADQAPI._handle)
thomasbarillot/DAQ
HHGMonitor/ADQAPI_python/SDR14_Playlist_example.py
Python
mit
8,460
import unittest import pytk.geo as geo class GeoQuatTest(unittest.TestCase): def test_shape(self): self.assertRaises(geo.GeoException, geo.quat, []) self.assertRaises(geo.GeoException, geo.quat, [0]) self.assertRaises(geo.GeoException, geo.quat, [0, 1]) self.assertRaises(geo.GeoException, geo.quat, [0, 1, 2]) self.assertRaises(geo.GeoException, geo.quat, [0, 1, 2, 3, 4]) self.assertRaises(geo.GeoException, geo.quat, [0, 1, 2, 3, 4, 5]) self.assertRaises(geo.GeoException, geo.quat, [0, 1, 2, 3, 4, 5, 6]) self.assertRaises(geo.GeoException, geo.quat, [0, 1, 2, 3, 4, 5, 6, 7]) def test_equality(self): w = geo.quat([1, 0, 0, 0]) x = geo.quat([0, 1, 0, 0]) y = geo.quat([0, 0, 1, 0]) z = geo.quat([0, 0, 0, 1]) self.assertEqual(w, w) self.assertEqual(x, x) self.assertEqual(y, y) self.assertEqual(z, z) self.assertNotEqual(w, x) self.assertNotEqual(w, y) self.assertNotEqual(w, z) self.assertNotEqual(x, y) self.assertNotEqual(x, z) self.assertNotEqual(y, z) def test_add_sub(self): w = geo.quat([1, 0, 0, 0]) x = geo.quat([0, 1, 0, 0]) y = geo.quat([0, 0, 1, 0]) z = geo.quat([0, 0, 0, 1]) self.assertEqual( w + x + y , geo.quat([1, 1, 1, 0])) self.assertEqual( w + x + z, geo.quat([1, 1, 0, 1])) self.assertEqual( w + y + z, geo.quat([1, 0, 1, 1])) self.assertEqual( x + y + z, geo.quat([0, 1, 1, 1])) self.assertEqual( w - x + y , geo.quat([ 1, -1, 1, 0])) self.assertEqual( w - x + z, geo.quat([ 1, -1, 0, 1])) self.assertEqual( w - y + z, geo.quat([ 1, 0, -1, 1])) self.assertEqual( x - y + z, geo.quat([ 0, 1, -1, 1])) self.assertEqual(- w + x - y , geo.quat([-1, 1, -1, 0])) self.assertEqual(- w + x - z, geo.quat([-1, 1, 0, -1])) self.assertEqual(- w + y - z, geo.quat([-1, 0, 1, -1])) self.assertEqual( - x + y - z, geo.quat([ 0, -1, 1, -1])) def test_neg(self): w = geo.quat([1, 0, 0, 0]) x = geo.quat([0, 1, 0, 0]) y = geo.quat([0, 0, 1, 0]) z = geo.quat([0, 0, 0, 1]) self.assertEqual(w - x, w + (-x)) self.assertEqual(w - y, w + (-y)) self.assertEqual(w - z, w + (-z)) self.assertEqual(x - y, x + (-y)) self.assertEqual(x - z, x + (-z)) self.assertEqual(y - z, y + (-z)) def test_pow(self): w = geo.quat([1, 0, 0, 0]) x = geo.quat([0, 1, 0, 0]) y = geo.quat([0, 0, 1, 0]) z = geo.quat([0, 0, 0, 1]) self.assertAlmostEqual(w ** 2, 1) self.assertAlmostEqual(x ** 2, 1) self.assertAlmostEqual(y ** 2, 1) self.assertAlmostEqual(z ** 2, 1) self.assertAlmostEqual(( w - x + y ) ** 2, 3) self.assertAlmostEqual(( w - x + z) ** 2, 3) self.assertAlmostEqual(( w - y + z) ** 2, 3) self.assertAlmostEqual(( x - y + z) ** 2, 3) self.assertAlmostEqual((- w + x - y ) ** 2, 3) self.assertAlmostEqual((- w + x - z) ** 2, 3) self.assertAlmostEqual((- w + y - z) ** 2, 3) self.assertAlmostEqual(( - x + y - z) ** 2, 3) def test_conj(self): w = geo.quat([1, 0, 0, 0]) x = geo.quat([0, 1, 0, 0]) y = geo.quat([0, 0, 1, 0]) z = geo.quat([0, 0, 0, 1]) self.assertEqual(w + w.conj, geo.quat([2, 0, 0, 0])) self.assertEqual(x + x.conj, geo.quat([0, 0, 0, 0])) self.assertEqual(y + y.conj, geo.quat([0, 0, 0, 0])) self.assertEqual(z + z.conj, geo.quat([0, 0, 0, 0])) def test_inv(self): w = geo.quat([1, 0, 0, 0]) x = geo.quat([0, 1, 0, 0]) y = geo.quat([0, 0, 1, 0]) z = geo.quat([0, 0, 0, 1]) self.assertEqual(w * w.inv, geo.quat([1, 0, 0, 0])) self.assertEqual(w.inv * w, geo.quat([1, 0, 0, 0])) self.assertEqual(x * x.inv, geo.quat([1, 0, 0, 0])) self.assertEqual(x.inv * x, geo.quat([1, 0, 0, 0])) self.assertEqual(y * y.inv, geo.quat([1, 0, 0, 0])) self.assertEqual(y.inv * y, geo.quat([1, 0, 0, 0])) self.assertEqual(z * z.inv, geo.quat([1, 0, 0, 0])) self.assertEqual(z.inv * z, geo.quat([1, 0, 0, 0])) def test_normal(self): w = geo.quat([1, 0, 0, 0]) x = geo.quat([0, 1, 0, 0]) y = geo.quat([0, 0, 1, 0]) z = geo.quat([0, 0, 0, 1]) self.assertAlmostEqual((w ).normal ** 2, 1) self.assertAlmostEqual(( x ).normal ** 2, 1) self.assertAlmostEqual(( y ).normal ** 2, 1) self.assertAlmostEqual(( z).normal ** 2, 1) self.assertAlmostEqual((w + x ).normal ** 2, 1) self.assertAlmostEqual((w + y ).normal ** 2, 1) self.assertAlmostEqual((w + z).normal ** 2, 1) self.assertAlmostEqual(( x + y ).normal ** 2, 1) self.assertAlmostEqual(( x + z).normal ** 2, 1) self.assertAlmostEqual(( y + z).normal ** 2, 1) self.assertAlmostEqual((w + x + y ).normal ** 2, 1) self.assertAlmostEqual((w + x + z).normal ** 2, 1) self.assertAlmostEqual((w + y + z).normal ** 2, 1) self.assertAlmostEqual(( x + y + z).normal ** 2, 1) self.assertAlmostEqual((w + x + y + z).normal ** 2, 1) def test_as_rquat(self): w = geo.quat([1, 0, 0, 0]) x = geo.quat([0, 1, 0, 0]) y = geo.quat([0, 0, 1, 0]) z = geo.quat([0, 0, 0, 1]) self.assertEqual((w ).as_rquat, rquat([1, 0, 0, 0])) self.assertEqual(( x ).as_rquat, rquat([0, 1, 0, 0])) self.assertEqual(( y ).as_rquat, rquat([0, 0, 1, 0])) self.assertEqual(( z).as_rquat, rquat([0, 0, 0, 1])) self.assertEqual((w + x ).as_rquat, rquat([1, 1, 0, 0])) self.assertEqual((w + y ).as_rquat, rquat([1, 0, 1, 0])) self.assertEqual((w + z).as_rquat, rquat([1, 0, 0, 1])) self.assertEqual(( x + y ).as_rquat, rquat([0, 1, 1, 0])) self.assertEqual(( x + z).as_rquat, rquat([0, 1, 0, 1])) self.assertEqual(( y + z).as_rquat, rquat([0, 0, 1, 1])) self.assertEqual((w + x + y ).as_rquat, rquat([1, 1, 1, 0])) self.assertEqual((w + x + z).as_rquat, rquat([1, 1, 0, 1])) self.assertEqual((w + y + z).as_rquat, rquat([1, 0, 1, 1])) self.assertEqual(( x + y + z).as_rquat, rquat([0, 1, 1, 1])) self.assertEqual((w + x + y + z).as_rquat, rquat([1, 1, 1, 1])) def test_as_vect(self): w = geo.quat([1, 0, 0, 0]) x = geo.quat([0, 1, 0, 0]) y = geo.quat([0, 0, 1, 0]) z = geo.quat([0, 0, 0, 1]) self.assertEqual((w ).as_vect, vect([0, 0, 0])) self.assertEqual(( x ).as_vect, vect([1, 0, 0])) self.assertEqual(( y ).as_vect, vect([0, 1, 0])) self.assertEqual(( z).as_vect, vect([0, 0, 1])) self.assertEqual((w + x ).as_vect, vect([1, 0, 0])) self.assertEqual((w + y ).as_vect, vect([0, 1, 0])) self.assertEqual((w + z).as_vect, vect([0, 0, 1])) self.assertEqual(( x + y ).as_vect, vect([1, 1, 0])) self.assertEqual(( x + z).as_vect, vect([1, 0, 1])) self.assertEqual(( y + z).as_vect, vect([0, 1, 1])) self.assertEqual((w + x + y ).as_vect, vect([1, 1, 0])) self.assertEqual((w + x + z).as_vect, vect([1, 0, 1])) self.assertEqual((w + y + z).as_vect, vect([0, 1, 1])) self.assertEqual(( x + y + z).as_vect, vect([1, 1, 1])) self.assertEqual((w + x + y + z).as_vect, vect([1, 1, 1])) def test_mul(self): w = geo.quat([1, 0, 0, 0]) x = geo.quat([0, 1, 0, 0]) y = geo.quat([0, 0, 1, 0]) z = geo.quat([0, 0, 0, 1]) self.assertEqual( w * x , geo.quat([ 0, 1, 0, 0])) self.assertEqual( w * y , geo.quat([ 0, 0, 1, 0])) self.assertEqual( w * z , geo.quat([ 0, 0, 0, 1])) self.assertEqual( x * y , geo.quat([ 0, 0, 0, 1])) self.assertEqual( x * z , geo.quat([ 0, 0, -1, 0])) self.assertEqual( y * z , geo.quat([ 0, 1, 0, 0])) self.assertEqual( w * x * y , geo.quat([ 0, 0, 0, 1])) self.assertEqual( w * x * z , geo.quat([ 0, 0, -1, 0])) self.assertEqual( w * y * z , geo.quat([ 0, 1, 0, 0])) self.assertEqual( x * y * z , geo.quat([-1, 0, 0, 0])) self.assertEqual( w * x * y * z , geo.quat([-1, 0, 0, 0])) self.assertEqual( (w * x) * y * z , geo.quat([-1, 0, 0, 0])) self.assertEqual( w * (x * y) * z , geo.quat([-1, 0, 0, 0])) self.assertEqual( w * x * (y * z) , geo.quat([-1, 0, 0, 0])) self.assertEqual((w * x * y) * (z), geo.quat([-1, 0, 0, 0])) self.assertEqual((w * x) * (y * z), geo.quat([-1, 0, 0, 0])) self.assertEqual((w) * (x * y * z), geo.quat([-1, 0, 0, 0])) self.assertNotEqual(x * y, y * x) self.assertNotEqual(x * z, z * x) self.assertNotEqual(y * z, z * y) def test_rotate(self): v = geo.vect([0, 1, 2]) w = geo.quat([1, 0, 0, 0]) x = geo.quat([0, 1, 0, 0]) y = geo.quat([0, 0, 1, 0]) z = geo.quat([0, 0, 0, 1]) self.assertEqual( w * v , geo.vect([0, 1, 2])) self.assertEqual( x * v , geo.vect([0, -1, -2])) self.assertEqual( y * v , geo.vect([0, 1, -2])) self.assertEqual( z * v , geo.vect([0, -1, 2])) self.assertEqual( w * x * v , geo.vect([0, -1, -2])) self.assertEqual( w * y * v , geo.vect([0, 1, -2])) self.assertEqual( w * z * v , geo.vect([0, -1, 2])) self.assertEqual( x * y * v , geo.vect([0, -1, 2])) self.assertEqual( x * z * v , geo.vect([0, 1, -2])) self.assertEqual( y * z * v , geo.vect([0, -1, -2])) self.assertEqual( w * x * y * v , geo.vect([0, -1, 2])) self.assertEqual( w * x * z * v , geo.vect([0, 1, -2])) self.assertEqual( w * y * z * v , geo.vect([0, -1, -2])) self.assertEqual( x * y * z * v , geo.vect([0, 1, 2])) self.assertEqual( w * x * y * z * v , geo.vect([0, 1, 2]))
bigblindbais/pytk
tests/geo/test_quat.py
Python
mit
10,747
class ParamsException(Exception): """Exception raised when tp, fmt and size values are wrongs""" pass class LineSizeException(Exception): """Exception raised when line size is bigger then specified""" pass class LineIdentifierException(Exception): """Exception raised when line indentifier rased from the file is different to the line identifier used in the specification obs: line identifier is defined using .eq() function """ pass
anderson89marques/PyFixedFlatFile
pyFixedFlatFile/exceptions.py
Python
mit
476
import json import numpy as np import pandas as pd import numbers class NumpyAndPandasEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, (np.ndarray, np.matrix)): return [self.default(x) for x in obj] if isinstance(obj, pd.DataFrame): return [self.default(series) for _, series in obj.iterrows()] if isinstance(obj, pd.Series): return [self.default(val) for _, val in obj.iteritems()] if isinstance(obj, numbers.Integral): return int(obj) if isinstance(obj, (numbers.Real, numbers.Rational)): return float(obj) return super().default(obj)
PKU-Dragon-Team/Datalab-Utilities
__init__.py
Python
mit
672
"""Contain common module fields.""" # pylint: disable=too-many-public-methods from __future__ import absolute_import import re from django.db import models from django.core.exceptions import ValidationError class NameField(models.CharField): """Item name string field. This field is limited to 64 characters and contains the name(string). Good examples: * "name_lastname" * "name@lasrname" * 64 characters name Bad examples: * 65 characters name """ MAX_LEN = 150 def __init__(self, max_length=MAX_LEN, *args, **kwargs): super(NameField, self).__init__(*args, max_length=max_length, **kwargs) class DynamicIPAddressField(models.CharField): """DNS name or IP address.""" MAX_LEN = 64 def __init__(self, max_length=MAX_LEN, *args, **kwargs): super(DynamicIPAddressField, self).__init__(*args, max_length=max_length, **kwargs) class MACAddressField(models.CharField): """MAC address field.""" MAX_LEN = 17 # enables writing exactly 16 characters MAC_ADDRESS_REGEX = '(([0-9a-fA-F]{2}):){5}[0-9a-fA-F]{2}' def __init__(self, max_length=MAX_LEN, *args, **kwargs): super(MACAddressField, self).__init__(*args, max_length=max_length, **kwargs) def validate(self, value, model_instance): """Validate that the input value is a MAC address.""" super(MACAddressField, self).validate(value, model_instance) if re.match(self.MAC_ADDRESS_REGEX, value) is None: raise ValidationError('The input MAC address does not match the ' 'pattern of a MAC address') class PathField(models.CharField): r"""File-system path string field. This field is limited to 200 characters and contains string path split by slashes or backslashes. Good examples: * "/mnt/home/code/a.txt" * "/./a" * "c:\\windows\\temp" Bad examples: * "//mnt//@%$2" * "c:\;" """ MAX_LEN = 200 def __init__(self, max_length=MAX_LEN, *args, **kwargs): super(PathField, self).__init__(*args, max_length=max_length, **kwargs) class VersionField(models.CharField): """Item version string field. This field is limited to 10 characters and contains numbers and characters separated by dots. Good examples: * "4.12F" * "1.1423" Bad examples: * "4,12F" * "1/1423" """ MAX_LEN = 10 def __init__(self, max_length=MAX_LEN, *args, **kwargs): super(VersionField, self).__init__(*args, max_length=max_length, **kwargs) class PortField(models.PositiveSmallIntegerField): """Port number field (for IP connections).""" pass
gregoil/rotest
src/rotest/common/django_utils/fields.py
Python
mit
2,999
#!/usr/bin/env python """Convert 3 fastq inputs (read 1, read 2, UMI) into paired inputs with UMIs in read names Usage: bcbio_fastq_umi_prep.py single <out basename> <read 1 fastq> <read 2 fastq> <umi fastq> or: bcbio_fastq_umi_prep.py autopair [<list> <of> <fastq> <files>] Creates two fastq files with embedded UMIs: <out_basename>_R1.fq.gz <out_basename>_R2.fq.gz or a directory of fastq files with UMIs added to the names. """ from __future__ import print_function import argparse import os import sys from bcbio import utils from bcbio.bam import fastq from bcbio.provenance import do from bcbio.distributed.multi import run_multicore, zeromq_aware_logging transform_json = r"""{ "read1": "(?P<name>@.*)\\n(?P<seq>.*)\\n\\+(.*)\\n(?P<qual>.*)\\n", "read2": "(?P<name>@.*)\\n(?P<seq>.*)\\n\\+(.*)\\n(?P<qual>.*)\\n", "read3": "(@.*)\\n(?P<MB>.*)\\n\\+(.*)\\n(.*)\\n" } """ def run_single(args): add_umis_to_fastq(args.out_base, args.read1_fq, args.read2_fq, args.umi_fq) @utils.map_wrap @zeromq_aware_logging def add_umis_to_fastq_parallel(out_base, read1_fq, read2_fq, umi_fq, config): add_umis_to_fastq(out_base, read1_fq, read2_fq, umi_fq) def add_umis_to_fastq(out_base, read1_fq, read2_fq, umi_fq): print("Processing", read1_fq, read2_fq, umi_fq) cores = 8 out1_fq = out_base + "_R1.fq.gz" out2_fq = out_base + "_R2.fq.gz" transform_json_file = out_base + "-transform.json" with open(transform_json_file, "w") as out_handle: out_handle.write(transform_json) with utils.open_gzipsafe(read1_fq) as in_handle: ex_name = in_handle.readline().split(" ") if len(ex_name) == 2: fastq_tags_arg = "--keep_fastq_tags" else: fastq_tags_arg = "" cmd = ("umis fastqtransform {fastq_tags_arg} " "--fastq1out >(pbgzip -n {cores} -c > {out1_fq}) " "--fastq2out >(pbgzip -n {cores} -c > {out2_fq}) " "{transform_json_file} {read1_fq} " "{read2_fq} {umi_fq}") do.run(cmd.format(**locals()), "Add UMIs to paired fastq files") os.remove(transform_json_file) def run_autopair(args): outdir = utils.safe_makedir(args.outdir) to_run = [] extras = [] for fnames in fastq.combine_pairs(sorted(args.files)): if len(fnames) == 2: to_run.append(fnames) elif len(fnames) == 3: r1, r2, r3 = sorted(fnames) to_run.append([r1, r2]) extras.append(r3) else: assert len(fnames) == 1, fnames extras.append(fnames[0]) ready_to_run = [] for r1, r2 in to_run: target = os.path.commonprefix([r1, r2]) r3 = None for test_r3 in extras: if (os.path.commonprefix([r1, test_r3]) == target and os.path.commonprefix([r2, test_r3]) == target): r3 = test_r3 break assert r3, (r1, r2, extras) base_name = os.path.join(outdir, os.path.commonprefix([r1, r2, r3]).rstrip("_R")) ready_to_run.append([base_name, r1, r3, r2, {"algorithm": {}, "resources": {}}]) parallel = {"type": "local", "cores": len(ready_to_run), "progs": []} run_multicore(add_umis_to_fastq_parallel, ready_to_run, {"algorithm": {}}, parallel) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Add UMIs to fastq read names") sp = parser.add_subparsers(title="[sub-commands]") p = sp.add_parser("autopair", help="Automatically pair R1/R2/R3 fastq inputs") p.add_argument("--outdir", default="with_umis", help="Output directory to write UMI prepped fastqs") p.add_argument("files", nargs="*", help="All fastq files to pair and process") p.set_defaults(func=run_autopair) p = sp.add_parser("single", help="Run single set of fastq files with separate UMIs") p.add_argument("out_base", help="Base name for output files -- you get <base_name>_R1.fq.gz") p.add_argument("read1_fq", help="Input fastq, read 1") p.add_argument("read2_fq", help="Input fastq, read 2") p.add_argument("umi_fq", help="Input fastq, UMIs") p.set_defaults(func=run_single) if len(sys.argv) == 1: parser.print_help() args = parser.parse_args() args.func(args)
brainstorm/bcbio-nextgen
scripts/bcbio_fastq_umi_prep.py
Python
mit
4,259
#!/usr/bin/env python import collections def read_only(self, name, val): raise ValueError('not supported') class SimpleObject(object): def __init__(self, a, b, c): self.a = a self.b = b self.b = c class SimpleObjectImmutable(object): def __init__(self, a, b, c): self.a = a self.b = b self.b = c NamedTuple = collections.namedtuple('NamedTuple', ['a', 'b', 'c',]) def SimpleTuple(a, b, c): return (a, b, c) from types_c import c_struct
androm3da/struct_bench
types_.py
Python
mit
505
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from glob import glob from vlpp.utils import save_json from vlpp.qamosaic import Mosaic def main(): # Usefull directories os.mkdir("data") # Informations participant_id = "${sub.sub}" # Images Path try: anat = glob("${sub.anat}")[0] except: anat = None try: brainmask = glob("${sub.brainmask}")[0] except: brainmask = None try: atlas = glob("${sub.atlas}")[0] except: atlas = None try: pet = glob("${sub.pet}")[0] except: pet = None try: cerebellumCortex = glob("${sub.cerebellumCortex}")[0] except: cerebellumCortex = None try: atlasBaker = glob("${sub.atlasBaker}")[0] except: atlasBaker = None try: suvrBaker = glob("${sub.suvrBaker}")[0] except: suvrBaker = None # Anat tag = "anat" m = Mosaic(anat, mask=brainmask, cmap="gray") target = "data/{0}_{1}_mosaic.jpg".format(participant_id, tag) m.save(target) # Atlas tag = "atlas" m = Mosaic(anat, mask=brainmask, overlay=atlas, cmap="gray") target = "data/{0}_{1}_mosaic.jpg".format(participant_id, tag) m.save(target) # Pet tag = "pet" m = Mosaic(pet, mask=brainmask, contour=cerebellumCortex) target = "data/{0}_{1}_mosaic.jpg".format(participant_id, tag) m.save(target) # SUVR Baker tag = "suvrbaker" m = Mosaic(suvrBaker, mask=brainmask) target = "data/{0}_{1}_mosaic.jpg".format(participant_id, tag) m.save(target) # Atlas Baker tag = "atlasbaker" m = Mosaic(anat, mask=brainmask, overlay=atlasBaker, cmap="gray") target = "data/{0}_{1}_mosaic.jpg".format(participant_id, tag) m.save(target) # Pet Atlas tag = "petatlas" m = Mosaic(pet, mask=brainmask, overlay=atlas, cmap="gray") target = "data/{0}_{1}_mosaic.jpg".format(participant_id, tag) participant_info = m.save(target) participant_info["participant_id"] = participant_id jsonPath = "data/{}_registration_T1w.json".format(participant_id) save_json(jsonPath, participant_info) if __name__ == "__main__": main()
villeneuvelab/vlpp
pipelines/templates/qa_mosaics_T1w.py
Python
mit
2,115
from typing import Any, Dict, Tuple, Union __cached_defs: Dict[str, Any] = {} def __getattr__(name: str) -> Any: import importlib # noqa # isort:skip if name in __cached_defs: return __cached_defs[name] if name == "JsonBase": module = importlib.import_module(".json_base", "tomodachi.envelope") elif name == "ProtobufBase": try: module = importlib.import_module(".protobuf_base", "tomodachi.envelope") except Exception: # pragma: no cover class ProtobufBase(object): @classmethod def validate(cls, **kwargs: Any) -> None: raise Exception("google.protobuf package not installed") @classmethod async def build_message(cls, service: Any, topic: str, data: Any, **kwargs: Any) -> str: raise Exception("google.protobuf package not installed") @classmethod async def parse_message( cls, payload: str, proto_class: Any = None, validator: Any = None, **kwargs: Any ) -> Union[Dict, Tuple]: raise Exception("google.protobuf package not installed") __cached_defs[name] = ProtobufBase return __cached_defs[name] else: raise AttributeError("module 'tomodachi.envelope' has no attribute '{}'".format(name)) __cached_defs[name] = getattr(module, name) return __cached_defs[name] __all__ = ["JsonBase", "ProtobufBase"]
kalaspuff/tomodachi
tomodachi/envelope/__init__.py
Python
mit
1,527
""" example with 'calls_expected' in addtoBatch used """ import batchOpenMPI def f_mult(x) : return x*2.0 f = batchOpenMPI.batchFunction(f_mult) #creating function wrapper batchOpenMPI.begin_MPI_loop() # both the workers and the master process run the same code up until here f.addtoBatch(4,calls_expected=4) batchOpenMPI.processBatch() #get the workers to calculate all the inputs res = [f(4),f(4),f(4)] print(res) #another test f.addtoBatch(1) batchOpenMPI.processBatch() #get the workers to calculate all the inputs res = f(1), f(1) batchOpenMPI.end_MPI_loop(print_stats=True) #releases workers print("*** jobs executed by workers should be 2 ,(5 calls made),jobs uncollected should = 1, jobs_master=1")
hamish2014/batchOpenMPI
examples/ex3.py
Python
mit
719
# -*- coding: utf-8 -*- # Copyright (c) 2015 Holger Nahrstaedt # See COPYING for license details. """ wavelet toolbox """ from __future__ import division, print_function, absolute_import from .dwt import * from .utility import * from ._pyyawt import * from .dwt1d import * from .dwt2d import * from .dwt3d import * from .cowt import * from .cwt import * from .swt import * from .denoising import * from pyyawt.version import version as __version__ from numpy.testing import Tester __all__ = [s for s in dir() if not s.startswith('_')] test = Tester().test
holgern/pyyawt
pyyawt/__init__.py
Python
mit
565
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion import django.utils.timezone from django.conf import settings def siteconf_func(apps, schema_editor): Site = apps.get_model('sites', 'Site') db_alias = schema_editor.connection.alias Site.objects.using(db_alias).create( domain='herocomics.kr', name='히어로코믹스', ) class Migration(migrations.Migration): replaces = [('board', '0001_initial'), ('board', '0002_auto_20141210_2117'), ('board', '0003_attachment_checksum'), ('board', '0004_auto_20141211_1736'), ('board', '0005_auto_20141213_1307'), ('board', '0006_auto_20141213_2149'), ('board', '0007_auto_20141213_2221'), ('board', '0008_auto_20141214_1355'), ('board', '0009_auto_20141214_1817'), ('board', '0010_attachment'), ('board', '0011_auto_20141215_1514'), ('board', '0012_auto_20141221_1249'), ('board', '0013_auto_20141221_2059'), ('board', '0014_auto_20141222_1913'), ('board', '0015_auto_20141227_1704'), ('board', '0016_auto_20141227_2033'), ('board', '0017_auto_20141228_1146'), ('board', '0018_auto_20141228_2307'), ('board', '0019_auto_20141228_2318'), ('board', '0020_auto_20141229_0103'), ('board', '0021_auto_20141229_2017'), ('board', '0022_auto_20141229_2347')] dependencies = [ ('sites', '__first__'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('auth', '0001_initial'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(default=django.utils.timezone.now, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('email', models.EmailField(db_index=True, max_length=255, unique=True, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('nickname', models.CharField(max_length=16, unique=True)), ('groups', models.ManyToManyField(to='auth.Group', related_name='user_set', help_text='The groups this user belongs to. A user will get all permissions granted to each of his/her group.', blank=True, verbose_name='groups', related_query_name='user')), ('user_permissions', models.ManyToManyField(to='auth.Permission', related_name='user_set', help_text='Specific permissions for this user.', blank=True, verbose_name='user permissions', related_query_name='user')), ], options={ 'abstract': False, 'verbose_name_plural': 'users', 'verbose_name': 'user', }, bases=(models.Model,), ), migrations.RunPython( code=siteconf_func, reverse_code=None, atomic=False, ), migrations.CreateModel( name='Announcement', fields=[ ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Board', fields=[ ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=16)), ('slug', models.SlugField()), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=8)), ('slug', models.SlugField()), ('board', models.ForeignKey(to='board.Board')), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')), ('ipaddress', models.GenericIPAddressField(protocol='IPv4')), ('contents', models.TextField()), ('created_time', models.DateTimeField(auto_now_add=True)), ('comment', models.ForeignKey(to='board.Comment', related_name='subcomments', blank=True, null=True)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')), ('ipaddress', models.GenericIPAddressField(protocol='IPv4')), ('title', models.CharField(max_length=32)), ('contents', models.TextField()), ('viewcount', models.PositiveIntegerField(default=0)), ('created_time', models.DateTimeField(auto_now_add=True)), ('modified_time', models.DateTimeField()), ('board', models.ForeignKey(to='board.Board')), ('category', models.ForeignKey(to='board.Category', blank=True, null=True)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Tag', fields=[ ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=32, unique=True)), ], options={ }, bases=(models.Model,), ), migrations.AddField( model_name='post', name='tags', field=models.ManyToManyField(to='board.Tag', blank=True, null=True), preserve_default=True, ), migrations.AddField( model_name='post', name='user', field=models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='posts', blank=True, null=True), preserve_default=True, ), migrations.AddField( model_name='comment', name='post', field=models.ForeignKey(to='board.Post', related_name='comments'), preserve_default=True, ), migrations.AddField( model_name='comment', name='user', field=models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='comments', blank=True, null=True), preserve_default=True, ), migrations.AddField( model_name='announcement', name='boards', field=models.ManyToManyField(to='board.Board', blank=True, null=True, related_name='announcements'), preserve_default=True, ), migrations.AddField( model_name='announcement', name='post', field=models.OneToOneField(to='board.Post', related_name='announcement'), preserve_default=True, ), migrations.AlterField( model_name='category', name='board', field=models.ForeignKey(to='board.Board', related_name='categories'), preserve_default=True, ), migrations.AlterField( model_name='post', name='board', field=models.ForeignKey(to='board.Board', related_name='posts'), preserve_default=True, ), migrations.AlterField( model_name='post', name='category', field=models.ForeignKey(to='board.Category', related_name='posts', blank=True, null=True), preserve_default=True, ), migrations.CreateModel( name='Vote', fields=[ ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')), ('ipaddress', models.GenericIPAddressField(protocol='IPv4')), ('vote', models.SmallIntegerField(choices=[(-1, 'Not recommend'), (1, 'Recommend')])), ('comment', models.ForeignKey(to='board.Comment', related_name='_votes', blank=True, null=True)), ('post', models.ForeignKey(to='board.Post', related_name='_votes', blank=True, null=True)), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='_votes', blank=True, null=True)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='OneTimeUser', fields=[ ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')), ('nick', models.CharField(max_length=16)), ('password', models.CharField(max_length=128)), ], options={ }, bases=(models.Model,), ), migrations.AddField( model_name='comment', name='onetime_user', field=models.OneToOneField(to='board.OneTimeUser', on_delete=django.db.models.deletion.SET_NULL, related_name='comment', blank=True, null=True), preserve_default=True, ), migrations.AddField( model_name='post', name='onetime_user', field=models.OneToOneField(to='board.OneTimeUser', on_delete=django.db.models.deletion.SET_NULL, related_name='post', blank=True, null=True), preserve_default=True, ), migrations.AlterField( model_name='post', name='tags', field=models.ManyToManyField(to='board.Tag', blank=True, null=True, related_name='posts'), preserve_default=True, ), ]
devunt/hydrocarbon
board/migrations/0001_squashed_0022_auto_20141229_2347.py
Python
mit
10,743
#!/usr/bin/python import sys sys.path.append('..') from bcert_pb2 import * import binascii # fill out a minimal bitcoin cert cert = BitcoinCert() # first the data part (the part is later signed by the "higher level cert" or "the blockchain") cert.data.version = '0.1' cert.data.subjectname = 'Foo Inc.' email = cert.data.contacts.add() email.type = email.EMAIL email.value = 'foo@fooinc.com' url = cert.data.contacts.add() url.type = url.URL url.value = 'http://www.fooinc.com' paykey = cert.data.paymentkeys.add() paykey.usage = paykey.PAYMENT paykey.algorithm.type = paykey.algorithm.STATIC_BTCADDR # is default anyway key = paykey.value.append("mrMyF68x19kAc2byGKqR9MLfdAe1t5MPzh") #key = paykey.value.append("0211b60f23135a806aff2c8f0fbbe620c16ba05a9ca4772735c08a16407f185b34".decode('hex')) # this is standard in bitcoin ripemd(sha256()) from bitcoin import hash_160 # add signature to cert #sig = cert.signatures.add() #sig.algorithm.type = sig.algorithm.BCPKI #sig.algorithm.version = "0.3" #sig.value = "foo1" # for signatures of type BCPKI the alias IS the value, # other types place the signature of BitcoinCertDataToHash(certData) here, # for BCPKI this hash appears in the blockchain instead # see how the cert looks print cert # serialize it def CertToAscii(cert): ser = cert.SerializeToString() crc = binascii.crc32(ser) & 0xffffff # keep only last 24 bit (should use CRC-24 like OpenPGP) # OpenPGP uses initializations for its crc-24, see http://tools.ietf.org/html/rfc2440 asc = binascii.b2a_base64(cert.SerializeToString())[:-1] # without trailing newline asc += '=' # checksum is seperated by = asc += binascii.b2a_base64(('%06x'%crc).decode('hex')) return asc def CertToAsciiMsg(cert): ver = cert.version asc = CertToAscii(cert) res = '-----BEGIN BTCPKI CERTIFICATE-----\n' res += 'Version: '+cert.version+'\n\n' res += '\n'.join(asc[i:i+72] for i in xrange(0, len(asc), 72)) res += '-----END BTCPKI CERTIFICATE-----\n' return res # TODO: AsciiToCert from e import derivepubkey #print "deriving filename from: "+normalized #fname = id+'.bcrt' fname = 'foo1_static.bcrt' f=open(fname,'wb') f.write(cert.SerializeToString()) f.close() print "binary cert written to: "+fname #fname = id+'.acrt' #f=open(fname,'wb') #f.write(CertToAscii(cert)) #f.close() #print "ascii cert written to: "+fname #fname = 'my.data' #f=open(fname,'wb') #f.write(cert.data.SerializeToString()) #f.close() #print "binary data part written to: "+fname # see the hash print "hash of data part is: "+hash_160(cert.data.SerializeToString()).encode('hex') print "hex binary cert: "+cert.SerializeToString().encode('hex') #print CertToAscii(cert) #print CertToAsciiMsg(cert) # OLD #from subprocess import Popen,PIPE,check_call,call #p = Popen(['./bitcoind','-testnet','registeralias','foo3','0.5',hash],stdout=PIPE) #result = p.stdout.read() #print result
bcpki/bitcoin
src/bcert/examples/mk_foo1_static.py
Python
mit
2,934
# -*- coding: utf-8 -*- # # sammy documentation build configuration file, created by # sphinx-quickstart on Sun Feb 17 11:46:20 2013. # # 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 = [] # 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'sammy' copyright = u'2014, ChangeMyName' # 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.1' # The full version, including alpha/beta/rc tags. release = '0.1' # 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 = 'sammydoc' # -- 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', 'sammy.tex', u'sammy Documentation', u'ChangeToMyName', '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', 'sammy', u'sammy Documentation', [u'ChangeToMyName'], 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', 'sammy', u'sammy Documentation', u'ChangeToMyName', 'sammy', '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'
tyrog236/site-perso
docs/conf.py
Python
mit
7,708
#!/usr/bin/env python # encoding: utf-8 import argparse import cmd import os import shlex import sys from tabulate import tabulate import time from talus_client.cmds import TalusCmdBase import talus_client.api import talus_client.errors as errors from talus_client.models import Image,Field class ImageCmd(TalusCmdBase): """The Talus images command processor """ command_name = "image" def do_list(self, args): """List existing images in Talus image list Examples: List all images in Talus: image list """ parts = shlex.split(args) search = self._search_terms(parts, user_default_filter=False) if "sort" not in search: search["sort"] = "timestamps.created" if "--all" not in parts and "num" not in search: search["num"] = 20 self.out("showing first 20 results, use --all to see everything") fields = [] for image in self._talus_client.image_iter(**search): fields.append([ image.id, image.name, image.status["name"], image.tags, self._nice_name(image, "base_image") if image.base_image is not None else None, self._nice_name(image, "os"), image.md5, ]) print(tabulate(fields, headers=Image.headers())) def do_info(self, args): """List detailed information about an image info ID_OR_NAME Examples: List info about the image named "Win 7 Pro" image info "Win 7 Pro" """ pass def do_import(self, args): """Import an image into Talus import FILE -n NAME -o OSID [-d DESC] [-t TAG1,TAG2,..] [-u USER] [-p PASS] [-i] FILE The file to import -o,--os ID or name of the operating system model -n,--name The name of the resulting image (default: basename(FILE)) -d,--desc A description of the image (default: "") -t,--tags Tags associated with the image (default: []) -f,--file-id The id of an already-uploaded file (NOT A NORMAL USE CASE) -u,--username The username to be used in the image (default: user) -p,--password The password to be used in the image (default: password) -i,--interactive To interact with the imported image for setup (default: False) Examples: To import an image from VMWare at ``~/images/win7pro.vmdk`` named "win 7 pro test" and to be given a chance to perform some manual setup/checks: image import ~/images/win7pro.vmdk -n "win 7 pro test" -i -o "win7pro" -t windows7,x64,IE8 """ parser = argparse.ArgumentParser() parser.add_argument("file", type=str) parser.add_argument("--os", "-o") parser.add_argument("--name", "-n") parser.add_argument("--desc", "-d", default="desc") parser.add_argument("--file-id", "-f", default=None) parser.add_argument("--tags", "-t", default="") parser.add_argument("--username", "-u", default="user") parser.add_argument("--password", "-p", default="password") parser.add_argument("--interactive", "-i", action="store_true", default=False) args = parser.parse_args(shlex.split(args)) args.tags = args.tags.split(",") if args.name is None: args.name = os.path.basename(args.file) image = self._talus_client.image_import( image_path = args.file, image_name = args.name, os_id = args.os, desc = args.desc, tags = args.tags, file_id = args.file_id, username = args.username, password = args.password ) self._wait_for_image(image, args.interactive) def do_edit(self, args): """Edit an existing image. Interactive mode only """ if args.strip() == "": raise errors.TalusApiError("you must provide a name/id of an image to edit it") parts = shlex.split(args) leftover = [] image_id_or_name = None search = self._search_terms(parts, out_leftover=leftover) if len(leftover) > 0: image_id_or_name = leftover[0] image = self._resolve_one_model(image_id_or_name, Image, search) if image is None: raise errors.TalusApiError("could not find talus image with id {!r}".format(image_id_or_name)) while True: model_cmd = self._make_model_cmd(image) cancelled = model_cmd.cmdloop() if cancelled: break error = False if image.os is None: self.err("You must specify the os") error = True if image.name is None or image.name == "": self.err("You must specify a name for the image") error = True if image.base_image is None: self.err("You must specify the base_image for your new image") error = True if error: continue try: image.timestamps = {"modified": time.time()} image.save() self.ok("edited image {}".format(image.id)) self.ok("note that this DOES NOT start the image for configuring!") except errors.TalusApiError as e: self.err(e.message) return def do_create(self, args): """Create a new image in talus using an existing base image. Anything not explicitly specified will be inherited from the base image, except for the name, which is required. create -n NAME -b BASEID_NAME [-d DESC] [-t TAG1,TAG2,..] [-u USER] [-p PASS] [-o OSID] [-i] -o,--os ID or name of the operating system model -b,--base ID or name of the base image -n,--name The name of the resulting image (default: basename(FILE)) -d,--desc A description of the image (default: "") -t,--tags Tags associated with the image (default: []) --shell Forcefully drop into an interactive shell -v,--vagrantfile A vagrant file that will be used to congfigure the image -i,--interactive To interact with the imported image for setup (default: False) Examples: To create a new image based on the image with id 222222222222222222222222 and adding a new description and allowing for manual user setup: image create -b 222222222222222222222222 -d "some new description" -i """ args = shlex.split(args) if self._go_interactive(args): image = Image() self._prep_model(image) image.username = "user" image.password = "password" image.md5 = " " image.desc = "some description" image.status = { "name": "create", "vagrantfile": None, "user_interaction": True } while True: model_cmd = self._make_model_cmd(image) model_cmd.add_field( "interactive", Field(True), lambda x,v: x.status.update({"user_interaction": v}), lambda x: x.status["user_interaction"], desc="If the image requires user interaction for configuration", ) model_cmd.add_field( "vagrantfile", Field(str), lambda x,v: x.status.update({"vagrantfile": open(v).read()}), lambda x: x.status["vagrantfile"], desc="The path to the vagrantfile that will configure the image" ) cancelled = model_cmd.cmdloop() if cancelled: break error = False if image.os is None: self.err("You must specify the os") error = True if image.name is None or image.name == "": self.err("You must specify a name for the image") error = True if image.base_image is None: self.err("You must specify the base_image for your new image") error = True if error: continue try: image.timestamps = {"created": time.time()} image.save() self.ok("created new image {}".format(image.id)) except errors.TalusApiError as e: self.err(e.message) else: self._wait_for_image(image, image.status["user_interaction"]) return parser = self._argparser() parser.add_argument("--os", "-o", default=None) parser.add_argument("--base", "-b", default=None) parser.add_argument("--name", "-n", default=None) parser.add_argument("--desc", "-d", default="") parser.add_argument("--tags", "-t", default="") parser.add_argument("--vagrantfile", "-v", default=None, type=argparse.FileType("rb")) parser.add_argument("--interactive", "-i", action="store_true", default=False) args = parser.parse_args(args) if args.name is None: raise errors.TalusApiError("You must specify an image name") vagrantfile_contents = None if args.vagrantfile is not None: vagrantfile_contents = args.vagrantfile.read() if args.tags is not None: args.tags = args.tags.split(",") error = False validation = { "os" : "You must set the os", "base" : "You must set the base", "name" : "You must set the name", } error = False for k,v in validation.iteritems(): if getattr(args, k) is None: self.err(v) error = True if error: parser.print_help() return image = self._talus_client.image_create( image_name = args.name, base_image_id_or_name = args.base, os_id = args.os, desc = args.desc, tags = args.tags, vagrantfile = vagrantfile_contents, user_interaction = args.interactive ) self._wait_for_image(image, args.interactive) def do_configure(self, args): """Configure an existing image in talus configure ID_OR_NAME [-v PATH_TO_VAGRANTFILE] [-i] id_or_name The ID or name of the image that is to be configured (required) -i,--interactive To interact with the imported image for setup (default: False) -v,--vagrantfile The path to the vagrantfile that should be used to configure the image (default=None) Examples: To configure an image named "Windows 7 x64 Test", using a vagrantfile found at `~/vagrantfiles/UpdateIE` with no interaction: configure "Windows 7 x64 Test" --vagrantfile ~/vagrantfiles/UpdateIE """ parser = self._argparser() parser.add_argument("image_id_or_name", type=str) parser.add_argument("--interactive", "-i", action="store_true", default=False) parser.add_argument("--vagrantfile", "-v", default=None, type=argparse.FileType("rb")) args = parser.parse_args(shlex.split(args)) vagrantfile_contents = None if args.vagrantfile is not None: vagrantfile_contents = args.vagrantfile.read() image = self._talus_client.image_configure( args.image_id_or_name, vagrantfile=vagrantfile_contents, user_interaction=args.interactive ) if image is None: return self._wait_for_image(image, args.interactive) def do_delete(self, args): """Attempt to delete the specified image. This may fail if the image is the base image for another image. delete id_or_name id_or_name The ID or name of the image that is to be deleted """ args = shlex.split(args) image = self._talus_client.image_delete(args[0]) if image is None: return try: while image.status["name"] == "delete": time.sleep(1) image.refresh() if "error" in image.status: self.err("could not delete image due to: " + image.status["error"]) else: self.ok("image succesfully deleted") except: self.err("could not delete image") # ---------------------------- # UTILITY # ---------------------------- def _wait_for_image(self, image, interactive): """Wait for the image to be ready, either for interactive interaction or to enter the ready state""" if interactive: while image.status["name"] != "configuring": time.sleep(1) image.refresh() self.ok("Image is up and running at {}".format(image.status["vnc"]["vnc"]["uri"])) self.ok("Shutdown (yes, nicely shut it down) to save your changes") else: while image.status["name"] != "ready": time.sleep(1) image.refresh() self.ok("image {!r} is ready for use".format(image.name))
optiv-labs/talus_client
talus_client/cmds/images.py
Python
mit
11,313
"""Yummly data models. """ from inspect import getargspec class Storage(dict): """An object that is like a dict except `obj.foo` can be used in addition to `obj['foo']`. Raises Attribute/Key errors for missing references. >>> o = Storage(a=1, b=2) >>> assert(o.a == o['a']) >>> assert(o.b == o['b']) >>> o.a = 2 >>> print o['a'] 2 >>> x = o.copy() >>> assert(x == o) >>> del o.a >>> print o.a Traceback (most recent call last): ... AttributeError: a >>> print o['a'] Traceback (most recent call last): ... KeyError: 'a' >>> o._get_fields() Traceback (most recent call last): ... TypeError: ... """ def __getattr__(self, key): if key in self: return self[key] else: raise AttributeError(key) def __setattr__(self, key, value): self[key] = value def __delattr__(self, key): if key in self: del self[key] else: raise AttributeError(key) def __repr__(self): return '%s(%s)' % (self.__class__.__name__, dict.__repr__(self)) @classmethod def _get_fields(cls): """Return class' __init__() args excluding `self`. Assumes that calling class has actually implemented __init__(), otherwise, this will fail. """ # For classes, first element of args == self which we don't want. return getargspec(cls.__init__).args[1:] ################################################## # Get recipe related models ################################################## class Recipe(Storage): """Recipe model.""" def __init__(self, **kargs): self.id = kargs['id'] self.name = kargs['name'] self.rating = kargs.get('rating') self.totalTime = kargs.get('totalTime') or 0 self.totalTimeInSeconds = kargs.get('totalTimeInSeconds') or 0 self.ingredientLines = kargs.get('ingredientLines') or [] self.numberOfServings = kargs.get('numberOfServings') self.yields = kargs.get('yields') self.attributes = kargs.get('attributes') or {} self.source = RecipeSource(**(kargs.get('source') or {})) self.attribution = Attribution(**(kargs.get('attribution') or {})) # NOTE: For `flavors`, the keys are returned capitalized so normalize # to lowercase since search results' flavor keys are lowercase. flavors = kargs.get('flavors') or {} self.flavors = Flavors(**{key.lower(): value for key, value in flavors.iteritems()}) self.nutritionEstimates = [NutritionEstimate(**nute) for nute in (kargs.get('nutritionEstimates') or [])] self.images = [RecipeImages(**imgs) for imgs in (kargs.get('images') or [])] class Flavors(Storage): """Flavors model.""" def __init__(self, **kargs): self.salty = kargs.get('salty') self.meaty = kargs.get('meaty') self.piquant = kargs.get('piquant') self.bitter = kargs.get('bitter') self.sour = kargs.get('sour') self.sweet = kargs.get('sweet') class Attribution(Storage): """Attribution model.""" def __init__(self, **kargs): self.html = kargs.get('html') self.url = kargs.get('url') self.text = kargs.get('text') self.logo = kargs.get('logo') class NutritionEstimate(Storage): """Nutrition estimate model.""" def __init__(self, **kargs): self.attribute = kargs.get('attribute') self.description = kargs.get('description') self.value = kargs.get('value') self.unit = NutritionUnit(**(kargs.get('unit') or {})) class NutritionUnit(Storage): """Nutrition unit model.""" def __init__(self, **kargs): self.id = kargs['id'] self.abbreviation = kargs.get('abbreviation') self.plural = kargs.get('plural') self.pluralAbbreviation = kargs.get('pluralAbbreviation') class RecipeImages(Storage): """Recipe images model.""" def __init__(self, **kargs): self.hostedLargeUrl = kargs.get('hostedLargeUrl') self.hostedSmallUrl = kargs.get('hostedSmallUrl') class RecipeSource(Storage): """Recipe source model.""" def __init__(self, **kargs): self.sourceRecipeUrl = kargs.get('sourceRecipeUrl') self.sourceSiteUrl = kargs.get('sourceSiteUrl') self.sourceDisplayName = kargs.get('sourceDisplayName') ################################################## # Search related models ################################################## class SearchResult(Storage): """Search result model.""" def __init__(self, **kargs): self.totalMatchCount = kargs['totalMatchCount'] self.criteria = SearchCriteria(**kargs['criteria']) self.facetCounts = kargs['facetCounts'] self.matches = [SearchMatch(**match) for match in kargs['matches']] self.attribution = Attribution(**kargs['attribution']) class SearchMatch(Storage): """Search match model.""" def __init__(self, **kargs): self.id = kargs['id'] self.recipeName = kargs['recipeName'] self.rating = kargs.get('rating') self.totalTimeInSeconds = kargs.get('totalTimeInSeconds', 0) self.ingredients = kargs.get('ingredients') self.flavors = Flavors(**(kargs.get('flavors') or {})) self.smallImageUrls = kargs.get('smallImageUrls') self.sourceDisplayName = kargs.get('sourceDisplayName', '') self.attributes = kargs.get('attributes') class SearchCriteria(Storage): """Search criteria model.""" def __init__(self, **kargs): self.maxResults = kargs.get('maxResults') self.resultsToSkip = kargs.get('resultsToSkip') self.terms = kargs.get('terms') self.requirePictures = kargs.get('requirePictures') self.facetFields = kargs.get('facetFields') self.allowedIngredients = kargs.get('allowedIngredients') self.excludedIngredients = kargs.get('excludedIngredients') self.attributeRanges = kargs.get('attributeRanges', {}) self.allowedAttributes = kargs.get('allowedAttributes', []) self.excludedAttributes = kargs.get('excludedAttributes', []) self.allowedDiets = kargs.get('allowedDiets', []) self.nutritionRestrictions = kargs.get('nutritionRestrictions', {}) ################################################## # Metadata related models ################################################## class MetaAttribute(Storage): """Base class for metadata attributes.""" def __init__(self, **kargs): self.id = kargs['id'] self.description = kargs['description'] self.localesAvailableIn = kargs['localesAvailableIn'] self.name = kargs['name'] self.searchValue = kargs['searchValue'] self.type = kargs['type'] class MetaHoliday(MetaAttribute): """Holiday metadata model.""" pass class MetaCuisine(MetaAttribute): """Cuisine metadata model.""" pass class MetaCourse(MetaAttribute): """Course metadata model.""" pass class MetaTechnique(MetaAttribute): """Technique metadata model.""" pass class MetaSource(Storage): """Source metadata model.""" def __init__(self, **kargs): self.faviconUrl = kargs['faviconUrl'] self.description = kargs['description'] self.searchValue = kargs['searchValue'] class MetaBrand(Storage): """Brand metadata model.""" def __init__(self, **kargs): self.faviconUrl = kargs['faviconUrl'] self.description = kargs['description'] self.searchValue = kargs['searchValue'] class MetaDiet(Storage): """Diet metadata model.""" def __init__(self, **kargs): self.id = kargs['id'] self.localesAvailableIn = kargs['localesAvailableIn'] self.longDescription = kargs['longDescription'] self.searchValue = kargs['searchValue'] self.shortDescription = kargs['shortDescription'] self.type = kargs['type'] class MetaAllergy(Storage): """Allergy metadata model.""" def __init__(self, **kargs): self.id = kargs['id'] self.localesAvailableIn = kargs['localesAvailableIn'] self.longDescription = kargs['longDescription'] self.shortDescription = kargs['shortDescription'] self.searchValue = kargs['searchValue'] self.type = kargs['type'] class MetaIngredient(Storage): """Ingredient metadata model.""" def __init__(self, **kargs): self.description = kargs['description'] self.term = kargs['term'] self.searchValue = kargs['searchValue']
dgilland/yummly.py
yummly/models.py
Python
mit
8,795
# -*- coding: utf-8 -*- import scrapy import json import re from locations.items import GeojsonPointItem class McDonalsILSpider(scrapy.Spider): name = "mcdonalds_il" allowed_domains = ["www.mcdonalds.co.il"] start_urls = ( 'https://www.mcdonalds.co.il/%D7%90%D7%99%D7%AA%D7%95%D7%A8_%D7%9E%D7%A1%D7%A2%D7%93%D7%94', ) def store_hours(self, data): day_groups = [] this_day_group = {} weekdays = ['Su', 'Mo', 'Th', 'We', 'Tu', 'Fr', 'Sa'] for day_hour in data: if day_hour['idx'] > 7: continue hours = '' start, end = day_hour['value'].split("-")[0].strip(), day_hour['value'].split("-")[1].strip() short_day = weekdays[day_hour['idx'] - 1] hours = '{}:{}-{}:{}'.format(start[:2], start[3:], end[:2], end[3:]) if not this_day_group: this_day_group = { 'from_day': short_day, 'to_day': short_day, 'hours': hours, } elif hours == this_day_group['hours']: this_day_group['to_day'] = short_day elif hours != this_day_group['hours']: day_groups.append(this_day_group) this_day_group = { 'from_day': short_day, 'to_day': short_day, 'hours': hours, } day_groups.append(this_day_group) if not day_groups: return None opening_hours = '' if len(day_groups) == 1 and not day_groups[0]: return None if len(day_groups) == 1 and day_groups[0]['hours'] in ('00:00-23:59', '00:00-00:00'): opening_hours = '24/7' else: for day_group in day_groups: if day_group['from_day'] == day_group['to_day']: opening_hours += '{from_day} {hours}; '.format(**day_group) else: opening_hours += '{from_day}-{to_day} {hours}; '.format(**day_group) opening_hours = opening_hours [:-2] return opening_hours def parse_Ref(self, data): match = re.search(r'store_id=(.*\d)', data) ref = match.groups()[0] return ref def parse_name(self, name): name = name.xpath('//h1/text()').extract_first() return name.strip() def parse_latlon(self, data): lat = lon = '' data = data.xpath('//div[@id="map"]') lat = data.xpath('//@data-lat').extract_first() lon = data.xpath('//@data-lng').extract_first() return lat, lon def parse_phone(self, phone): phone = phone.xpath('//div[@class="padding_hf_v sp_padding_qt_v"]/a/text()').extract_first() if not phone: return "" return phone.strip() def parse_address(self, address): address = address.xpath('//h2/strong/text()').extract_first() return address.strip() def parse_store(self, response): data = response.body_as_unicode() name = self.parse_name(response) address = self.parse_address(response) phone = self.parse_phone(response) lat, lon = self.parse_latlon(response) properties = { 'ref': response.meta['ref'], 'phone': phone, 'lon': lon, 'lat': lat, 'name': name, 'addr_full': address } yield GeojsonPointItem(**properties) def parse(self, response): stores = response.xpath('//div[@class="store_wrap link"]/a/@href').extract() for store in stores: ref = self.parse_Ref(store) yield scrapy.Request('https:' + store, meta={'ref': ref}, callback=self.parse_store)
iandees/all-the-places
locations/spiders/mcdonalds_il.py
Python
mit
3,804
class DinkyFish: def monthsUntilCrowded(self, tankVolume, maleNum, femaleNum): months = 0 while maleNum + femaleNum <= (tankVolume * 2): minFishes = min(maleNum, femaleNum) maleNum += minFishes femaleNum += minFishes months += 1 return months
Oscarbralo/TopBlogCoder
SRMs/SRM180PY/250/250.py
Python
mit
326
#!/usr/bin/env python # coding=utf-8 from mcurl.utils import monkey_patch import zmq.green as zmq import sys import json __author__ = 'chenfengyuan' monkey_patch.dummy() def client(port): host = '127.0.0.1' context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://%s:%s" % (host, port)) socket.send(b'') message = socket.recv() socket.close() data = json.loads(message.decode('utf-8')) """:type: list""" data.sort(key=lambda x: x['filename']) for info in data: print('%s %.3fGB %.2f%%' % (info['filename'], info['filesize'] / 1024 / 1024 / 1024, info['percentage'] * 100)) def main(): port = int(sys.argv[1]) client(port) if __name__ == '__main__': main()
chenfengyuan/mcurl
python3/get_info.py
Python
mit
751
from os.path import expanduser ###################### # Common project files ###################### # These are files, packages, and folders that will be copied from the # development folder to the destination obfuscated project. ###################### # Python packages to obfuscate. obfuscated_packages = [ 'controller', 'db', 'dbdata', 'logic', 'migrations', 'platform_api', 'tests', 'view' ] # Non-python folders and Python packages that are not obfuscated. # Note: Tests are a special case: both obfuscated and unobfuscated versions # are desired. unobfuscated_folders = [ 'csvlite', 'fonts', 'help', 'images', 'initial_data', 'international', 'kivygraph', 'tests', ] # Required files or types in the project directory (that is, the base # directory in which all the common packages exist in) that must be # obfuscated. For example, main.py is not in any of the common packages, but # should be obfuscated and included in the project, so *.py (or alternatively, # main.py) is included here. obfuscated_root_files = [ '*.kv', '*.py', ] # Required files or types in the project directory that should not be # obfuscated. unobfuscated_root_files = [ '*.ini', '*.txt', ] ##################### # Default directories ##################### # A project is moved through directories as follows: # 1. It is copied into IMPORTED (use import_project/fabfile.py). # 2. The IMPORTED project is obfuscated and written into OBFUSCATED (run # pymixup.py). # 3. When an obfuscated project is ready to test, it is copied into # EXPORTED for a particular platform (e.g., for ios, use # export_ios/fabfile.py). # If no platform is specified, it will be copied into a folder called # "default". # 4. When an exported project is deployed, it is copied into DEPLOYED under # its version number. # # Note that files in IMPORTED, OBFUSCATED, and EXPORTED are overwritten with # each refresh from the development project. When a project is deployed, # however, a permanent copy is retained under its version number. ##################### # Project name. This should be the name of the last folder in the project # path. The name is appended to the directories below. project_name = 'MyProject' # The base directory of the project to obfuscate. # For example, the base directory of a project in '~/projects/MyProject' would # be '~/projects' project_base_dir = expanduser('~/PycharmProjects') # The directory to copy the imported development project files to. # Make sure this base directory exists; the fabfile scripts expects it. # The project_name will be appended to the directory. # For example, specify '~/projects/IMPORTED' to have the files from the # project MyProject copied into '~/projects/IMPORTED/MyProject'. imported_dir = expanduser('~/projects/IMPORTED') # The directory to write the obfuscated files to. # Make sure this base directory exists; the fabfile scripts expects it. # The project_name and platform will be appended to the directory. # For example, if '~/projects/OBFUSCATED' is specified, then the project # MyProject obfuscated for the android platform will be placed in # '~/projects/OBFUSCATED/MyProject/android'. obfuscated_dir = expanduser('~/projects/OBFUSCATED') # The directory to write the exported files to. # Make sure this base directory exists; the fabfile scripts expects it. # The project_name and platform will be appended to the directory. # For example, if '~/projects/EXPORTED' is specified, then the project # MyProject exported for the android platform will be placed in # '~/projects/EXPORTED/MyProject/android'. exported_dir = expanduser('~/projects/EXPORTED') # The directory to write the exported files to. # Make sure this base directory exists; the fabfile scripts expects it. # For example, if '~/projects/EXPORTED' is specified, then the project # MyProject deployed for the android platform for version 1.3.2 will be placed # in '~/projects/DEPLOYED/MyProject/android/1.3.2'. deployed_dir = expanduser('~/projects/DEPLOYED') # The directory that contains extra files and folders needed for the project. extras_dir = expanduser('~/project/EXTRAS')
rdevost/pymixup
common/settings.py
Python
mit
4,238
from django import template register = template.Library() @register.assignment_tag(takes_context=True) def has_bookmark_permission(context, action): """Checks if the current user can bookmark the action item. Returns a boolean. Syntax:: {% has_bookmark_permission action %} """ request = context['request'] if not request.user.is_authenticated(): return False has_permission = True if action.target.approval_required and not request.user.can_access_all_projects: has_permission = False if not has_permission: return False return True @register.assignment_tag(takes_context=True) def get_existing_bookmark(context, action): request = context['request'] if not request.user.is_authenticated(): return None existing_bookmark = request.user.bookmark_set.filter( object_pk=action.action_object.pk, content_type=action.action_object_content_type ).first() return existing_bookmark
HMSBeagle1831/rapidscience
rlp/bookmarks/templatetags/bookmarks.py
Python
mit
990
# -*- coding: utf-8 -*- import sys, time from PySide import QtGui, QtCore from presentacion.form_abm_paciente import FormPacienteABM if __name__ == "__main__": app = QtGui.QApplication(sys.argv) # Create and display the splash screen splash_pix = QtGui.QPixmap('splash.png') splash = QtGui.QSplashScreen(splash_pix, QtCore.Qt.WindowStaysOnTopHint) splash.setWindowFlags( QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint) splash.setEnabled(False) # splash = QSplashScreen(splash_pix) # adding progress bar progressBar = QtGui.QProgressBar(splash) progressBar.setMaximum(10) progressBar.setGeometry(0, 0, splash_pix.width(), 20) css = "QProgressBar::chunk { background: yellow; }" progressBar.setStyleSheet(css) # splash.setMask(splash_pix.mask()) splash.show() for i in range(1, 11): progressBar.setValue(i) t = time.time() while time.time() < t + 0.1: app.processEvents() # Simulate something that takes time time.sleep(1) form = FormPacienteABM() form.show() splash.close() sys.exit(app.exec_())
gabofer82/taller_programacion_2017
Documentación/SOURCE/Programa/main.py
Python
mit
1,181
#!/usr/bin/python3 from tkinter import * from tkinter.messagebox import * fenetre = Tk() fenetre.title("The Enigma Machine") fenetre.configure(background='white') fenetre.geometry("550x800") class AutoScrollbar(Scrollbar): #create a 'responsive' scrollbar def set(self, lo, hi): if float(lo) <= 0.0 and float(hi) >= 1.0: self.tk.call("grid", "remove", self) else: self.grid() Scrollbar.set(self, lo, hi) def pack(self, **kw): raise(TclError, "can't pack this widget") def place(self, **kw): raise(TclError, "can't grid this widget") vscrollbar = AutoScrollbar(fenetre) vscrollbar.grid(row=0, column=1, sticky=N+S) hscrollbar = AutoScrollbar(fenetre, orient=HORIZONTAL) hscrollbar.grid(row=1, column=0, sticky=E+W) canvas = Canvas(fenetre, yscrollcommand=vscrollbar.set, xscrollcommand=hscrollbar.set) canvas.grid(row=0, column=0, sticky=N+S+E+W) vscrollbar.config(command=canvas.yview) hscrollbar.config(command=canvas.xview) # make the canvas expandable fenetre.grid_rowconfigure(0, weight=1) fenetre.grid_columnconfigure(0, weight=1) # # create canvas contents frame = Frame(canvas, background="white", borderwidth=0) #enigma_image image = PhotoImage(file="enigma.gif") Label(frame, image=image, background="white", borderwidth=0).pack(padx=10, pady=10, side=TOP) #help_button def help(): showinfo("The Enigma Machine Quick Start", "Hello World!\nThis is a quick tutorial on how to use this app!\nFirst, you need to choose the order of the rotors.\nThen you need to set the rotors' position\nYou can finally write your message and encrypt it by pressing the Return key!\nThat's it, you've just encrypt your first enigma message!\n Have fun!") helpButton = Button(frame, text ="Help! Quick Start", command = help, background="white") helpButton.pack(padx=5, pady=5) #spinboxes_choose_rotors frameRotor = Frame(frame, background='white') var4 = StringVar() spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]", "rotor2=[N,T,Z,P,S,F,B,O,K,M,W,R,C,J,D,I,V,L,A,E,Y,U,X,H,G,Q]", "rotor3=[J,V,I,U,B,H,T,C,D,Y,A,K,E,Q,Z,P,O,S,G,X,N,R,M,W,F,L]"), textvariable=var4, width=44) var4.set("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]") spinbox.grid(row=0, column=1) var5 = StringVar() spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]", "rotor2=[N,T,Z,P,S,F,B,O,K,M,W,R,C,J,D,I,V,L,A,E,Y,U,X,H,G,Q]", "rotor3=[J,V,I,U,B,H,T,C,D,Y,A,K,E,Q,Z,P,O,S,G,X,N,R,M,W,F,L]"), textvariable=var5, width=44) var5.set("rotor2=[N,T,Z,P,S,F,B,O,K,M,W,R,C,J,D,I,V,L,A,E,Y,U,X,H,G,Q]") spinbox.grid(row=1, column=1) var6 = StringVar() spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]", "rotor2=[N,T,Z,P,S,F,B,O,K,M,W,R,C,J,D,I,V,L,A,E,Y,U,X,H,G,Q]", "rotor3=[J,V,I,U,B,H,T,C,D,Y,A,K,E,Q,Z,P,O,S,G,X,N,R,M,W,F,L]"), textvariable=var6, width=44) var6.set("rotor3=[J,V,I,U,B,H,T,C,D,Y,A,K,E,Q,Z,P,O,S,G,X,N,R,M,W,F,L]") spinbox.grid(row=2, column=1) var7 = StringVar() spinbox = Spinbox(frameRotor, values = ("reflec=[Y,R,U,H,Q,S,L,D,P,X,N,G,O,K,M,I,E,B,F,Z,C,W,V,J,A,T]"), textvariable=var7, width=44) var7.set("reflec=[Y,R,U,H,Q,S,L,D,P,X,N,G,O,K,M,I,E,B,F,Z,C,W,V,J,A,T]") spinbox.grid(row=3, column=1) rotorn1 = Label(frameRotor, text='Slot n°=1:', padx=10, pady=5, background="white") rotorn1.grid(row=0, column=0) rotorn2 = Label(frameRotor, text='Slot n°=2:', padx=10, pady=5, background="white") rotorn2.grid(row=1, column=0) rotorn3 = Label(frameRotor, text='Slot n°=3:', padx=10, pady=5, background="white") rotorn3.grid(row=2, column=0) reflectorn = Label(frameRotor, text='Reflector:', padx=10, pady=5, background="white") reflectorn.grid(row=3, column=0) frameRotor.pack() #frame_to_set_rotor_position frame1 = Frame(frame, borderwidth=0, relief=FLAT, background='white') frame1.pack(side=TOP, padx=10, pady=10) def update1(x): x = int(x) alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] lab1.configure(text='position : {}'.format(alphabetList[x-1])) def update2(x): x = int(x) alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] lab2.configure(text='position : {}'.format(alphabetList[x-1])) def update3(x): x = int(x) alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] lab3.configure(text='position : {}'.format(alphabetList[x-1])) rotor1lab = Label(frame1, text='Rotor 1', padx=10, pady=5, background="white") rotor1lab.grid(row=0, column=0) rotor2lab = Label(frame1, text='Rotor 2', padx=10, pady=5, background="white") rotor2lab.grid(row=0, column=1) rotor3lab = Label(frame1, text='Rotor 3', padx=10, pady=5, background="white") rotor3lab.grid(row=0, column=2) #scales_choose_position var1 = DoubleVar() scale = Scale(frame1, from_=1, to=26, variable = var1, cursor='dot', showvalue=0, command=update1, length= 100, background="white") scale.grid(row=1, column=0, padx=60, pady=10) var2 = DoubleVar() scale = Scale(frame1, from_=1, to=26, variable = var2, cursor='dot', showvalue=0, command=update2, length= 100, background="white") scale.grid(row=1, column=1, padx=60, pady=10) var3 = DoubleVar() scale = Scale(frame1, from_=1, to=26, variable = var3, cursor='dot', showvalue=0, command=update3, length= 100, background="white") scale.grid(row=1, column=2, padx=60, pady=10) lab1 = Label(frame1, background="white") lab1.grid(row=2, column=0) lab2 = Label(frame1, background="white") lab2.grid(row=2, column=1) lab3 = Label(frame1, background="white") lab3.grid(row=2, column=2) #function_code def code(event=None): a = int(var1.get()) b = int(var2.get()) c = int(var3.get()) def rotationRotor(liste1): liste1.append(liste1[0]) del liste1[0] return liste1 def estValide(liste1): if liste1 == []: return False for elt in liste1: if alphabetList.count(elt.upper()) < 1: return False return True sortie = entryvar.get() var4str = var4.get() var4list = list(var4str) var5str = var5.get() var5list = list(var5str) var6str = var6.get() var6list = list(var6str) if var4list[5] == '1': rotor1 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H'] elif var4list[5] == '2': rotor1 = ['N','T','Z','P','S','F','B','O','K','M','W','R','C','J','D','I','V','L','A','E','Y','U','X','H','G','Q'] elif var4list[5] == '3': rotor1 = ['J','V','I','U','B','H','T','C','D','Y','A','K','E','Q','Z','P','O','S','G','X','N','R','M','W','F','L'] if var5list[5] == '1': rotor2 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H'] elif var5list[5] == '2': rotor2 = ['N','T','Z','P','S','F','B','O','K','M','W','R','C','J','D','I','V','L','A','E','Y','U','X','H','G','Q'] elif var5list[5] == '3': rotor2 = ['J','V','I','U','B','H','T','C','D','Y','A','K','E','Q','Z','P','O','S','G','X','N','R','M','W','F','L'] if var6list[5] == '1': rotor3 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H'] elif var6list[5] == '2': rotor3 = ['N','T','Z','P','S','F','B','O','K','M','W','R','C','J','D','I','V','L','A','E','Y','U','X','H','G','Q'] elif var6list[5] == '3': rotor3 = ['J','V','I','U','B','H','T','C','D','Y','A','K','E','Q','Z','P','O','S','G','X','N','R','M','W','F','L'] alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',' '] alphabetDict = {'G': 7, 'U': 21, 'T': 20, 'L': 12, 'Y': 25, 'Q': 17, 'V': 22, 'J': 10, 'O': 15, 'W': 23, 'N': 14, 'R': 18, 'Z': 26, 'S': 19, 'X': 24, 'A': 1, 'M': 13, 'E': 5, 'D': 4, 'I': 9, 'F': 6, 'P': 16, 'B': 2, 'H': 8, 'K': 11, 'C': 3} #rotor1 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H'] #rotor2 = ['N','T','Z','P','S','F','B','O','K','M','W','R','C','J','D','I','V','L','A','E','Y','U','X','H','G','Q'] #rotor3 = ['J','V','I','U','B','H','T','C','D','Y','A','K','E','Q','Z','P','O','S','G','X','N','R','M','W','F','L'] reflector = ['Y', 'R', 'U', 'H', 'Q', 'S', 'L', 'D', 'P', 'X', 'N', 'G', 'O', 'K', 'M', 'I', 'E', 'B', 'F', 'Z', 'C', 'W', 'V', 'J', 'A', 'T'] for loop1 in range(a): rotationRotor(rotor1) for loop2 in range(b): rotationRotor(rotor2) for loop3 in range(c): rotationRotor(rotor3) sortieListe = list(sortie) print(sortieListe) sortieListe = [x for x in sortieListe if x != " "] print(sortieListe) if not estValide(sortieListe): value = StringVar() value.set('Please enter only letters and spaces!') liste.insert(END, value.get()) liste.itemconfig(END, {'bg':'red'}) liste.see("end") elif (var4list[5] == var5list[5] == var6list[5]) or (var4list[5] == var5list[5]) or (var4list[5] == var6list[5]) or (var5list[5] == var6list[5]): value = StringVar() value.set('You can only use a rotor once!') liste.insert(END, value.get()) liste.itemconfig(END, {'bg':'red'}) liste.see("end") else: s = [] for i in range(0,len(sortieListe),1): a = alphabetDict[sortieListe[i].upper()] b = rotor1[a-1] c = alphabetDict[b] d = rotor2[c-1] e = alphabetDict[d] f = rotor3[e-1] g = alphabetDict[f] h = reflector[g-1] j = rotor3.index(h) k = alphabetList[j] l = rotor2.index(k) m = alphabetList[l] n = rotor1.index(m) o = alphabetList[n] s.append(o) if (i+1) % 1 == 0: rotationRotor(rotor1) if (i+1) % 26 == 0: rotationRotor(rotor2) if (i+1) % 676 == 0: rotationRotor(rotor3) value = StringVar() value.set(''.join(s)) liste.insert(END, value.get()) liste.see("end") #text_entry entryvar = StringVar() entry = Entry(frame, textvariable = entryvar, width=50, background="white") entry.focus_set() entry.bind("<Return>", code) entry.pack(padx=10, pady=10) #clear_listbox def clear(): liste.delete(0, END) #button_to_(de)code b1 = Button(frame, text="(de)code", width=10, command=code, background="white") b1.pack() #store_results f1 = Frame(frame) s1 = Scrollbar(f1) liste = Listbox(f1, height=5, width=50, borderwidth=0, background='white') s1.config(command = liste.yview) liste.config(yscrollcommand = s1.set) liste.pack(side = LEFT, fill = Y, padx=5, pady=5) s1.pack(side = RIGHT, fill = Y) f1.pack() #button_to_clear_listbox b2 = Button(frame, text="clear list", width=10, command=clear, background='white') b2.pack(padx=5, pady=5) #credits credits = Label(frame, text = "coded with <3 by omnitrogen",background="white") credits.pack(side = BOTTOM, padx=10, pady=10) #quit_button quitButton = Button(frame, text="quit", width=10, command=frame.quit, background='white') quitButton.pack(side = BOTTOM) canvas.create_window(0, 0, anchor=NW, window=frame) frame.update_idletasks() canvas.config(scrollregion=canvas.bbox("all")) mainloop()
omnitrogen/enigma
gui/enigma-gui-resizable-window.py
Python
mit
11,660
import pytest from pillowtalk import * # TODO: test when where returns [] or None or [None] # TODO: test update() (or autoupdate?) @pytest.fixture def folder_json(): return {'count' : 59, 'created_at' : '2013-10-01T20:07:18+00:00', 'description' : '', 'id': 'lib_pP6d50rJn1', 'modified_at' : '2017-01-20T21:57:55.991758+00:00', 'name' : 'Plasmids', 'owner' : 'ent_A7BlnCcJTU', 'permissions' : {'admin' : True, 'appendable': True, 'owner' : False, 'readable' : True, 'writable' : True}, 'sequences' : [ {'id': 'seq_Nv6wYspV', 'name': 'FAR1-mut-87aa-TP'}, {'id': 'seq_0FmHFzJe', 'name': 'pMODT4-pGAL1-attB1-GAVNY'}, {'id': 'seq_usn0K27s', 'name': 'pMODU6-pGALZ4-BleoMX'}, {'id': 'seq_Na2oNxzs', 'name': 'pMODU6-pGALZ4-FAR1-mut-87aa'}, {'id': 'seq_AyQ7ToIn', 'name': 'pBR322 (Sample Sequence)'}, {'id': 'seq_QuWMpfRK', 'name': 'pMODT4-pGAL1-attB1-GVNY'}, {'id': 'seq_K5hwGNwg', 'name': 'pMODU6-pGAL1-BleoMX'}, {'id': 'seq_2rKmILGU', 'name': 'pMODU6-pGAL1-NatMX'}, {'id': 'seq_5HcRWKi8', 'name': 'pMODU6-pGALZ4-P1G1-HygMX'}, {'id': 'seq_tMz0Xv3g', 'name': 'pMODU6-pGAL1-FAR1-L1-IAA17T2'}, {'id': 'seq_k0MuYdIM', 'name': 'pMODU6-pGAL1-IAA17T2-FAR1'}, {'id': 'seq_fkFjzKkb', 'name': 'v63_pGP8zGAL-STE5(-)RING-SNC2 C-term'}, {'id': 'seq_WQ0wqb9f', 'name': 'pMODU6-pGALZ4-iaaH'}, {'id': 'seq_hhI5TTbO', 'name': 'pMODU6-pGAL1-FAR1-IAA17T2'}, {'id': 'seq_beOWphBv', 'name': 'pMODKan-HO-pACT1-ZEV4'}, {'id': 'seq_QteKmJdS', 'name': 'pGPT4-pGAL1-GAVNY_mutated_library'}, {'id': 'seq_w2IZPFzd', 'name': 'pMODOK-pACT1-GAVNY'}, {'id': 'seq_AgQ1w9ak', 'name': 'pLAB2'}, {'id': 'seq_kKtPZ1Rs', 'name': 'pMODT4-pGAL1-P1G1-GAVNY'}, {'id': 'seq_4ccBmI1j', 'name': 'pGPU6-pGAL1-AFB2'}, {'id': 'seq_wHiaXdFM', 'name': 'pGPT4-pGAL1-G(m)AVNY'}, {'id': 'seq_QGfqobtP', 'name': 'pGPT4-pGAL1-AVNY'}, {'id': 'seq_VazadBJw', 'name': 'pGPT4-pGAL1-GAVNY'}, {'id': 'seq_Qc6f2Kii', 'name': 'pMOD4G-NLS_dCas9_VP64'}, {'id': 'seq_SGfG2YeB', 'name': 'pMODU6-pGALZ4-HygMX'}, {'id': 'seq_i0Yl6uzk', 'name': 'pMODH8-pGPD-TIR1_DM'}, {'id': 'seq_ri07UntS', 'name': 'pMODU6-pGPD-EYFP'}, {'id': 'seq_F4tEc0XU', 'name': 'pMODU6-pGALZ4-STE5(-)RING'}, {'id': 'seq_qihkmlW4', 'name': 'pMODU6-pGAL1-AlphaFactor'}, {'id': 'seq_2MFFshfl', 'name': 'pYMOD2Kmx_pGAL1-HYG_ZEV4-cassette'}, {'id': 'seq_bw3XWuZU', 'name': 'pMODT4-pGALZ4-AVNY'}, {'id': 'seq_D1iAdKMz', 'name': 'pGPL5G-pGAL1-URA3'}, {'id': 'seq_rzQGBzv2', 'name': 'pGP5G-ccdB'}, {'id': 'seq_9ph0SnJV', 'name': 'AmpR-T4-pGAL1-GAL4DBD-L1'}, {'id': 'seq_PKJNfuZA', 'name': 'pGPH8-pGAL1-GAVNY_v2'}, {'id': 'seq_m42PVReQ', 'name': 'pMODT4-pGALZ4-Z4AVNY'}, {'id': 'seq_5bmPzcKN', 'name': 'pMODU6-pGALZ4-NatMX'}, {'id': 'seq_mfMW58Dd', 'name': 'pGPL5G-pGALZ4-URA3'}, {'id': 'seq_l5VHTc8Z', 'name': 'pGPU6-pGAL1-TIR1_DM'}, {'id': 'seq_tFGIIL0C', 'name': 'pMODU6-pGAL1-FAR1'}, {'id': 'seq_y9xdtVx7', 'name': 'pMODKan-HO-pACT1GEV'}, {'id': 'seq_t77GYXRB', 'name': 'pGPT4-pGAL1-EGFP'}, {'id': 'seq_TWAJLtvz', 'name': 'pMODU6-pGAL1-P1G1-HygMX'}, {'id': 'seq_ztl4dnOW', 'name': 'pLAB1'}, {'id': 'seq_TsTM0B8q', 'name': 'pMOD4-pGAL1Z3(P3)-MF(AL'}, {'id': 'seq_UbsucV1t', 'name': 'pMODU6-pGAL1-HygMX'}, {'id': 'seq_7O7ThYSI', 'name': 'pMODU6-pGALZ4-Z4AVNY'}, {'id': 'seq_iGdjEEx4', 'name': 'pGPT4-pGAL1-P1G1-GEV'}, {'id': 'seq_2xGw2yCj', 'name': 'pGPH8-pGAL1-GAVNY'}, {'id': 'seq_okitCPyx', 'name': 'pGPT4-pGAL1-GAVNY(VP64)'}, {'id': 'seq_rwDoRd9Q', 'name': 'pMODU6-pGALZ4-FAR1'}, {'id': 'seq_f4GgnFdY', 'name': 'pGPT4-pGAL1-GAVNY_seq_verified'}, {'id': 'seq_5AXMlSvB', 'name': 'pYMOD2Kmx_pGAL1-HYG_pGAL1-iaah'}, {'id': 'seq_6VN5FDpP', 'name': 'pMODOK-pACT1-GAVN'}, {'id': 'seq_etTsAfD4', 'name': 'pGPU6-pGALZ4-eYFP'}, {'id': 'seq_IyZI9bEh', 'name': 'pMODU6-pGAL1-FAR1-L1-IAA17T1_opt'}, {'id': 'seq_7yXay7Ep', 'name': 'pGP8G-TIR1-Y'}, {'id': 'seq_GuqSGBXY', 'name': 'pGPT4-pGAL1-GAVNY(VP64) new design'}, {'id': 'seq_vA5dxrqd', 'name': 'pMODU6-pGALZ4-AlphaFactor'}], 'type' : 'ALL'} def test_folder(folder_json): class MyBase(PillowtalkBase): def find(self, *args, **kwargs): pass def where(self, *args, **kwargs): pass @add_schema class Folder(MyBase): items = {} FIELDS = ["id", "name"] RELATIONSHIPS = [ Many("sequences", "where Folder.id <> Sequence.folder") ] @add_schema class Sequence(MyBase): items = {} FIELDS = ["id", "name", "bases"] RELATIONSHIPS = [ One("folder", "find Sequence.folder <> Folder.id"), ] f = Folder.load(folder_json) assert len(f.sequences) > 1
jvrana/Pillowtalk
tests/test_with_larger_examples/test_sequence_example/test_examples.py
Python
mit
5,684
def topgeo ('topgeo'): """ Esta libreria funciona para realizar calculos topograficos. """
Alan-Jairo/topgeo
doc.py
Python
mit
103
__author__ = 'leif' from game_models import HighScore, UserProfile from ifind.common.utils import encode_string_to_url from django.contrib.auth.models import User from django.db.models import Max, Sum, Avg # ranking based on highest total score (top x players) # ranking of players based on level/xp # top players in each category # top schools ranked by average total_score of players # boys vs girls based on average total_score # and breakdown by age / boys vs girls # add in school, gender, age, into UserProfile # ranking based on the last 30 days / highest scores class GameLeaderboard(object): def __init__(self, top=20): self.top = top def get_leaderboard(self): pass def highscore_to_list(self, highscores): """ :param highscores: list of rows from HighScore :return: a formatted list rank, username, uid, category, cid, highest_score """ leaders = list() for i, hs in enumerate(highscores): entry = {'rank': i+1, 'username': hs.user.username, 'score': hs.highest_score} if hs.category: print hs.category entry['category'] = hs.category.name entry['category_url'] = encode_string_to_url(hs.category.name) print entry leaders.append(entry) return leaders class CatHighScoresLeaderboard(GameLeaderboard): def get_leaderboard(self): hs = HighScore.objects.all().order_by('-highest_score')[:self.top] return self.highscore_to_list(hs[:10]) def __str__(self): return 'Highest Category Scores' class HighScoresLeaderboard(GameLeaderboard): def get_leaderboard(self): highscores = HighScore.objects.values('user').annotate(highest_score=Sum('highest_score')).order_by('-highest_score')[:self.top] leaders = list() for i, hs in enumerate(highscores): username = User.objects.get(id=hs['user']) entry = {'rank': i+1, 'username': username, 'score': hs['highest_score']} leaders.append(entry) return leaders def __str__(self): return 'Highest Overall Scores' class SchoolLeaderboard(GameLeaderboard): def get_leaderboard(self): users = UserProfile.objects.all() schools = {} score_list=[] for user in users: if user.school != "": if user.school not in schools: user_score = self._get_user_score_sum(user) #list is [total_score_of_users,num_of_users] schools[user.school] = [user_score,1] else: schools[user.school][0] += self._get_user_score_sum(user) schools[user.school][1] += 1 for school, values in schools.iteritems(): dummy_user = User(username=school) score_list.append(HighScore(user=dummy_user, highest_score=values[0]/values[1] ,category=None )) score_list.sort(key=lambda x: x.highest_score, reverse=True) return self.highscore_to_list(score_list) def _get_user_score_sum(self, user): hs = HighScore.objects.filter(user=user.user) user_score = 0 for sc in hs: user_score += sc.highest_score return user_score def __str__(self): return 'School High Scores' class AgeLeaderboard(GameLeaderboard): def get_leaderboard(self): users = UserProfile.objects.all() age_groups = {} score_list=[] for user in users: if user.age is not None: if user.age not in age_groups: user_score = self._get_user_score_sum(user) #list is [total_score_of_users,num_of_users] age_groups[user.age] = [user_score,1] else: age_groups[user.age][0] += self._get_user_score_sum(user) age_groups[user.age][1] += 1 for age_group, values in age_groups.iteritems(): dummy_user = User(username=age_group) score_list.append(HighScore(user=dummy_user, highest_score=values[0]/values[1] ,category=None )) score_list.sort(key=lambda x: x.highest_score, reverse=True) return self.highscore_to_list(score_list) def _get_user_score_sum(self, user): hs = HighScore.objects.filter(user=user.user) user_score = 0 for sc in hs: user_score += sc.highest_score return user_score def __str__(self): return 'High Scores by age group' class GenderLeaderboard(GameLeaderboard): def get_leaderboard(self): users = UserProfile.objects.all() gender_groups = {} score_list=[] for user in users: if user.gender != '': if user.gender not in gender_groups: user_score = self._get_user_score_sum(user) #list is [total_score_of_users,num_of_users] gender_groups[user.gender] = [user_score,1] else: gender_groups[user.gender][0] += self._get_user_score_sum(user) gender_groups[user.gender][1] += 1 for gender_group, values in gender_groups.iteritems(): dummy_user = User(username=gender_group) score_list.append(HighScore(user=dummy_user, highest_score=values[0]/values[1] ,category=None )) score_list.sort(key=lambda x: x.highest_score, reverse=True) return self.highscore_to_list(score_list) def _get_user_score_sum(self, user): hs = HighScore.objects.filter(user=user.user) user_score = 0 for sc in hs: user_score += sc.highest_score return user_score def __str__(self): return 'High Scores by gender group'
leifos/pagefetch
pagefetch_project/pagefetch/game_leaderboards.py
Python
mit
5,894
"""Generate year files with news counts Usage: filter_news.py <directory> <output> <lang> Options: -h, --help """ from docopt import docopt from os import listdir from os.path import isfile, join, getsize import datetime from tqdm import * import pandas as pd def find_index(id, lis): for i in range(0, len(lis)): if id == lis[i]: return i return -1 if __name__ == "__main__": # Parse the command line args = docopt(__doc__) # Array with the week we are considering weeks = [42,43,44,45,46,47,48,49,50,51,52,1,23,4,5,6,7,8,9,10,11,12,13,14,15] # Final count dictionary news_count = {} # Get only the files in the directory which have a dimension greater than zero onlyfiles = [f for f in listdir(args["<directory>"]) if isfile(join(args["<directory>"], f)) and getsize(join(args["<directory>"], f))>0] if (len(onlyfiles) == 0): print("No file with size greater the zero found! Exiting.") exit(-1) # Loop over all the files and parse them for file in tqdm(onlyfiles): # Split the filename and get the day/month/year file_name = file.split("_") day = file_name[2] month = file_name[1] year = file_name[3] # Compute the week number week_number = datetime.date(int(year), int(month), int(day)).isocalendar()[1] # Read and parse the file only if it is in the week range we are considering if week_number in weeks: # Read the file file = pd.read_csv(args["<directory>"]+"/"+file) # Count how many news we have, considering only the italian ones total_news = file[file.lang_detected == args["<lang>"]].count() # If that year column is still empty, create it and set it to zero if news_count.get(year, []) == []: news_count[year] = [0 for x in range(0, len(weeks))] # Increment the week count news_count[year][find_index(week_number, weeks)] += int(total_news["lang_detected"]) # Generate the index for the future dataframe df_index = [] # Add a zero in front of number less than 10 for i in weeks: if i < 10: number = "0" + str(i) else: number = str(i) df_index.append(number) # Generate the dataframe final_df = pd.DataFrame(news_count) final_df.set_index([df_index]) # Print the dataframe to show the result print(final_df) # Save it to file final_df.to_csv(args["<output>"], index_label="Week")
geektoni/Influenza-Like-Illness-Predictor
data_analysis/filter_news.py
Python
mit
2,317
# test-case-name: twisted.names.test.test_dns # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for twisted.names.dns. """ from __future__ import division, absolute_import from io import BytesIO import struct from zope.interface.verify import verifyClass from twisted.python.failure import Failure from twisted.python.util import FancyEqMixin, FancyStrMixin from twisted.internet import address, task from twisted.internet.error import CannotListenError, ConnectionDone from twisted.trial import unittest from twisted.names import dns from twisted.test import proto_helpers from twisted.test.testutils import ComparisonTestsMixin RECORD_TYPES = [ dns.Record_NS, dns.Record_MD, dns.Record_MF, dns.Record_CNAME, dns.Record_MB, dns.Record_MG, dns.Record_MR, dns.Record_PTR, dns.Record_DNAME, dns.Record_A, dns.Record_SOA, dns.Record_NULL, dns.Record_WKS, dns.Record_SRV, dns.Record_AFSDB, dns.Record_RP, dns.Record_HINFO, dns.Record_MINFO, dns.Record_MX, dns.Record_TXT, dns.Record_AAAA, dns.Record_A6, dns.Record_NAPTR, dns.UnknownRecord, ] class Ord2ByteTests(unittest.TestCase): """ Tests for L{dns._ord2bytes}. """ def test_ord2byte(self): """ L{dns._ord2byte} accepts an integer and returns a byte string of length one with an ordinal value equal to the given integer. """ self.assertEqual(b'\x10', dns._ord2bytes(0x10)) class Str2TimeTests(unittest.TestCase): """ Tests for L{dns.str2name}. """ def test_nonString(self): """ When passed a non-string object, L{dns.str2name} returns it unmodified. """ time = object() self.assertIs(time, dns.str2time(time)) def test_seconds(self): """ Passed a string giving a number of seconds, L{dns.str2time} returns the number of seconds represented. For example, C{"10S"} represents C{10} seconds. """ self.assertEqual(10, dns.str2time("10S")) def test_minutes(self): """ Like C{test_seconds}, but for the C{"M"} suffix which multiplies the time value by C{60} (the number of seconds in a minute!). """ self.assertEqual(2 * 60, dns.str2time("2M")) def test_hours(self): """ Like C{test_seconds}, but for the C{"H"} suffix which multiplies the time value by C{3600}, the number of seconds in an hour. """ self.assertEqual(3 * 3600, dns.str2time("3H")) def test_days(self): """ Like L{test_seconds}, but for the C{"D"} suffix which multiplies the time value by C{86400}, the number of seconds in a day. """ self.assertEqual(4 * 86400, dns.str2time("4D")) def test_weeks(self): """ Like L{test_seconds}, but for the C{"W"} suffix which multiplies the time value by C{604800}, the number of seconds in a week. """ self.assertEqual(5 * 604800, dns.str2time("5W")) def test_years(self): """ Like L{test_seconds}, but for the C{"Y"} suffix which multiplies the time value by C{31536000}, the number of seconds in a year. """ self.assertEqual(6 * 31536000, dns.str2time("6Y")) def test_invalidPrefix(self): """ If a non-integer prefix is given, L{dns.str2time} raises L{ValueError}. """ self.assertRaises(ValueError, dns.str2time, "fooS") class NameTests(unittest.TestCase): """ Tests for L{Name}, the representation of a single domain name with support for encoding into and decoding from DNS message format. """ def test_nonStringName(self): """ When constructed with a name which is neither C{bytes} nor C{str}, L{Name} raises L{TypeError}. """ self.assertRaises(TypeError, dns.Name, 123) self.assertRaises(TypeError, dns.Name, object()) self.assertRaises(TypeError, dns.Name, []) def test_unicodeName(self): """ L{dns.Name} automatically encodes unicode domain name using C{idna} encoding. """ name = dns.Name(u'\u00e9chec.example.org') self.assertIsInstance(name.name, bytes) self.assertEqual(b'xn--chec-9oa.example.org', name.name) def test_decode(self): """ L{Name.decode} populates the L{Name} instance with name information read from the file-like object passed to it. """ n = dns.Name() n.decode(BytesIO(b"\x07example\x03com\x00")) self.assertEqual(n.name, b"example.com") def test_encode(self): """ L{Name.encode} encodes its name information and writes it to the file-like object passed to it. """ name = dns.Name(b"foo.example.com") stream = BytesIO() name.encode(stream) self.assertEqual(stream.getvalue(), b"\x03foo\x07example\x03com\x00") def test_encodeWithCompression(self): """ If a compression dictionary is passed to it, L{Name.encode} uses offset information from it to encode its name with references to existing labels in the stream instead of including another copy of them in the output. It also updates the compression dictionary with the location of the name it writes to the stream. """ name = dns.Name(b"foo.example.com") compression = {b"example.com": 0x17} # Some bytes already encoded into the stream for this message previous = b"some prefix to change .tell()" stream = BytesIO() stream.write(previous) # The position at which the encoded form of this new name will appear in # the stream. expected = len(previous) + dns.Message.headerSize name.encode(stream, compression) self.assertEqual( b"\x03foo\xc0\x17", stream.getvalue()[len(previous):]) self.assertEqual( {b"example.com": 0x17, b"foo.example.com": expected}, compression) def test_unknown(self): """ A resource record of unknown type and class is parsed into an L{UnknownRecord} instance with its data preserved, and an L{UnknownRecord} instance is serialized to a string equal to the one it was parsed from. """ wire = ( b'\x01\x00' # Message ID b'\x00' # answer bit, opCode nibble, auth bit, trunc bit, recursive # bit b'\x00' # recursion bit, empty bit, authenticData bit, # checkingDisabled bit, response code nibble b'\x00\x01' # number of queries b'\x00\x01' # number of answers b'\x00\x00' # number of authorities b'\x00\x01' # number of additionals # query b'\x03foo\x03bar\x00' # foo.bar b'\xde\xad' # type=0xdead b'\xbe\xef' # cls=0xbeef # 1st answer b'\xc0\x0c' # foo.bar - compressed b'\xde\xad' # type=0xdead b'\xbe\xef' # cls=0xbeef b'\x00\x00\x01\x01' # ttl=257 b'\x00\x08somedata' # some payload data # 1st additional b'\x03baz\x03ban\x00' # baz.ban b'\x00\x01' # type=A b'\x00\x01' # cls=IN b'\x00\x00\x01\x01' # ttl=257 b'\x00\x04' # len=4 b'\x01\x02\x03\x04' # 1.2.3.4 ) msg = dns.Message() msg.fromStr(wire) self.assertEqual(msg.queries, [ dns.Query(b'foo.bar', type=0xdead, cls=0xbeef), ]) self.assertEqual(msg.answers, [ dns.RRHeader(b'foo.bar', type=0xdead, cls=0xbeef, ttl=257, payload=dns.UnknownRecord(b'somedata', ttl=257)), ]) self.assertEqual(msg.additional, [ dns.RRHeader(b'baz.ban', type=dns.A, cls=dns.IN, ttl=257, payload=dns.Record_A('1.2.3.4', ttl=257)), ]) enc = msg.toStr() self.assertEqual(enc, wire) def test_decodeWithCompression(self): """ If the leading byte of an encoded label (in bytes read from a stream passed to L{Name.decode}) has its two high bits set, the next byte is treated as a pointer to another label in the stream and that label is included in the name being decoded. """ # Slightly modified version of the example from RFC 1035, section 4.1.4. stream = BytesIO( b"x" * 20 + b"\x01f\x03isi\x04arpa\x00" b"\x03foo\xc0\x14" b"\x03bar\xc0\x20") stream.seek(20) name = dns.Name() name.decode(stream) # Verify we found the first name in the stream and that the stream # position is left at the first byte after the decoded name. self.assertEqual(b"f.isi.arpa", name.name) self.assertEqual(32, stream.tell()) # Get the second name from the stream and make the same assertions. name.decode(stream) self.assertEqual(name.name, b"foo.f.isi.arpa") self.assertEqual(38, stream.tell()) # Get the third and final name name.decode(stream) self.assertEqual(name.name, b"bar.foo.f.isi.arpa") self.assertEqual(44, stream.tell()) def test_rejectCompressionLoop(self): """ L{Name.decode} raises L{ValueError} if the stream passed to it includes a compression pointer which forms a loop, causing the name to be undecodable. """ name = dns.Name() stream = BytesIO(b"\xc0\x00") self.assertRaises(ValueError, name.decode, stream) def test_equality(self): """ L{Name} instances are equal as long as they have the same value for L{Name.name}, regardless of the case. """ name1 = dns.Name(b"foo.bar") name2 = dns.Name(b"foo.bar") self.assertEqual(name1, name2) name3 = dns.Name(b"fOO.bar") self.assertEqual(name1, name3) def test_inequality(self): """ L{Name} instances are not equal as long as they have different L{Name.name} attributes. """ name1 = dns.Name(b"foo.bar") name2 = dns.Name(b"bar.foo") self.assertNotEqual(name1, name2) class RoundtripDNSTests(unittest.TestCase): """ Encoding and then decoding various objects. """ names = [b"example.org", b"go-away.fish.tv", b"23strikesback.net"] def test_name(self): for n in self.names: # encode the name f = BytesIO() dns.Name(n).encode(f) # decode the name f.seek(0, 0) result = dns.Name() result.decode(f) self.assertEqual(result.name, n) def test_query(self): """ L{dns.Query.encode} returns a byte string representing the fields of the query which can be decoded into a new L{dns.Query} instance using L{dns.Query.decode}. """ for n in self.names: for dnstype in range(1, 17): for dnscls in range(1, 5): # encode the query f = BytesIO() dns.Query(n, dnstype, dnscls).encode(f) # decode the result f.seek(0, 0) result = dns.Query() result.decode(f) self.assertEqual(result.name.name, n) self.assertEqual(result.type, dnstype) self.assertEqual(result.cls, dnscls) def test_resourceRecordHeader(self): """ L{dns.RRHeader.encode} encodes the record header's information and writes it to the file-like object passed to it and L{dns.RRHeader.decode} reads from a file-like object to re-construct a L{dns.RRHeader} instance. """ # encode the RR f = BytesIO() dns.RRHeader(b"test.org", 3, 4, 17).encode(f) # decode the result f.seek(0, 0) result = dns.RRHeader() result.decode(f) self.assertEqual(result.name, dns.Name(b"test.org")) self.assertEqual(result.type, 3) self.assertEqual(result.cls, 4) self.assertEqual(result.ttl, 17) def test_resources(self): """ L{dns.SimpleRecord.encode} encodes the record's name information and writes it to the file-like object passed to it and L{dns.SimpleRecord.decode} reads from a file-like object to re-construct a L{dns.SimpleRecord} instance. """ names = ( b"this.are.test.name", b"will.compress.will.this.will.name.will.hopefully", b"test.CASE.preSErVatIOn.YeAH", b"a.s.h.o.r.t.c.a.s.e.t.o.t.e.s.t", b"singleton" ) for s in names: f = BytesIO() dns.SimpleRecord(s).encode(f) f.seek(0, 0) result = dns.SimpleRecord() result.decode(f) self.assertEqual(result.name, dns.Name(s)) def test_hashable(self): """ Instances of all record types are hashable. """ for k in RECORD_TYPES: k1, k2 = k(), k() hk1 = hash(k1) hk2 = hash(k2) self.assertEqual(hk1, hk2, "%s != %s (for %s)" % (hk1,hk2,k)) def test_Charstr(self): """ Test L{dns.Charstr} encode and decode. """ for n in self.names: # encode the name f = BytesIO() dns.Charstr(n).encode(f) # decode the name f.seek(0, 0) result = dns.Charstr() result.decode(f) self.assertEqual(result.string, n) def _recordRoundtripTest(self, record): """ Assert that encoding C{record} and then decoding the resulting bytes creates a record which compares equal to C{record}. """ stream = BytesIO() record.encode(stream) length = stream.tell() stream.seek(0, 0) replica = record.__class__() replica.decode(stream, length) self.assertEqual(record, replica) def test_SOA(self): """ The byte stream written by L{dns.Record_SOA.encode} can be used by L{dns.Record_SOA.decode} to reconstruct the state of the original L{dns.Record_SOA} instance. """ self._recordRoundtripTest( dns.Record_SOA( mname=b'foo', rname=b'bar', serial=12, refresh=34, retry=56, expire=78, minimum=90)) def test_A(self): """ The byte stream written by L{dns.Record_A.encode} can be used by L{dns.Record_A.decode} to reconstruct the state of the original L{dns.Record_A} instance. """ self._recordRoundtripTest(dns.Record_A('1.2.3.4')) def test_NULL(self): """ The byte stream written by L{dns.Record_NULL.encode} can be used by L{dns.Record_NULL.decode} to reconstruct the state of the original L{dns.Record_NULL} instance. """ self._recordRoundtripTest(dns.Record_NULL(b'foo bar')) def test_WKS(self): """ The byte stream written by L{dns.Record_WKS.encode} can be used by L{dns.Record_WKS.decode} to reconstruct the state of the original L{dns.Record_WKS} instance. """ self._recordRoundtripTest(dns.Record_WKS('1.2.3.4', 3, b'xyz')) def test_AAAA(self): """ The byte stream written by L{dns.Record_AAAA.encode} can be used by L{dns.Record_AAAA.decode} to reconstruct the state of the original L{dns.Record_AAAA} instance. """ self._recordRoundtripTest(dns.Record_AAAA('::1')) def test_A6(self): """ The byte stream written by L{dns.Record_A6.encode} can be used by L{dns.Record_A6.decode} to reconstruct the state of the original L{dns.Record_A6} instance. """ self._recordRoundtripTest(dns.Record_A6(8, '::1:2', b'foo')) def test_SRV(self): """ The byte stream written by L{dns.Record_SRV.encode} can be used by L{dns.Record_SRV.decode} to reconstruct the state of the original L{dns.Record_SRV} instance. """ self._recordRoundtripTest(dns.Record_SRV( priority=1, weight=2, port=3, target=b'example.com')) def test_NAPTR(self): """ Test L{dns.Record_NAPTR} encode and decode. """ naptrs = [ (100, 10, b"u", b"sip+E2U", b"!^.*$!sip:information@domain.tld!", b""), (100, 50, b"s", b"http+I2L+I2C+I2R", b"", b"_http._tcp.gatech.edu")] for (order, preference, flags, service, regexp, replacement) in naptrs: rin = dns.Record_NAPTR(order, preference, flags, service, regexp, replacement) e = BytesIO() rin.encode(e) e.seek(0, 0) rout = dns.Record_NAPTR() rout.decode(e) self.assertEqual(rin.order, rout.order) self.assertEqual(rin.preference, rout.preference) self.assertEqual(rin.flags, rout.flags) self.assertEqual(rin.service, rout.service) self.assertEqual(rin.regexp, rout.regexp) self.assertEqual(rin.replacement.name, rout.replacement.name) self.assertEqual(rin.ttl, rout.ttl) def test_AFSDB(self): """ The byte stream written by L{dns.Record_AFSDB.encode} can be used by L{dns.Record_AFSDB.decode} to reconstruct the state of the original L{dns.Record_AFSDB} instance. """ self._recordRoundtripTest(dns.Record_AFSDB( subtype=3, hostname=b'example.com')) def test_RP(self): """ The byte stream written by L{dns.Record_RP.encode} can be used by L{dns.Record_RP.decode} to reconstruct the state of the original L{dns.Record_RP} instance. """ self._recordRoundtripTest(dns.Record_RP( mbox=b'alice.example.com', txt=b'example.com')) def test_HINFO(self): """ The byte stream written by L{dns.Record_HINFO.encode} can be used by L{dns.Record_HINFO.decode} to reconstruct the state of the original L{dns.Record_HINFO} instance. """ self._recordRoundtripTest(dns.Record_HINFO(cpu=b'fast', os=b'great')) def test_MINFO(self): """ The byte stream written by L{dns.Record_MINFO.encode} can be used by L{dns.Record_MINFO.decode} to reconstruct the state of the original L{dns.Record_MINFO} instance. """ self._recordRoundtripTest(dns.Record_MINFO( rmailbx=b'foo', emailbx=b'bar')) def test_MX(self): """ The byte stream written by L{dns.Record_MX.encode} can be used by L{dns.Record_MX.decode} to reconstruct the state of the original L{dns.Record_MX} instance. """ self._recordRoundtripTest(dns.Record_MX( preference=1, name=b'example.com')) def test_TXT(self): """ The byte stream written by L{dns.Record_TXT.encode} can be used by L{dns.Record_TXT.decode} to reconstruct the state of the original L{dns.Record_TXT} instance. """ self._recordRoundtripTest(dns.Record_TXT(b'foo', b'bar')) MESSAGE_AUTHENTIC_DATA_BYTES = ( b'\x00\x00' # ID b'\x00' # b'\x20' # RA, Z, AD=1, CD, RCODE b'\x00\x00' # Query count b'\x00\x00' # Answer count b'\x00\x00' # Authority count b'\x00\x00' # Additional count ) MESSAGE_CHECKING_DISABLED_BYTES = ( b'\x00\x00' # ID b'\x00' # b'\x10' # RA, Z, AD, CD=1, RCODE b'\x00\x00' # Query count b'\x00\x00' # Answer count b'\x00\x00' # Authority count b'\x00\x00' # Additional count ) class MessageTests(unittest.SynchronousTestCase): """ Tests for L{twisted.names.dns.Message}. """ def test_authenticDataDefault(self): """ L{dns.Message.authenticData} has default value 0. """ self.assertEqual(dns.Message().authenticData, 0) def test_authenticDataOverride(self): """ L{dns.Message.__init__} accepts a C{authenticData} argument which is assigned to L{dns.Message.authenticData}. """ self.assertEqual(dns.Message(authenticData=1).authenticData, 1) def test_authenticDataEncode(self): """ L{dns.Message.toStr} encodes L{dns.Message.authenticData} into byte4 of the byte string. """ self.assertEqual( dns.Message(authenticData=1).toStr(), MESSAGE_AUTHENTIC_DATA_BYTES ) def test_authenticDataDecode(self): """ L{dns.Message.fromStr} decodes byte4 and assigns bit3 to L{dns.Message.authenticData}. """ m = dns.Message() m.fromStr(MESSAGE_AUTHENTIC_DATA_BYTES) self.assertEqual(m.authenticData, 1) def test_checkingDisabledDefault(self): """ L{dns.Message.checkingDisabled} has default value 0. """ self.assertEqual(dns.Message().checkingDisabled, 0) def test_checkingDisabledOverride(self): """ L{dns.Message.__init__} accepts a C{checkingDisabled} argument which is assigned to L{dns.Message.checkingDisabled}. """ self.assertEqual( dns.Message(checkingDisabled=1).checkingDisabled, 1) def test_checkingDisabledEncode(self): """ L{dns.Message.toStr} encodes L{dns.Message.checkingDisabled} into byte4 of the byte string. """ self.assertEqual( dns.Message(checkingDisabled=1).toStr(), MESSAGE_CHECKING_DISABLED_BYTES ) def test_checkingDisabledDecode(self): """ L{dns.Message.fromStr} decodes byte4 and assigns bit4 to L{dns.Message.checkingDisabled}. """ m = dns.Message() m.fromStr(MESSAGE_CHECKING_DISABLED_BYTES) self.assertEqual(m.checkingDisabled, 1) def test_reprDefaults(self): """ L{dns.Message.__repr__} omits field values and sections which are identical to their defaults. The id field value is always shown. """ self.assertEqual( '<Message id=0>', repr(dns.Message()) ) def test_reprFlagsIfSet(self): """ L{dns.Message.__repr__} displays flags if they are L{True}. """ m = dns.Message(answer=True, auth=True, trunc=True, recDes=True, recAv=True, authenticData=True, checkingDisabled=True) self.assertEqual( '<Message ' 'id=0 ' 'flags=answer,auth,trunc,recDes,recAv,authenticData,' 'checkingDisabled' '>', repr(m), ) def test_reprNonDefautFields(self): """ L{dns.Message.__repr__} displays field values if they differ from their defaults. """ m = dns.Message(id=10, opCode=20, rCode=30, maxSize=40) self.assertEqual( '<Message ' 'id=10 ' 'opCode=20 ' 'rCode=30 ' 'maxSize=40' '>', repr(m), ) def test_reprNonDefaultSections(self): """ L{dns.Message.__repr__} displays sections which differ from their defaults. """ m = dns.Message() m.queries = [1, 2, 3] m.answers = [4, 5, 6] m.authority = [7, 8, 9] m.additional = [10, 11, 12] self.assertEqual( '<Message ' 'id=0 ' 'queries=[1, 2, 3] ' 'answers=[4, 5, 6] ' 'authority=[7, 8, 9] ' 'additional=[10, 11, 12]' '>', repr(m), ) def test_emptyMessage(self): """ Test that a message which has been truncated causes an EOFError to be raised when it is parsed. """ msg = dns.Message() self.assertRaises(EOFError, msg.fromStr, b'') def test_emptyQuery(self): """ Test that bytes representing an empty query message can be decoded as such. """ msg = dns.Message() msg.fromStr( b'\x01\x00' # Message ID b'\x00' # answer bit, opCode nibble, auth bit, trunc bit, recursive bit b'\x00' # recursion bit, empty bit, authenticData bit, # checkingDisabled bit, response code nibble b'\x00\x00' # number of queries b'\x00\x00' # number of answers b'\x00\x00' # number of authorities b'\x00\x00' # number of additionals ) self.assertEqual(msg.id, 256) self.assertFalse( msg.answer, "Message was not supposed to be an answer.") self.assertEqual(msg.opCode, dns.OP_QUERY) self.assertFalse( msg.auth, "Message was not supposed to be authoritative.") self.assertFalse( msg.trunc, "Message was not supposed to be truncated.") self.assertEqual(msg.queries, []) self.assertEqual(msg.answers, []) self.assertEqual(msg.authority, []) self.assertEqual(msg.additional, []) def test_NULL(self): """ A I{NULL} record with an arbitrary payload can be encoded and decoded as part of a L{dns.Message}. """ bytes = b''.join([dns._ord2bytes(i) for i in range(256)]) rec = dns.Record_NULL(bytes) rr = dns.RRHeader(b'testname', dns.NULL, payload=rec) msg1 = dns.Message() msg1.answers.append(rr) s = BytesIO() msg1.encode(s) s.seek(0, 0) msg2 = dns.Message() msg2.decode(s) self.assertIsInstance(msg2.answers[0].payload, dns.Record_NULL) self.assertEqual(msg2.answers[0].payload.payload, bytes) def test_lookupRecordTypeDefault(self): """ L{Message.lookupRecordType} returns C{dns.UnknownRecord} if it is called with an integer which doesn't correspond to any known record type. """ # 65280 is the first value in the range reserved for private # use, so it shouldn't ever conflict with an officially # allocated value. self.assertIs(dns.Message().lookupRecordType(65280), dns.UnknownRecord) def test_nonAuthoritativeMessage(self): """ The L{RRHeader} instances created by L{Message} from a non-authoritative message are marked as not authoritative. """ buf = BytesIO() answer = dns.RRHeader(payload=dns.Record_A('1.2.3.4', ttl=0)) answer.encode(buf) message = dns.Message() message.fromStr( b'\x01\x00' # Message ID # answer bit, opCode nibble, auth bit, trunc bit, recursive bit b'\x00' # recursion bit, empty bit, authenticData bit, # checkingDisabled bit, response code nibble b'\x00' b'\x00\x00' # number of queries b'\x00\x01' # number of answers b'\x00\x00' # number of authorities b'\x00\x00' # number of additionals + buf.getvalue() ) self.assertEqual(message.answers, [answer]) self.assertFalse(message.answers[0].auth) def test_authoritativeMessage(self): """ The L{RRHeader} instances created by L{Message} from an authoritative message are marked as authoritative. """ buf = BytesIO() answer = dns.RRHeader(payload=dns.Record_A('1.2.3.4', ttl=0)) answer.encode(buf) message = dns.Message() message.fromStr( b'\x01\x00' # Message ID # answer bit, opCode nibble, auth bit, trunc bit, recursive bit b'\x04' # recursion bit, empty bit, authenticData bit, # checkingDisabled bit, response code nibble b'\x00' b'\x00\x00' # number of queries b'\x00\x01' # number of answers b'\x00\x00' # number of authorities b'\x00\x00' # number of additionals + buf.getvalue() ) answer.auth = True self.assertEqual(message.answers, [answer]) self.assertTrue(message.answers[0].auth) class MessageComparisonTests(ComparisonTestsMixin, unittest.SynchronousTestCase): """ Tests for the rich comparison of L{dns.Message} instances. """ def messageFactory(self, *args, **kwargs): """ Create a L{dns.Message}. The L{dns.Message} constructor doesn't accept C{queries}, C{answers}, C{authority}, C{additional} arguments, so we extract them from the kwargs supplied to this factory function and assign them to the message. @param args: Positional arguments. @param kwargs: Keyword arguments. @return: A L{dns.Message} instance. """ queries = kwargs.pop('queries', []) answers = kwargs.pop('answers', []) authority = kwargs.pop('authority', []) additional = kwargs.pop('additional', []) m = dns.Message(**kwargs) if queries: m.queries = queries if answers: m.answers = answers if authority: m.authority = authority if additional: m.additional = additional return m def test_id(self): """ Two L{dns.Message} instances compare equal if they have the same id value. """ self.assertNormalEqualityImplementation( self.messageFactory(id=10), self.messageFactory(id=10), self.messageFactory(id=20), ) def test_answer(self): """ Two L{dns.Message} instances compare equal if they have the same answer flag. """ self.assertNormalEqualityImplementation( self.messageFactory(answer=1), self.messageFactory(answer=1), self.messageFactory(answer=0), ) def test_opCode(self): """ Two L{dns.Message} instances compare equal if they have the same opCode value. """ self.assertNormalEqualityImplementation( self.messageFactory(opCode=10), self.messageFactory(opCode=10), self.messageFactory(opCode=20), ) def test_recDes(self): """ Two L{dns.Message} instances compare equal if they have the same recDes flag. """ self.assertNormalEqualityImplementation( self.messageFactory(recDes=1), self.messageFactory(recDes=1), self.messageFactory(recDes=0), ) def test_recAv(self): """ Two L{dns.Message} instances compare equal if they have the same recAv flag. """ self.assertNormalEqualityImplementation( self.messageFactory(recAv=1), self.messageFactory(recAv=1), self.messageFactory(recAv=0), ) def test_auth(self): """ Two L{dns.Message} instances compare equal if they have the same auth flag. """ self.assertNormalEqualityImplementation( self.messageFactory(auth=1), self.messageFactory(auth=1), self.messageFactory(auth=0), ) def test_rCode(self): """ Two L{dns.Message} instances compare equal if they have the same rCode value. """ self.assertNormalEqualityImplementation( self.messageFactory(rCode=10), self.messageFactory(rCode=10), self.messageFactory(rCode=20), ) def test_trunc(self): """ Two L{dns.Message} instances compare equal if they have the same trunc flag. """ self.assertNormalEqualityImplementation( self.messageFactory(trunc=1), self.messageFactory(trunc=1), self.messageFactory(trunc=0), ) def test_maxSize(self): """ Two L{dns.Message} instances compare equal if they have the same maxSize value. """ self.assertNormalEqualityImplementation( self.messageFactory(maxSize=10), self.messageFactory(maxSize=10), self.messageFactory(maxSize=20), ) def test_authenticData(self): """ Two L{dns.Message} instances compare equal if they have the same authenticData flag. """ self.assertNormalEqualityImplementation( self.messageFactory(authenticData=1), self.messageFactory(authenticData=1), self.messageFactory(authenticData=0), ) def test_checkingDisabled(self): """ Two L{dns.Message} instances compare equal if they have the same checkingDisabled flag. """ self.assertNormalEqualityImplementation( self.messageFactory(checkingDisabled=1), self.messageFactory(checkingDisabled=1), self.messageFactory(checkingDisabled=0), ) def test_queries(self): """ Two L{dns.Message} instances compare equal if they have the same queries. """ self.assertNormalEqualityImplementation( self.messageFactory(queries=[dns.Query(b'example.com')]), self.messageFactory(queries=[dns.Query(b'example.com')]), self.messageFactory(queries=[dns.Query(b'example.org')]), ) def test_answers(self): """ Two L{dns.Message} instances compare equal if they have the same answers. """ self.assertNormalEqualityImplementation( self.messageFactory(answers=[dns.RRHeader( b'example.com', payload=dns.Record_A('1.2.3.4'))]), self.messageFactory(answers=[dns.RRHeader( b'example.com', payload=dns.Record_A('1.2.3.4'))]), self.messageFactory(answers=[dns.RRHeader( b'example.org', payload=dns.Record_A('4.3.2.1'))]), ) def test_authority(self): """ Two L{dns.Message} instances compare equal if they have the same authority records. """ self.assertNormalEqualityImplementation( self.messageFactory(authority=[dns.RRHeader( b'example.com', type=dns.SOA, payload=dns.Record_SOA())]), self.messageFactory(authority=[dns.RRHeader( b'example.com', type=dns.SOA, payload=dns.Record_SOA())]), self.messageFactory(authority=[dns.RRHeader( b'example.org', type=dns.SOA, payload=dns.Record_SOA())]), ) def test_additional(self): """ Two L{dns.Message} instances compare equal if they have the same additional records. """ self.assertNormalEqualityImplementation( self.messageFactory(additional=[dns.RRHeader( b'example.com', payload=dns.Record_A('1.2.3.4'))]), self.messageFactory(additional=[dns.RRHeader( b'example.com', payload=dns.Record_A('1.2.3.4'))]), self.messageFactory(additional=[dns.RRHeader( b'example.org', payload=dns.Record_A('1.2.3.4'))]), ) class TestController(object): """ Pretend to be a DNS query processor for a DNSDatagramProtocol. @ivar messages: the list of received messages. @type messages: C{list} of (msg, protocol, address) """ def __init__(self): """ Initialize the controller: create a list of messages. """ self.messages = [] def messageReceived(self, msg, proto, addr=None): """ Save the message so that it can be checked during the tests. """ self.messages.append((msg, proto, addr)) class DatagramProtocolTests(unittest.TestCase): """ Test various aspects of L{dns.DNSDatagramProtocol}. """ def setUp(self): """ Create a L{dns.DNSDatagramProtocol} with a deterministic clock. """ self.clock = task.Clock() self.controller = TestController() self.proto = dns.DNSDatagramProtocol(self.controller) transport = proto_helpers.FakeDatagramTransport() self.proto.makeConnection(transport) self.proto.callLater = self.clock.callLater def test_truncatedPacket(self): """ Test that when a short datagram is received, datagramReceived does not raise an exception while processing it. """ self.proto.datagramReceived( b'', address.IPv4Address('UDP', '127.0.0.1', 12345)) self.assertEqual(self.controller.messages, []) def test_simpleQuery(self): """ Test content received after a query. """ d = self.proto.query(('127.0.0.1', 21345), [dns.Query(b'foo')]) self.assertEqual(len(self.proto.liveMessages.keys()), 1) m = dns.Message() m.id = next(iter(self.proto.liveMessages.keys())) m.answers = [dns.RRHeader(payload=dns.Record_A(address='1.2.3.4'))] def cb(result): self.assertEqual(result.answers[0].payload.dottedQuad(), '1.2.3.4') d.addCallback(cb) self.proto.datagramReceived(m.toStr(), ('127.0.0.1', 21345)) return d def test_queryTimeout(self): """ Test that query timeouts after some seconds. """ d = self.proto.query(('127.0.0.1', 21345), [dns.Query(b'foo')]) self.assertEqual(len(self.proto.liveMessages), 1) self.clock.advance(10) self.assertFailure(d, dns.DNSQueryTimeoutError) self.assertEqual(len(self.proto.liveMessages), 0) return d def test_writeError(self): """ Exceptions raised by the transport's write method should be turned into C{Failure}s passed to errbacks of the C{Deferred} returned by L{DNSDatagramProtocol.query}. """ def writeError(message, addr): raise RuntimeError("bar") self.proto.transport.write = writeError d = self.proto.query(('127.0.0.1', 21345), [dns.Query(b'foo')]) return self.assertFailure(d, RuntimeError) def test_listenError(self): """ Exception L{CannotListenError} raised by C{listenUDP} should be turned into a C{Failure} passed to errback of the C{Deferred} returned by L{DNSDatagramProtocol.query}. """ def startListeningError(): raise CannotListenError(None, None, None) self.proto.startListening = startListeningError # Clean up transport so that the protocol calls startListening again self.proto.transport = None d = self.proto.query(('127.0.0.1', 21345), [dns.Query(b'foo')]) return self.assertFailure(d, CannotListenError) def test_receiveMessageNotInLiveMessages(self): """ When receiving a message whose id is not in L{DNSDatagramProtocol.liveMessages} or L{DNSDatagramProtocol.resends}, the message will be received by L{DNSDatagramProtocol.controller}. """ message = dns.Message() message.id = 1 message.answers = [dns.RRHeader( payload=dns.Record_A(address='1.2.3.4'))] self.proto.datagramReceived(message.toStr(), ('127.0.0.1', 21345)) self.assertEqual(self.controller.messages[-1][0].toStr(), message.toStr()) class TestTCPController(TestController): """ Pretend to be a DNS query processor for a DNSProtocol. @ivar connections: A list of L{DNSProtocol} instances which have notified this controller that they are connected and have not yet notified it that their connection has been lost. """ def __init__(self): TestController.__init__(self) self.connections = [] def connectionMade(self, proto): self.connections.append(proto) def connectionLost(self, proto): self.connections.remove(proto) class DNSProtocolTests(unittest.TestCase): """ Test various aspects of L{dns.DNSProtocol}. """ def setUp(self): """ Create a L{dns.DNSProtocol} with a deterministic clock. """ self.clock = task.Clock() self.controller = TestTCPController() self.proto = dns.DNSProtocol(self.controller) self.proto.makeConnection(proto_helpers.StringTransport()) self.proto.callLater = self.clock.callLater def test_connectionTracking(self): """ L{dns.DNSProtocol} calls its controller's C{connectionMade} method with itself when it is connected to a transport and its controller's C{connectionLost} method when it is disconnected. """ self.assertEqual(self.controller.connections, [self.proto]) self.proto.connectionLost( Failure(ConnectionDone("Fake Connection Done"))) self.assertEqual(self.controller.connections, []) def test_queryTimeout(self): """ Test that query timeouts after some seconds. """ d = self.proto.query([dns.Query(b'foo')]) self.assertEqual(len(self.proto.liveMessages), 1) self.clock.advance(60) self.assertFailure(d, dns.DNSQueryTimeoutError) self.assertEqual(len(self.proto.liveMessages), 0) return d def test_simpleQuery(self): """ Test content received after a query. """ d = self.proto.query([dns.Query(b'foo')]) self.assertEqual(len(self.proto.liveMessages.keys()), 1) m = dns.Message() m.id = next(iter(self.proto.liveMessages.keys())) m.answers = [dns.RRHeader(payload=dns.Record_A(address='1.2.3.4'))] def cb(result): self.assertEqual(result.answers[0].payload.dottedQuad(), '1.2.3.4') d.addCallback(cb) s = m.toStr() s = struct.pack('!H', len(s)) + s self.proto.dataReceived(s) return d def test_writeError(self): """ Exceptions raised by the transport's write method should be turned into C{Failure}s passed to errbacks of the C{Deferred} returned by L{DNSProtocol.query}. """ def writeError(message): raise RuntimeError("bar") self.proto.transport.write = writeError d = self.proto.query([dns.Query(b'foo')]) return self.assertFailure(d, RuntimeError) def test_receiveMessageNotInLiveMessages(self): """ When receiving a message whose id is not in L{DNSProtocol.liveMessages} the message will be received by L{DNSProtocol.controller}. """ message = dns.Message() message.id = 1 message.answers = [dns.RRHeader( payload=dns.Record_A(address='1.2.3.4'))] string = message.toStr() string = struct.pack('!H', len(string)) + string self.proto.dataReceived(string) self.assertEqual(self.controller.messages[-1][0].toStr(), message.toStr()) class ReprTests(unittest.TestCase): """ Tests for the C{__repr__} implementation of record classes. """ def test_ns(self): """ The repr of a L{dns.Record_NS} instance includes the name of the nameserver and the TTL of the record. """ self.assertEqual( repr(dns.Record_NS(b'example.com', 4321)), "<NS name=example.com ttl=4321>") def test_md(self): """ The repr of a L{dns.Record_MD} instance includes the name of the mail destination and the TTL of the record. """ self.assertEqual( repr(dns.Record_MD(b'example.com', 4321)), "<MD name=example.com ttl=4321>") def test_mf(self): """ The repr of a L{dns.Record_MF} instance includes the name of the mail forwarder and the TTL of the record. """ self.assertEqual( repr(dns.Record_MF(b'example.com', 4321)), "<MF name=example.com ttl=4321>") def test_cname(self): """ The repr of a L{dns.Record_CNAME} instance includes the name of the mail forwarder and the TTL of the record. """ self.assertEqual( repr(dns.Record_CNAME(b'example.com', 4321)), "<CNAME name=example.com ttl=4321>") def test_mb(self): """ The repr of a L{dns.Record_MB} instance includes the name of the mailbox and the TTL of the record. """ self.assertEqual( repr(dns.Record_MB(b'example.com', 4321)), "<MB name=example.com ttl=4321>") def test_mg(self): """ The repr of a L{dns.Record_MG} instance includes the name of the mail group member and the TTL of the record. """ self.assertEqual( repr(dns.Record_MG(b'example.com', 4321)), "<MG name=example.com ttl=4321>") def test_mr(self): """ The repr of a L{dns.Record_MR} instance includes the name of the mail rename domain and the TTL of the record. """ self.assertEqual( repr(dns.Record_MR(b'example.com', 4321)), "<MR name=example.com ttl=4321>") def test_ptr(self): """ The repr of a L{dns.Record_PTR} instance includes the name of the pointer and the TTL of the record. """ self.assertEqual( repr(dns.Record_PTR(b'example.com', 4321)), "<PTR name=example.com ttl=4321>") def test_dname(self): """ The repr of a L{dns.Record_DNAME} instance includes the name of the non-terminal DNS name redirection and the TTL of the record. """ self.assertEqual( repr(dns.Record_DNAME(b'example.com', 4321)), "<DNAME name=example.com ttl=4321>") def test_a(self): """ The repr of a L{dns.Record_A} instance includes the dotted-quad string representation of the address it is for and the TTL of the record. """ self.assertEqual( repr(dns.Record_A('1.2.3.4', 567)), '<A address=1.2.3.4 ttl=567>') def test_soa(self): """ The repr of a L{dns.Record_SOA} instance includes all of the authority fields. """ self.assertEqual( repr(dns.Record_SOA(mname=b'mName', rname=b'rName', serial=123, refresh=456, retry=789, expire=10, minimum=11, ttl=12)), "<SOA mname=mName rname=rName serial=123 refresh=456 " "retry=789 expire=10 minimum=11 ttl=12>") def test_null(self): """ The repr of a L{dns.Record_NULL} instance includes the repr of its payload and the TTL of the record. """ self.assertEqual( repr(dns.Record_NULL(b'abcd', 123)), "<NULL payload='abcd' ttl=123>") def test_wks(self): """ The repr of a L{dns.Record_WKS} instance includes the dotted-quad string representation of the address it is for, the IP protocol number it is for, and the TTL of the record. """ self.assertEqual( repr(dns.Record_WKS('2.3.4.5', 7, ttl=8)), "<WKS address=2.3.4.5 protocol=7 ttl=8>") def test_aaaa(self): """ The repr of a L{dns.Record_AAAA} instance includes the colon-separated hex string representation of the address it is for and the TTL of the record. """ self.assertEqual( repr(dns.Record_AAAA('8765::1234', ttl=10)), "<AAAA address=8765::1234 ttl=10>") def test_a6(self): """ The repr of a L{dns.Record_A6} instance includes the colon-separated hex string representation of the address it is for and the TTL of the record. """ self.assertEqual( repr(dns.Record_A6(0, '1234::5678', b'foo.bar', ttl=10)), "<A6 suffix=1234::5678 prefix=foo.bar ttl=10>") def test_srv(self): """ The repr of a L{dns.Record_SRV} instance includes the name and port of the target and the priority, weight, and TTL of the record. """ self.assertEqual( repr(dns.Record_SRV(1, 2, 3, b'example.org', 4)), "<SRV priority=1 weight=2 target=example.org port=3 ttl=4>") def test_naptr(self): """ The repr of a L{dns.Record_NAPTR} instance includes the order, preference, flags, service, regular expression, replacement, and TTL of the record. """ record = dns.Record_NAPTR( 5, 9, b"S", b"http", b"/foo/bar/i", b"baz", 3) self.assertEqual( repr(record), "<NAPTR order=5 preference=9 flags=S service=http " "regexp=/foo/bar/i replacement=baz ttl=3>") def test_afsdb(self): """ The repr of a L{dns.Record_AFSDB} instance includes the subtype, hostname, and TTL of the record. """ self.assertEqual( repr(dns.Record_AFSDB(3, b'example.org', 5)), "<AFSDB subtype=3 hostname=example.org ttl=5>") def test_rp(self): """ The repr of a L{dns.Record_RP} instance includes the mbox, txt, and TTL fields of the record. """ self.assertEqual( repr(dns.Record_RP(b'alice.example.com', b'admin.example.com', 3)), "<RP mbox=alice.example.com txt=admin.example.com ttl=3>") def test_hinfo(self): """ The repr of a L{dns.Record_HINFO} instance includes the cpu, os, and TTL fields of the record. """ self.assertEqual( repr(dns.Record_HINFO(b'sparc', b'minix', 12)), "<HINFO cpu='sparc' os='minix' ttl=12>") def test_minfo(self): """ The repr of a L{dns.Record_MINFO} instance includes the rmailbx, emailbx, and TTL fields of the record. """ record = dns.Record_MINFO( b'alice.example.com', b'bob.example.com', 15) self.assertEqual( repr(record), "<MINFO responsibility=alice.example.com " "errors=bob.example.com ttl=15>") def test_mx(self): """ The repr of a L{dns.Record_MX} instance includes the preference, name, and TTL fields of the record. """ self.assertEqual( repr(dns.Record_MX(13, b'mx.example.com', 2)), "<MX preference=13 name=mx.example.com ttl=2>") def test_txt(self): """ The repr of a L{dns.Record_TXT} instance includes the data and ttl fields of the record. """ self.assertEqual( repr(dns.Record_TXT(b"foo", b"bar", ttl=15)), "<TXT data=['foo', 'bar'] ttl=15>") def test_spf(self): """ The repr of a L{dns.Record_SPF} instance includes the data and ttl fields of the record. """ self.assertEqual( repr(dns.Record_SPF(b"foo", b"bar", ttl=15)), "<SPF data=['foo', 'bar'] ttl=15>") def test_unknown(self): """ The repr of a L{dns.UnknownRecord} instance includes the data and ttl fields of the record. """ self.assertEqual( repr(dns.UnknownRecord(b"foo\x1fbar", 12)), "<UNKNOWN data='foo\\x1fbar' ttl=12>") class EqualityTests(ComparisonTestsMixin, unittest.TestCase): """ Tests for the equality and non-equality behavior of record classes. """ def _equalityTest(self, firstValueOne, secondValueOne, valueTwo): return self.assertNormalEqualityImplementation( firstValueOne, secondValueOne, valueTwo) def test_charstr(self): """ Two L{dns.Charstr} instances compare equal if and only if they have the same string value. """ self._equalityTest( dns.Charstr(b'abc'), dns.Charstr(b'abc'), dns.Charstr(b'def')) def test_name(self): """ Two L{dns.Name} instances compare equal if and only if they have the same name value. """ self._equalityTest( dns.Name(b'abc'), dns.Name(b'abc'), dns.Name(b'def')) def _simpleEqualityTest(self, cls): """ Assert that instances of C{cls} with the same attributes compare equal to each other and instances with different attributes compare as not equal. @param cls: A L{dns.SimpleRecord} subclass. """ # Vary the TTL self._equalityTest( cls(b'example.com', 123), cls(b'example.com', 123), cls(b'example.com', 321)) # Vary the name self._equalityTest( cls(b'example.com', 123), cls(b'example.com', 123), cls(b'example.org', 123)) def test_rrheader(self): """ Two L{dns.RRHeader} instances compare equal if and only if they have the same name, type, class, time to live, payload, and authoritative bit. """ # Vary the name self._equalityTest( dns.RRHeader(b'example.com', payload=dns.Record_A('1.2.3.4')), dns.RRHeader(b'example.com', payload=dns.Record_A('1.2.3.4')), dns.RRHeader(b'example.org', payload=dns.Record_A('1.2.3.4'))) # Vary the payload self._equalityTest( dns.RRHeader(b'example.com', payload=dns.Record_A('1.2.3.4')), dns.RRHeader(b'example.com', payload=dns.Record_A('1.2.3.4')), dns.RRHeader(b'example.com', payload=dns.Record_A('1.2.3.5'))) # Vary the type. Leave the payload as None so that we don't have to # provide non-equal values. self._equalityTest( dns.RRHeader(b'example.com', dns.A), dns.RRHeader(b'example.com', dns.A), dns.RRHeader(b'example.com', dns.MX)) # Probably not likely to come up. Most people use the internet. self._equalityTest( dns.RRHeader(b'example.com', cls=dns.IN, payload=dns.Record_A('1.2.3.4')), dns.RRHeader(b'example.com', cls=dns.IN, payload=dns.Record_A('1.2.3.4')), dns.RRHeader(b'example.com', cls=dns.CS, payload=dns.Record_A('1.2.3.4'))) # Vary the ttl self._equalityTest( dns.RRHeader(b'example.com', ttl=60, payload=dns.Record_A('1.2.3.4')), dns.RRHeader(b'example.com', ttl=60, payload=dns.Record_A('1.2.3.4')), dns.RRHeader(b'example.com', ttl=120, payload=dns.Record_A('1.2.3.4'))) # Vary the auth bit self._equalityTest( dns.RRHeader(b'example.com', auth=1, payload=dns.Record_A('1.2.3.4')), dns.RRHeader(b'example.com', auth=1, payload=dns.Record_A('1.2.3.4')), dns.RRHeader(b'example.com', auth=0, payload=dns.Record_A('1.2.3.4'))) def test_ns(self): """ Two L{dns.Record_NS} instances compare equal if and only if they have the same name and TTL. """ self._simpleEqualityTest(dns.Record_NS) def test_md(self): """ Two L{dns.Record_MD} instances compare equal if and only if they have the same name and TTL. """ self._simpleEqualityTest(dns.Record_MD) def test_mf(self): """ Two L{dns.Record_MF} instances compare equal if and only if they have the same name and TTL. """ self._simpleEqualityTest(dns.Record_MF) def test_cname(self): """ Two L{dns.Record_CNAME} instances compare equal if and only if they have the same name and TTL. """ self._simpleEqualityTest(dns.Record_CNAME) def test_mb(self): """ Two L{dns.Record_MB} instances compare equal if and only if they have the same name and TTL. """ self._simpleEqualityTest(dns.Record_MB) def test_mg(self): """ Two L{dns.Record_MG} instances compare equal if and only if they have the same name and TTL. """ self._simpleEqualityTest(dns.Record_MG) def test_mr(self): """ Two L{dns.Record_MR} instances compare equal if and only if they have the same name and TTL. """ self._simpleEqualityTest(dns.Record_MR) def test_ptr(self): """ Two L{dns.Record_PTR} instances compare equal if and only if they have the same name and TTL. """ self._simpleEqualityTest(dns.Record_PTR) def test_dname(self): """ Two L{dns.Record_MD} instances compare equal if and only if they have the same name and TTL. """ self._simpleEqualityTest(dns.Record_DNAME) def test_a(self): """ Two L{dns.Record_A} instances compare equal if and only if they have the same address and TTL. """ # Vary the TTL self._equalityTest( dns.Record_A('1.2.3.4', 5), dns.Record_A('1.2.3.4', 5), dns.Record_A('1.2.3.4', 6)) # Vary the address self._equalityTest( dns.Record_A('1.2.3.4', 5), dns.Record_A('1.2.3.4', 5), dns.Record_A('1.2.3.5', 5)) def test_soa(self): """ Two L{dns.Record_SOA} instances compare equal if and only if they have the same mname, rname, serial, refresh, minimum, expire, retry, and ttl. """ # Vary the mname self._equalityTest( dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA(b'xname', b'rname', 123, 456, 789, 10, 20, 30)) # Vary the rname self._equalityTest( dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA(b'mname', b'xname', 123, 456, 789, 10, 20, 30)) # Vary the serial self._equalityTest( dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA(b'mname', b'rname', 1, 456, 789, 10, 20, 30)) # Vary the refresh self._equalityTest( dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA(b'mname', b'rname', 123, 1, 789, 10, 20, 30)) # Vary the minimum self._equalityTest( dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA(b'mname', b'rname', 123, 456, 1, 10, 20, 30)) # Vary the expire self._equalityTest( dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 1, 20, 30)) # Vary the retry self._equalityTest( dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 1, 30)) # Vary the ttl self._equalityTest( dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA(b'mname', b'xname', 123, 456, 789, 10, 20, 1)) def test_null(self): """ Two L{dns.Record_NULL} instances compare equal if and only if they have the same payload and ttl. """ # Vary the payload self._equalityTest( dns.Record_NULL('foo bar', 10), dns.Record_NULL('foo bar', 10), dns.Record_NULL('bar foo', 10)) # Vary the ttl self._equalityTest( dns.Record_NULL('foo bar', 10), dns.Record_NULL('foo bar', 10), dns.Record_NULL('foo bar', 100)) def test_wks(self): """ Two L{dns.Record_WKS} instances compare equal if and only if they have the same address, protocol, map, and ttl. """ # Vary the address self._equalityTest( dns.Record_WKS('1.2.3.4', 1, 'foo', 2), dns.Record_WKS('1.2.3.4', 1, 'foo', 2), dns.Record_WKS('4.3.2.1', 1, 'foo', 2)) # Vary the protocol self._equalityTest( dns.Record_WKS('1.2.3.4', 1, 'foo', 2), dns.Record_WKS('1.2.3.4', 1, 'foo', 2), dns.Record_WKS('1.2.3.4', 100, 'foo', 2)) # Vary the map self._equalityTest( dns.Record_WKS('1.2.3.4', 1, 'foo', 2), dns.Record_WKS('1.2.3.4', 1, 'foo', 2), dns.Record_WKS('1.2.3.4', 1, 'bar', 2)) # Vary the ttl self._equalityTest( dns.Record_WKS('1.2.3.4', 1, 'foo', 2), dns.Record_WKS('1.2.3.4', 1, 'foo', 2), dns.Record_WKS('1.2.3.4', 1, 'foo', 200)) def test_aaaa(self): """ Two L{dns.Record_AAAA} instances compare equal if and only if they have the same address and ttl. """ # Vary the address self._equalityTest( dns.Record_AAAA('1::2', 1), dns.Record_AAAA('1::2', 1), dns.Record_AAAA('2::1', 1)) # Vary the ttl self._equalityTest( dns.Record_AAAA('1::2', 1), dns.Record_AAAA('1::2', 1), dns.Record_AAAA('1::2', 10)) def test_a6(self): """ Two L{dns.Record_A6} instances compare equal if and only if they have the same prefix, prefix length, suffix, and ttl. """ # Note, A6 is crazy, I'm not sure these values are actually legal. # Hopefully that doesn't matter for this test. -exarkun # Vary the prefix length self._equalityTest( dns.Record_A6(16, '::abcd', b'example.com', 10), dns.Record_A6(16, '::abcd', b'example.com', 10), dns.Record_A6(32, '::abcd', b'example.com', 10)) # Vary the suffix self._equalityTest( dns.Record_A6(16, '::abcd', b'example.com', 10), dns.Record_A6(16, '::abcd', b'example.com', 10), dns.Record_A6(16, '::abcd:0', b'example.com', 10)) # Vary the prefix self._equalityTest( dns.Record_A6(16, '::abcd', b'example.com', 10), dns.Record_A6(16, '::abcd', b'example.com', 10), dns.Record_A6(16, '::abcd', b'example.org', 10)) # Vary the ttl self._equalityTest( dns.Record_A6(16, '::abcd', b'example.com', 10), dns.Record_A6(16, '::abcd', b'example.com', 10), dns.Record_A6(16, '::abcd', b'example.com', 100)) def test_srv(self): """ Two L{dns.Record_SRV} instances compare equal if and only if they have the same priority, weight, port, target, and ttl. """ # Vary the priority self._equalityTest( dns.Record_SRV(10, 20, 30, b'example.com', 40), dns.Record_SRV(10, 20, 30, b'example.com', 40), dns.Record_SRV(100, 20, 30, b'example.com', 40)) # Vary the weight self._equalityTest( dns.Record_SRV(10, 20, 30, b'example.com', 40), dns.Record_SRV(10, 20, 30, b'example.com', 40), dns.Record_SRV(10, 200, 30, b'example.com', 40)) # Vary the port self._equalityTest( dns.Record_SRV(10, 20, 30, b'example.com', 40), dns.Record_SRV(10, 20, 30, b'example.com', 40), dns.Record_SRV(10, 20, 300, b'example.com', 40)) # Vary the target self._equalityTest( dns.Record_SRV(10, 20, 30, b'example.com', 40), dns.Record_SRV(10, 20, 30, b'example.com', 40), dns.Record_SRV(10, 20, 30, b'example.org', 40)) # Vary the ttl self._equalityTest( dns.Record_SRV(10, 20, 30, b'example.com', 40), dns.Record_SRV(10, 20, 30, b'example.com', 40), dns.Record_SRV(10, 20, 30, b'example.com', 400)) def test_naptr(self): """ Two L{dns.Record_NAPTR} instances compare equal if and only if they have the same order, preference, flags, service, regexp, replacement, and ttl. """ # Vary the order self._equalityTest( dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12), dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12), dns.Record_NAPTR(2, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12)) # Vary the preference self._equalityTest( dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12), dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12), dns.Record_NAPTR(1, 3, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12)) # Vary the flags self._equalityTest( dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12), dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12), dns.Record_NAPTR(1, 2, b"p", b"sip+E2U", b"/foo/bar/", b"baz", 12)) # Vary the service self._equalityTest( dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12), dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12), dns.Record_NAPTR(1, 2, b"u", b"http", b"/foo/bar/", b"baz", 12)) # Vary the regexp self._equalityTest( dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12), dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12), dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/bar/foo/", b"baz", 12)) # Vary the replacement self._equalityTest( dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12), dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12), dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/bar/foo/", b"quux", 12)) # Vary the ttl self._equalityTest( dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12), dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12), dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/bar/foo/", b"baz", 5)) def test_afsdb(self): """ Two L{dns.Record_AFSDB} instances compare equal if and only if they have the same subtype, hostname, and ttl. """ # Vary the subtype self._equalityTest( dns.Record_AFSDB(1, b'example.com', 2), dns.Record_AFSDB(1, b'example.com', 2), dns.Record_AFSDB(2, b'example.com', 2)) # Vary the hostname self._equalityTest( dns.Record_AFSDB(1, b'example.com', 2), dns.Record_AFSDB(1, b'example.com', 2), dns.Record_AFSDB(1, b'example.org', 2)) # Vary the ttl self._equalityTest( dns.Record_AFSDB(1, b'example.com', 2), dns.Record_AFSDB(1, b'example.com', 2), dns.Record_AFSDB(1, b'example.com', 3)) def test_rp(self): """ Two L{Record_RP} instances compare equal if and only if they have the same mbox, txt, and ttl. """ # Vary the mbox self._equalityTest( dns.Record_RP(b'alice.example.com', b'alice is nice', 10), dns.Record_RP(b'alice.example.com', b'alice is nice', 10), dns.Record_RP(b'bob.example.com', b'alice is nice', 10)) # Vary the txt self._equalityTest( dns.Record_RP(b'alice.example.com', b'alice is nice', 10), dns.Record_RP(b'alice.example.com', b'alice is nice', 10), dns.Record_RP(b'alice.example.com', b'alice is not nice', 10)) # Vary the ttl self._equalityTest( dns.Record_RP(b'alice.example.com', b'alice is nice', 10), dns.Record_RP(b'alice.example.com', b'alice is nice', 10), dns.Record_RP(b'alice.example.com', b'alice is nice', 100)) def test_hinfo(self): """ Two L{dns.Record_HINFO} instances compare equal if and only if they have the same cpu, os, and ttl. """ # Vary the cpu self._equalityTest( dns.Record_HINFO('x86-64', 'plan9', 10), dns.Record_HINFO('x86-64', 'plan9', 10), dns.Record_HINFO('i386', 'plan9', 10)) # Vary the os self._equalityTest( dns.Record_HINFO('x86-64', 'plan9', 10), dns.Record_HINFO('x86-64', 'plan9', 10), dns.Record_HINFO('x86-64', 'plan11', 10)) # Vary the ttl self._equalityTest( dns.Record_HINFO('x86-64', 'plan9', 10), dns.Record_HINFO('x86-64', 'plan9', 10), dns.Record_HINFO('x86-64', 'plan9', 100)) def test_minfo(self): """ Two L{dns.Record_MINFO} instances compare equal if and only if they have the same rmailbx, emailbx, and ttl. """ # Vary the rmailbx self._equalityTest( dns.Record_MINFO(b'rmailbox', b'emailbox', 10), dns.Record_MINFO(b'rmailbox', b'emailbox', 10), dns.Record_MINFO(b'someplace', b'emailbox', 10)) # Vary the emailbx self._equalityTest( dns.Record_MINFO(b'rmailbox', b'emailbox', 10), dns.Record_MINFO(b'rmailbox', b'emailbox', 10), dns.Record_MINFO(b'rmailbox', b'something', 10)) # Vary the ttl self._equalityTest( dns.Record_MINFO(b'rmailbox', b'emailbox', 10), dns.Record_MINFO(b'rmailbox', b'emailbox', 10), dns.Record_MINFO(b'rmailbox', b'emailbox', 100)) def test_mx(self): """ Two L{dns.Record_MX} instances compare equal if and only if they have the same preference, name, and ttl. """ # Vary the preference self._equalityTest( dns.Record_MX(10, b'example.org', 20), dns.Record_MX(10, b'example.org', 20), dns.Record_MX(100, b'example.org', 20)) # Vary the name self._equalityTest( dns.Record_MX(10, b'example.org', 20), dns.Record_MX(10, b'example.org', 20), dns.Record_MX(10, b'example.net', 20)) # Vary the ttl self._equalityTest( dns.Record_MX(10, b'example.org', 20), dns.Record_MX(10, b'example.org', 20), dns.Record_MX(10, b'example.org', 200)) def test_txt(self): """ Two L{dns.Record_TXT} instances compare equal if and only if they have the same data and ttl. """ # Vary the length of the data self._equalityTest( dns.Record_TXT('foo', 'bar', ttl=10), dns.Record_TXT('foo', 'bar', ttl=10), dns.Record_TXT('foo', 'bar', 'baz', ttl=10)) # Vary the value of the data self._equalityTest( dns.Record_TXT('foo', 'bar', ttl=10), dns.Record_TXT('foo', 'bar', ttl=10), dns.Record_TXT('bar', 'foo', ttl=10)) # Vary the ttl self._equalityTest( dns.Record_TXT('foo', 'bar', ttl=10), dns.Record_TXT('foo', 'bar', ttl=10), dns.Record_TXT('foo', 'bar', ttl=100)) def test_spf(self): """ L{dns.Record_SPF} instances compare equal if and only if they have the same data and ttl. """ # Vary the length of the data self._equalityTest( dns.Record_SPF('foo', 'bar', ttl=10), dns.Record_SPF('foo', 'bar', ttl=10), dns.Record_SPF('foo', 'bar', 'baz', ttl=10)) # Vary the value of the data self._equalityTest( dns.Record_SPF('foo', 'bar', ttl=10), dns.Record_SPF('foo', 'bar', ttl=10), dns.Record_SPF('bar', 'foo', ttl=10)) # Vary the ttl self._equalityTest( dns.Record_SPF('foo', 'bar', ttl=10), dns.Record_SPF('foo', 'bar', ttl=10), dns.Record_SPF('foo', 'bar', ttl=100)) def test_unknown(self): """ L{dns.UnknownRecord} instances compare equal if and only if they have the same data and ttl. """ # Vary the length of the data self._equalityTest( dns.UnknownRecord('foo', ttl=10), dns.UnknownRecord('foo', ttl=10), dns.UnknownRecord('foobar', ttl=10)) # Vary the value of the data self._equalityTest( dns.UnknownRecord('foo', ttl=10), dns.UnknownRecord('foo', ttl=10), dns.UnknownRecord('bar', ttl=10)) # Vary the ttl self._equalityTest( dns.UnknownRecord('foo', ttl=10), dns.UnknownRecord('foo', ttl=10), dns.UnknownRecord('foo', ttl=100)) class RRHeaderTests(unittest.TestCase): """ Tests for L{twisted.names.dns.RRHeader}. """ def test_negativeTTL(self): """ Attempting to create a L{dns.RRHeader} instance with a negative TTL causes L{ValueError} to be raised. """ self.assertRaises( ValueError, dns.RRHeader, "example.com", dns.A, dns.IN, -1, dns.Record_A("127.0.0.1")) def test_nonIntegralTTL(self): """ L{dns.RRHeader} converts TTLs to integers. """ ttlAsFloat = 123.45 header = dns.RRHeader("example.com", dns.A, dns.IN, ttlAsFloat, dns.Record_A("127.0.0.1")) self.assertEqual(header.ttl, int(ttlAsFloat)) def test_nonNumericTTLRaisesTypeError(self): """ Attempting to create a L{dns.RRHeader} instance with a TTL that L{int} cannot convert to an integer raises a L{TypeError}. """ self.assertRaises( ValueError, dns.RRHeader, "example.com", dns.A, dns.IN, "this is not a number", dns.Record_A("127.0.0.1")) class NameToLabelsTests(unittest.SynchronousTestCase): """ Tests for L{twisted.names.dns._nameToLabels}. """ def test_empty(self): """ L{dns._nameToLabels} returns a list containing a single empty label for an empty name. """ self.assertEqual(dns._nameToLabels(b''), [b'']) def test_onlyDot(self): """ L{dns._nameToLabels} returns a list containing a single empty label for a name containing only a dot. """ self.assertEqual(dns._nameToLabels(b'.'), [b'']) def test_withoutTrailingDot(self): """ L{dns._nameToLabels} returns a list ending with an empty label for a name without a trailing dot. """ self.assertEqual(dns._nameToLabels(b'com'), [b'com', b'']) def test_withTrailingDot(self): """ L{dns._nameToLabels} returns a list ending with an empty label for a name with a trailing dot. """ self.assertEqual(dns._nameToLabels(b'com.'), [b'com', b'']) def test_subdomain(self): """ L{dns._nameToLabels} returns a list containing entries for all labels in a subdomain name. """ self.assertEqual( dns._nameToLabels(b'foo.bar.baz.example.com.'), [b'foo', b'bar', b'baz', b'example', b'com', b'']) def test_casePreservation(self): """ L{dns._nameToLabels} preserves the case of ascii characters in labels. """ self.assertEqual( dns._nameToLabels(b'EXAMPLE.COM'), [b'EXAMPLE', b'COM', b'']) def assertIsSubdomainOf(testCase, descendant, ancestor): """ Assert that C{descendant} *is* a subdomain of C{ancestor}. @type testCase: L{unittest.SynchronousTestCase} @param testCase: The test case on which to run the assertions. @type descendant: C{str} @param descendant: The subdomain name to test. @type ancestor: C{str} @param ancestor: The superdomain name to test. """ testCase.assertTrue( dns._isSubdomainOf(descendant, ancestor), '%r is not a subdomain of %r' % (descendant, ancestor)) def assertIsNotSubdomainOf(testCase, descendant, ancestor): """ Assert that C{descendant} *is not* a subdomain of C{ancestor}. @type testCase: L{unittest.SynchronousTestCase} @param testCase: The test case on which to run the assertions. @type descendant: C{str} @param descendant: The subdomain name to test. @type ancestor: C{str} @param ancestor: The superdomain name to test. """ testCase.assertFalse( dns._isSubdomainOf(descendant, ancestor), '%r is a subdomain of %r' % (descendant, ancestor)) class IsSubdomainOfTests(unittest.SynchronousTestCase): """ Tests for L{twisted.names.dns._isSubdomainOf}. """ def test_identical(self): """ L{dns._isSubdomainOf} returns C{True} for identical domain names. """ assertIsSubdomainOf(self, b'example.com', b'example.com') def test_parent(self): """ L{dns._isSubdomainOf} returns C{True} when the first name is an immediate descendant of the second name. """ assertIsSubdomainOf(self, b'foo.example.com', b'example.com') def test_distantAncestor(self): """ L{dns._isSubdomainOf} returns C{True} when the first name is a distant descendant of the second name. """ assertIsSubdomainOf(self, b'foo.bar.baz.example.com', b'com') def test_superdomain(self): """ L{dns._isSubdomainOf} returns C{False} when the first name is an ancestor of the second name. """ assertIsNotSubdomainOf(self, b'example.com', b'foo.example.com') def test_sibling(self): """ L{dns._isSubdomainOf} returns C{False} if the first name is a sibling of the second name. """ assertIsNotSubdomainOf(self, b'foo.example.com', b'bar.example.com') def test_unrelatedCommonSuffix(self): """ L{dns._isSubdomainOf} returns C{False} even when domain names happen to share a common suffix. """ assertIsNotSubdomainOf(self, b'foo.myexample.com', b'example.com') def test_subdomainWithTrailingDot(self): """ L{dns._isSubdomainOf} returns C{True} if the first name is a subdomain of the second name but the first name has a trailing ".". """ assertIsSubdomainOf(self, b'foo.example.com.', b'example.com') def test_superdomainWithTrailingDot(self): """ L{dns._isSubdomainOf} returns C{True} if the first name is a subdomain of the second name but the second name has a trailing ".". """ assertIsSubdomainOf(self, b'foo.example.com', b'example.com.') def test_bothWithTrailingDot(self): """ L{dns._isSubdomainOf} returns C{True} if the first name is a subdomain of the second name and both names have a trailing ".". """ assertIsSubdomainOf(self, b'foo.example.com.', b'example.com.') def test_emptySubdomain(self): """ L{dns._isSubdomainOf} returns C{False} if the first name is empty and the second name is not. """ assertIsNotSubdomainOf(self, b'', b'example.com') def test_emptySuperdomain(self): """ L{dns._isSubdomainOf} returns C{True} if the second name is empty and the first name is not. """ assertIsSubdomainOf(self, b'foo.example.com', b'') def test_caseInsensitiveComparison(self): """ L{dns._isSubdomainOf} does case-insensitive comparison of name labels. """ assertIsSubdomainOf(self, b'foo.example.com', b'EXAMPLE.COM') assertIsSubdomainOf(self, b'FOO.EXAMPLE.COM', b'example.com') class OPTNonStandardAttributes(object): """ Generate byte and instance representations of an L{dns._OPTHeader} where all attributes are set to non-default values. For testing whether attributes have really been read from the byte string during decoding. """ @classmethod def bytes(cls, excludeName=False, excludeOptions=False): """ Return L{bytes} representing an encoded OPT record. @param excludeName: A flag that controls whether to exclude the name field. This allows a non-standard name to be prepended during the test. @type excludeName: L{bool} @param excludeOptions: A flag that controls whether to exclude the RDLEN field. This allows encoded variable options to be appended during the test. @type excludeOptions: L{bool} @return: L{bytes} representing the encoded OPT record returned by L{object}. """ rdlen = b'\x00\x00' # RDLEN 0 if excludeOptions: rdlen = b'' return ( b'\x00' # 0 root zone b'\x00\x29' # type 41 b'\x02\x00' # udpPayloadsize 512 b'\x03' # extendedRCODE 3 b'\x04' # version 4 b'\x80\x00' # DNSSEC OK 1 + Z ) + rdlen @classmethod def object(cls): """ Return a new L{dns._OPTHeader} instance. @return: A L{dns._OPTHeader} instance with attributes that match the encoded record returned by L{bytes}. """ return dns._OPTHeader( udpPayloadSize=512, extendedRCODE=3, version=4, dnssecOK=True) class OPTHeaderTests(ComparisonTestsMixin, unittest.TestCase): """ Tests for L{twisted.names.dns._OPTHeader}. """ def test_interface(self): """ L{dns._OPTHeader} implements L{dns.IEncodable}. """ verifyClass(dns.IEncodable, dns._OPTHeader) def test_name(self): """ L{dns._OPTHeader.name} is an instance attribute whose value is fixed as the root domain """ self.assertEqual(dns._OPTHeader().name, dns.Name(b'')) def test_nameReadonly(self): """ L{dns._OPTHeader.name} is readonly. """ h = dns._OPTHeader() self.assertRaises( AttributeError, setattr, h, 'name', dns.Name(b'example.com')) def test_type(self): """ L{dns._OPTHeader.type} is an instance attribute with fixed value 41. """ self.assertEqual(dns._OPTHeader().type, 41) def test_typeReadonly(self): """ L{dns._OPTHeader.type} is readonly. """ h = dns._OPTHeader() self.assertRaises( AttributeError, setattr, h, 'type', dns.A) def test_udpPayloadSize(self): """ L{dns._OPTHeader.udpPayloadSize} defaults to 4096 as recommended in rfc6891 section-6.2.5. """ self.assertEqual(dns._OPTHeader().udpPayloadSize, 4096) def test_udpPayloadSizeOverride(self): """ L{dns._OPTHeader.udpPayloadSize} can be overridden in the constructor. """ self.assertEqual(dns._OPTHeader(udpPayloadSize=512).udpPayloadSize, 512) def test_extendedRCODE(self): """ L{dns._OPTHeader.extendedRCODE} defaults to 0. """ self.assertEqual(dns._OPTHeader().extendedRCODE, 0) def test_extendedRCODEOverride(self): """ L{dns._OPTHeader.extendedRCODE} can be overridden in the constructor. """ self.assertEqual(dns._OPTHeader(extendedRCODE=1).extendedRCODE, 1) def test_version(self): """ L{dns._OPTHeader.version} defaults to 0. """ self.assertEqual(dns._OPTHeader().version, 0) def test_versionOverride(self): """ L{dns._OPTHeader.version} can be overridden in the constructor. """ self.assertEqual(dns._OPTHeader(version=1).version, 1) def test_dnssecOK(self): """ L{dns._OPTHeader.dnssecOK} defaults to False. """ self.assertFalse(dns._OPTHeader().dnssecOK) def test_dnssecOKOverride(self): """ L{dns._OPTHeader.dnssecOK} can be overridden in the constructor. """ self.assertTrue(dns._OPTHeader(dnssecOK=True).dnssecOK) def test_options(self): """ L{dns._OPTHeader.options} defaults to empty list. """ self.assertEqual(dns._OPTHeader().options, []) def test_optionsOverride(self): """ L{dns._OPTHeader.options} can be overridden in the constructor. """ h = dns._OPTHeader(options=[(1, 1, b'\x00')]) self.assertEqual(h.options, [(1, 1, b'\x00')]) def test_encode(self): """ L{dns._OPTHeader.encode} packs the header fields and writes them to a file like object passed in as an argument. """ b = BytesIO() OPTNonStandardAttributes.object().encode(b) self.assertEqual( b.getvalue(), OPTNonStandardAttributes.bytes() ) def test_encodeWithOptions(self): """ L{dns._OPTHeader.options} is a list of L{dns._OPTVariableOption} instances which are packed into the rdata area of the header. """ h = OPTNonStandardAttributes.object() h.options = [ dns._OPTVariableOption(1, b'foobarbaz'), dns._OPTVariableOption(2, b'qux'), ] b = BytesIO() h.encode(b) self.assertEqual( b.getvalue(), OPTNonStandardAttributes.bytes(excludeOptions=True) + ( b'\x00\x14' # RDLEN 20 b'\x00\x01' # OPTION-CODE b'\x00\x09' # OPTION-LENGTH b'foobarbaz' # OPTION-DATA b'\x00\x02' # OPTION-CODE b'\x00\x03' # OPTION-LENGTH b'qux' # OPTION-DATA )) def test_decode(self): """ L{dns._OPTHeader.decode} unpacks the header fields from a file like object and populates the attributes of an existing L{dns._OPTHeader} instance. """ decodedHeader = dns._OPTHeader() decodedHeader.decode(BytesIO(OPTNonStandardAttributes.bytes())) self.assertEqual( decodedHeader, OPTNonStandardAttributes.object()) def test_decodeAllExpectedBytes(self): """ L{dns._OPTHeader.decode} reads all the bytes of the record that is being decoded. """ # Check that all the input data has been consumed. b = BytesIO(OPTNonStandardAttributes.bytes()) decodedHeader = dns._OPTHeader() decodedHeader.decode(b) self.assertEqual(b.tell(), len(b.getvalue())) def test_decodeOnlyExpectedBytes(self): """ L{dns._OPTHeader.decode} reads only the bytes from the current file position to the end of the record that is being decoded. Trailing bytes are not consumed. """ b = BytesIO(OPTNonStandardAttributes.bytes() + b'xxxx') # Trailing bytes decodedHeader = dns._OPTHeader() decodedHeader.decode(b) self.assertEqual(b.tell(), len(b.getvalue())-len(b'xxxx')) def test_decodeDiscardsName(self): """ L{dns._OPTHeader.decode} discards the name which is encoded in the supplied bytes. The name attribute of the resulting L{dns._OPTHeader} instance will always be L{dns.Name(b'')}. """ b = BytesIO(OPTNonStandardAttributes.bytes(excludeName=True) + b'\x07example\x03com\x00') h = dns._OPTHeader() h.decode(b) self.assertEqual(h.name, dns.Name(b'')) def test_decodeRdlengthTooShort(self): """ L{dns._OPTHeader.decode} raises an exception if the supplied RDLEN is too short. """ b = BytesIO( OPTNonStandardAttributes.bytes(excludeOptions=True) + ( b'\x00\x05' # RDLEN 5 Too short - should be 6 b'\x00\x01' # OPTION-CODE b'\x00\x02' # OPTION-LENGTH b'\x00\x00' # OPTION-DATA )) h = dns._OPTHeader() self.assertRaises(EOFError, h.decode, b) def test_decodeRdlengthTooLong(self): """ L{dns._OPTHeader.decode} raises an exception if the supplied RDLEN is too long. """ b = BytesIO( OPTNonStandardAttributes.bytes(excludeOptions=True) + ( b'\x00\x07' # RDLEN 7 Too long - should be 6 b'\x00\x01' # OPTION-CODE b'\x00\x02' # OPTION-LENGTH b'\x00\x00' # OPTION-DATA )) h = dns._OPTHeader() self.assertRaises(EOFError, h.decode, b) def test_decodeWithOptions(self): """ If the OPT bytes contain variable options, L{dns._OPTHeader.decode} will populate a list L{dns._OPTHeader.options} with L{dns._OPTVariableOption} instances. """ b = BytesIO( OPTNonStandardAttributes.bytes(excludeOptions=True) + ( b'\x00\x14' # RDLEN 20 b'\x00\x01' # OPTION-CODE b'\x00\x09' # OPTION-LENGTH b'foobarbaz' # OPTION-DATA b'\x00\x02' # OPTION-CODE b'\x00\x03' # OPTION-LENGTH b'qux' # OPTION-DATA )) h = dns._OPTHeader() h.decode(b) self.assertEqual( h.options, [dns._OPTVariableOption(1, b'foobarbaz'), dns._OPTVariableOption(2, b'qux'),] ) def test_fromRRHeader(self): """ L{_OPTHeader.fromRRHeader} accepts an L{RRHeader} instance and returns an L{_OPTHeader} instance whose attribute values have been derived from the C{cls}, C{ttl} and C{payload} attributes of the original header. """ genericHeader = dns.RRHeader( b'example.com', type=dns.OPT, cls=0xffff, ttl=(0xfe << 24 | 0xfd << 16 | True << 15), payload=dns.UnknownRecord(b'\xff\xff\x00\x03abc')) decodedOptHeader = dns._OPTHeader.fromRRHeader(genericHeader) expectedOptHeader = dns._OPTHeader( udpPayloadSize=0xffff, extendedRCODE=0xfe, version=0xfd, dnssecOK=True, options=[dns._OPTVariableOption(code=0xffff, data=b'abc')]) self.assertEqual(decodedOptHeader, expectedOptHeader) def test_repr(self): """ L{dns._OPTHeader.__repr__} displays the name and type and all the fixed and extended header values of the OPT record. """ self.assertEqual( repr(dns._OPTHeader()), '<_OPTHeader ' 'name= ' 'type=41 ' 'udpPayloadSize=4096 ' 'extendedRCODE=0 ' 'version=0 ' 'dnssecOK=False ' 'options=[]>') def test_equalityUdpPayloadSize(self): """ Two L{OPTHeader} instances compare equal if they have the same udpPayloadSize. """ self.assertNormalEqualityImplementation( dns._OPTHeader(udpPayloadSize=512), dns._OPTHeader(udpPayloadSize=512), dns._OPTHeader(udpPayloadSize=4096)) def test_equalityExtendedRCODE(self): """ Two L{OPTHeader} instances compare equal if they have the same extendedRCODE. """ self.assertNormalEqualityImplementation( dns._OPTHeader(extendedRCODE=1), dns._OPTHeader(extendedRCODE=1), dns._OPTHeader(extendedRCODE=2)) def test_equalityVersion(self): """ Two L{OPTHeader} instances compare equal if they have the same version. """ self.assertNormalEqualityImplementation( dns._OPTHeader(version=1), dns._OPTHeader(version=1), dns._OPTHeader(version=2)) def test_equalityDnssecOK(self): """ Two L{OPTHeader} instances compare equal if they have the same dnssecOK flags. """ self.assertNormalEqualityImplementation( dns._OPTHeader(dnssecOK=True), dns._OPTHeader(dnssecOK=True), dns._OPTHeader(dnssecOK=False)) def test_equalityOptions(self): """ Two L{OPTHeader} instances compare equal if they have the same options. """ self.assertNormalEqualityImplementation( dns._OPTHeader(options=[dns._OPTVariableOption(1, b'x')]), dns._OPTHeader(options=[dns._OPTVariableOption(1, b'x')]), dns._OPTHeader(options=[dns._OPTVariableOption(2, b'y')])) class OPTVariableOptionTests(ComparisonTestsMixin, unittest.TestCase): """ Tests for L{dns._OPTVariableOption}. """ def test_interface(self): """ L{dns._OPTVariableOption} implements L{dns.IEncodable}. """ verifyClass(dns.IEncodable, dns._OPTVariableOption) def test_constructorArguments(self): """ L{dns._OPTVariableOption.__init__} requires code and data arguments which are saved as public instance attributes. """ h = dns._OPTVariableOption(1, b'x') self.assertEqual(h.code, 1) self.assertEqual(h.data, b'x') def test_repr(self): """ L{dns._OPTVariableOption.__repr__} displays the code and data of the option. """ self.assertEqual( repr(dns._OPTVariableOption(1, b'x')), '<_OPTVariableOption ' 'code=1 ' "data=x" '>') def test_equality(self): """ Two OPTVariableOption instances compare equal if they have the same code and data values. """ self.assertNormalEqualityImplementation( dns._OPTVariableOption(1, b'x'), dns._OPTVariableOption(1, b'x'), dns._OPTVariableOption(2, b'x')) self.assertNormalEqualityImplementation( dns._OPTVariableOption(1, b'x'), dns._OPTVariableOption(1, b'x'), dns._OPTVariableOption(1, b'y')) def test_encode(self): """ L{dns._OPTVariableOption.encode} encodes the code and data instance attributes to a byte string which also includes the data length. """ o = dns._OPTVariableOption(1, b'foobar') b = BytesIO() o.encode(b) self.assertEqual( b.getvalue(), b'\x00\x01' # OPTION-CODE 1 b'\x00\x06' # OPTION-LENGTH 6 b'foobar' # OPTION-DATA ) def test_decode(self): """ L{dns._OPTVariableOption.decode} is a classmethod that decodes a byte string and returns a L{dns._OPTVariableOption} instance. """ b = BytesIO( b'\x00\x01' # OPTION-CODE 1 b'\x00\x06' # OPTION-LENGTH 6 b'foobar' # OPTION-DATA ) o = dns._OPTVariableOption() o.decode(b) self.assertEqual(o.code, 1) self.assertEqual(o.data, b'foobar') class RaisedArgs(Exception): """ An exception which can be raised by fakes to test that the fake is called with expected arguments. """ def __init__(self, args, kwargs): """ Store the positional and keyword arguments as attributes. @param args: The positional args. @param kwargs: The keyword args. """ self.args = args self.kwargs = kwargs class MessageEmpty(object): """ Generate byte string and constructor arguments for an empty L{dns._EDNSMessage}. """ @classmethod def bytes(cls): """ Bytes which are expected when encoding an instance constructed using C{kwargs} and which are expected to result in an identical instance when decoded. @return: The L{bytes} of a wire encoded message. """ return ( b'\x01\x00' # id: 256 b'\x97' # QR: 1, OPCODE: 2, AA: 0, TC: 0, RD: 1 b'\x8f' # RA: 1, Z, RCODE: 15 b'\x00\x00' # number of queries b'\x00\x00' # number of answers b'\x00\x00' # number of authorities b'\x00\x00' # number of additionals ) @classmethod def kwargs(cls): """ Keyword constructor arguments which are expected to result in an instance which returns C{bytes} when encoded. @return: A L{dict} of keyword arguments. """ return dict( id=256, answer=True, opCode=dns.OP_STATUS, auth=True, trunc=True, recDes=True, recAv=True, rCode=15, ednsVersion=None, ) class MessageTruncated(object): """ An empty response message whose TR bit is set to 1. """ @classmethod def bytes(cls): """ Bytes which are expected when encoding an instance constructed using C{kwargs} and which are expected to result in an identical instance when decoded. @return: The L{bytes} of a wire encoded message. """ return ( b'\x01\x00' # ID: 256 b'\x82' # QR: 1, OPCODE: 0, AA: 0, TC: 1, RD: 0 b'\x00' # RA: 0, Z, RCODE: 0 b'\x00\x00' # Number of queries b'\x00\x00' # Number of answers b'\x00\x00' # Number of authorities b'\x00\x00' # Number of additionals ) @classmethod def kwargs(cls): """ Keyword constructor arguments which are expected to result in an instance which returns C{bytes} when encoded. @return: A L{dict} of keyword arguments. """ return dict( id=256, answer=1, opCode=0, auth=0, trunc=1, recDes=0, recAv=0, rCode=0, ednsVersion=None,) class MessageNonAuthoritative(object): """ A minimal non-authoritative message. """ @classmethod def bytes(cls): """ Bytes which are expected when encoding an instance constructed using C{kwargs} and which are expected to result in an identical instance when decoded. @return: The L{bytes} of a wire encoded message. """ return ( b'\x01\x00' # ID 256 b'\x00' # QR: 0, OPCODE: 0, AA: 0, TC: 0, RD: 0 b'\x00' # RA: 0, Z, RCODE: 0 b'\x00\x00' # Query count b'\x00\x01' # Answer count b'\x00\x00' # Authorities count b'\x00\x00' # Additionals count # Answer b'\x00' # RR NAME (root) b'\x00\x01' # RR TYPE 1 (A) b'\x00\x01' # RR CLASS 1 (IN) b'\x00\x00\x00\x00' # RR TTL b'\x00\x04' # RDLENGTH 4 b'\x01\x02\x03\x04' # IPv4 1.2.3.4 ) @classmethod def kwargs(cls): """ Keyword constructor arguments which are expected to result in an instance which returns C{bytes} when encoded. @return: A L{dict} of keyword arguments. """ return dict( id=256, auth=0, ednsVersion=None, answers=[ dns.RRHeader( b'', payload=dns.Record_A('1.2.3.4', ttl=0), auth=False)]) class MessageAuthoritative(object): """ A minimal authoritative message. """ @classmethod def bytes(cls): """ Bytes which are expected when encoding an instance constructed using C{kwargs} and which are expected to result in an identical instance when decoded. @return: The L{bytes} of a wire encoded message. """ return ( b'\x01\x00' # ID: 256 b'\x04' # QR: 0, OPCODE: 0, AA: 1, TC: 0, RD: 0 b'\x00' # RA: 0, Z, RCODE: 0 b'\x00\x00' # Query count b'\x00\x01' # Answer count b'\x00\x00' # Authorities count b'\x00\x00' # Additionals count # Answer b'\x00' # RR NAME (root) b'\x00\x01' # RR TYPE 1 (A) b'\x00\x01' # RR CLASS 1 (IN) b'\x00\x00\x00\x00' # RR TTL b'\x00\x04' # RDLENGTH 4 b'\x01\x02\x03\x04' # IPv4 1.2.3.4 ) @classmethod def kwargs(cls): """ Keyword constructor arguments which are expected to result in an instance which returns C{bytes} when encoded. @return: A L{dict} of keyword arguments. """ return dict( id=256, auth=1, ednsVersion=None, answers=[ dns.RRHeader( b'', payload=dns.Record_A('1.2.3.4', ttl=0), auth=True)]) class MessageComplete: """ An example of a fully populated non-edns response message. Contains name compression, answers, authority, and additional records. """ @classmethod def bytes(cls): """ Bytes which are expected when encoding an instance constructed using C{kwargs} and which are expected to result in an identical instance when decoded. @return: The L{bytes} of a wire encoded message. """ return ( b'\x01\x00' # ID: 256 b'\x95' # QR: 1, OPCODE: 2, AA: 1, TC: 0, RD: 1 b'\x8f' # RA: 1, Z, RCODE: 15 b'\x00\x01' # Query count b'\x00\x01' # Answer count b'\x00\x01' # Authorities count b'\x00\x01' # Additionals count # Query begins at Byte 12 b'\x07example\x03com\x00' # QNAME b'\x00\x06' # QTYPE 6 (SOA) b'\x00\x01' # QCLASS 1 (IN) # Answers b'\xc0\x0c' # RR NAME (compression ref b12) b'\x00\x06' # RR TYPE 6 (SOA) b'\x00\x01' # RR CLASS 1 (IN) b'\xff\xff\xff\xff' # RR TTL b'\x00\x27' # RDLENGTH 39 b'\x03ns1\xc0\x0c' # Mname (ns1.example.com (compression ref b15) b'\x0ahostmaster\xc0\x0c' # rname (hostmaster.example.com) b'\xff\xff\xff\xfe' # Serial b'\x7f\xff\xff\xfd' # Refresh b'\x7f\xff\xff\xfc' # Retry b'\x7f\xff\xff\xfb' # Expire b'\xff\xff\xff\xfa' # Minimum # Authority b'\xc0\x0c' # RR NAME (example.com compression ref b12) b'\x00\x02' # RR TYPE 2 (NS) b'\x00\x01' # RR CLASS 1 (IN) b'\xff\xff\xff\xff' # RR TTL b'\x00\x02' # RDLENGTH b'\xc0\x29' # RDATA (ns1.example.com (compression ref b41) # Additional b'\xc0\x29' # RR NAME (ns1.example.com compression ref b41) b'\x00\x01' # RR TYPE 1 (A) b'\x00\x01' # RR CLASS 1 (IN) b'\xff\xff\xff\xff' # RR TTL b'\x00\x04' # RDLENGTH b'\x05\x06\x07\x08' # RDATA 5.6.7.8 ) @classmethod def kwargs(cls): """ Keyword constructor arguments which are expected to result in an instance which returns C{bytes} when encoded. @return: A L{dict} of keyword arguments. """ return dict( id=256, answer=1, opCode=dns.OP_STATUS, auth=1, recDes=1, recAv=1, rCode=15, ednsVersion=None, queries=[dns.Query(b'example.com', dns.SOA)], answers=[ dns.RRHeader( b'example.com', type=dns.SOA, ttl=0xffffffff, auth=True, payload=dns.Record_SOA( ttl=0xffffffff, mname=b'ns1.example.com', rname=b'hostmaster.example.com', serial=0xfffffffe, refresh=0x7ffffffd, retry=0x7ffffffc, expire=0x7ffffffb, minimum=0xfffffffa, ))], authority=[ dns.RRHeader( b'example.com', type=dns.NS, ttl=0xffffffff, auth=True, payload=dns.Record_NS( 'ns1.example.com', ttl=0xffffffff))], additional=[ dns.RRHeader( b'ns1.example.com', type=dns.A, ttl=0xffffffff, auth=True, payload=dns.Record_A( '5.6.7.8', ttl=0xffffffff))]) class MessageEDNSQuery(object): """ A minimal EDNS query message. """ @classmethod def bytes(cls): """ Bytes which are expected when encoding an instance constructed using C{kwargs} and which are expected to result in an identical instance when decoded. @return: The L{bytes} of a wire encoded message. """ return ( b'\x00\x00' # ID: 0 b'\x00' # QR: 0, OPCODE: 0, AA: 0, TC: 0, RD: 0 b'\x00' # RA: 0, Z, RCODE: 0 b'\x00\x01' # Queries count b'\x00\x00' # Anwers count b'\x00\x00' # Authority count b'\x00\x01' # Additionals count # Queries b'\x03www\x07example\x03com\x00' # QNAME b'\x00\x01' # QTYPE (A) b'\x00\x01' # QCLASS (IN) # Additional OPT record b'\x00' # NAME (.) b'\x00\x29' # TYPE (OPT 41) b'\x10\x00' # UDP Payload Size (4096) b'\x00' # Extended RCODE b'\x03' # EDNS version b'\x00\x00' # DO: False + Z b'\x00\x00' # RDLENGTH ) @classmethod def kwargs(cls): """ Keyword constructor arguments which are expected to result in an instance which returns C{bytes} when encoded. @return: A L{dict} of keyword arguments. """ return dict( id=0, answer=0, opCode=dns.OP_QUERY, auth=0, recDes=0, recAv=0, rCode=0, ednsVersion=3, dnssecOK=False, queries=[dns.Query(b'www.example.com', dns.A)], additional=[]) class MessageEDNSComplete(object): """ An example of a fully populated edns response message. Contains name compression, answers, authority, and additional records. """ @classmethod def bytes(cls): """ Bytes which are expected when encoding an instance constructed using C{kwargs} and which are expected to result in an identical instance when decoded. @return: The L{bytes} of a wire encoded message. """ return ( b'\x01\x00' # ID: 256 b'\x95' # QR: 1, OPCODE: 2, AA: 1, TC: 0, RD: 1 b'\xbf' # RA: 1, AD: 1, RCODE: 15 b'\x00\x01' # Query count b'\x00\x01' # Answer count b'\x00\x01' # Authorities count b'\x00\x02' # Additionals count # Query begins at Byte 12 b'\x07example\x03com\x00' # QNAME b'\x00\x06' # QTYPE 6 (SOA) b'\x00\x01' # QCLASS 1 (IN) # Answers b'\xc0\x0c' # RR NAME (compression ref b12) b'\x00\x06' # RR TYPE 6 (SOA) b'\x00\x01' # RR CLASS 1 (IN) b'\xff\xff\xff\xff' # RR TTL b'\x00\x27' # RDLENGTH 39 b'\x03ns1\xc0\x0c' # mname (ns1.example.com (compression ref b15) b'\x0ahostmaster\xc0\x0c' # rname (hostmaster.example.com) b'\xff\xff\xff\xfe' # Serial b'\x7f\xff\xff\xfd' # Refresh b'\x7f\xff\xff\xfc' # Retry b'\x7f\xff\xff\xfb' # Expire b'\xff\xff\xff\xfa' # Minimum # Authority b'\xc0\x0c' # RR NAME (example.com compression ref b12) b'\x00\x02' # RR TYPE 2 (NS) b'\x00\x01' # RR CLASS 1 (IN) b'\xff\xff\xff\xff' # RR TTL b'\x00\x02' # RDLENGTH b'\xc0\x29' # RDATA (ns1.example.com (compression ref b41) # Additional b'\xc0\x29' # RR NAME (ns1.example.com compression ref b41) b'\x00\x01' # RR TYPE 1 (A) b'\x00\x01' # RR CLASS 1 (IN) b'\xff\xff\xff\xff' # RR TTL b'\x00\x04' # RDLENGTH b'\x05\x06\x07\x08' # RDATA 5.6.7.8 # Additional OPT record b'\x00' # NAME (.) b'\x00\x29' # TYPE (OPT 41) b'\x04\x00' # UDP Payload Size (1024) b'\x00' # Extended RCODE b'\x03' # EDNS version b'\x80\x00' # DO: True + Z b'\x00\x00' # RDLENGTH ) @classmethod def kwargs(cls): """ Keyword constructor arguments which are expected to result in an instance which returns C{bytes} when encoded. @return: A L{dict} of keyword arguments. """ return dict( id=256, answer=1, opCode=dns.OP_STATUS, auth=1, trunc=0, recDes=1, recAv=1, rCode=15, ednsVersion=3, dnssecOK=True, authenticData=True, checkingDisabled=True, maxSize=1024, queries=[dns.Query(b'example.com', dns.SOA)], answers=[ dns.RRHeader( b'example.com', type=dns.SOA, ttl=0xffffffff, auth=True, payload=dns.Record_SOA( ttl=0xffffffff, mname=b'ns1.example.com', rname=b'hostmaster.example.com', serial=0xfffffffe, refresh=0x7ffffffd, retry=0x7ffffffc, expire=0x7ffffffb, minimum=0xfffffffa, ))], authority=[ dns.RRHeader( b'example.com', type=dns.NS, ttl=0xffffffff, auth=True, payload=dns.Record_NS( 'ns1.example.com', ttl=0xffffffff))], additional=[ dns.RRHeader( b'ns1.example.com', type=dns.A, ttl=0xffffffff, auth=True, payload=dns.Record_A( '5.6.7.8', ttl=0xffffffff))]) class MessageEDNSExtendedRCODE(object): """ An example of an EDNS message with an extended RCODE. """ @classmethod def bytes(cls): """ Bytes which are expected when encoding an instance constructed using C{kwargs} and which are expected to result in an identical instance when decoded. @return: The L{bytes} of a wire encoded message. """ return ( b'\x00\x00' b'\x00' b'\x0c' # RA: 0, Z, RCODE: 12 b'\x00\x00' b'\x00\x00' b'\x00\x00' b'\x00\x01' # 1 additionals # Additional OPT record b'\x00' b'\x00\x29' b'\x10\x00' b'\xab' # Extended RCODE: 171 b'\x00' b'\x00\x00' b'\x00\x00' ) @classmethod def kwargs(cls): """ Keyword constructor arguments which are expected to result in an instance which returns C{bytes} when encoded. @return: A L{dict} of keyword arguments. """ return dict( id=0, answer=False, opCode=dns.OP_QUERY, auth=False, trunc=False, recDes=False, recAv=False, rCode=0xabc, # Combined OPT extended RCODE + Message RCODE ednsVersion=0, dnssecOK=False, maxSize=4096, queries=[], answers=[], authority=[], additional=[], ) class MessageComparable(FancyEqMixin, FancyStrMixin, object): """ A wrapper around L{dns.Message} which is comparable so that it can be tested using some of the L{dns._EDNSMessage} tests. """ showAttributes = compareAttributes = ( 'id', 'answer', 'opCode', 'auth', 'trunc', 'recDes', 'recAv', 'rCode', 'queries', 'answers', 'authority', 'additional') def __init__(self, original): self.original = original def __getattr__(self, key): return getattr(self.original, key) def verifyConstructorArgument(testCase, cls, argName, defaultVal, altVal, attrName=None): """ Verify that an attribute has the expected default value and that a corresponding argument passed to a constructor is assigned to that attribute. @param testCase: The L{TestCase} whose assert methods will be called. @type testCase: L{unittest.TestCase} @param cls: The constructor under test. @type cls: L{type} @param argName: The name of the constructor argument under test. @type argName: L{str} @param defaultVal: The expected default value of C{attrName} / C{argName} @type defaultVal: L{object} @param altVal: A value which is different from the default. Used to test that supplied constructor arguments are actually assigned to the correct attribute. @type altVal: L{object} @param attrName: The name of the attribute under test if different from C{argName}. Defaults to C{argName} @type attrName: L{str} """ if attrName is None: attrName = argName actual = {} expected = {'defaultVal': defaultVal, 'altVal': altVal} o = cls() actual['defaultVal'] = getattr(o, attrName) o = cls(**{argName: altVal}) actual['altVal'] = getattr(o, attrName) testCase.assertEqual(expected, actual) class ConstructorTestsMixin(object): """ Helper methods for verifying default attribute values and corresponding constructor arguments. """ def _verifyConstructorArgument(self, argName, defaultVal, altVal): """ Wrap L{verifyConstructorArgument} to provide simpler interface for testing Message and _EDNSMessage constructor arguments. @param argName: The name of the constructor argument. @param defaultVal: The expected default value. @param altVal: An alternative value which is expected to be assigned to a correspondingly named attribute. """ verifyConstructorArgument(testCase=self, cls=self.messageFactory, argName=argName, defaultVal=defaultVal, altVal=altVal) def _verifyConstructorFlag(self, argName, defaultVal): """ Wrap L{verifyConstructorArgument} to provide simpler interface for testing _EDNSMessage constructor flags. @param argName: The name of the constructor flag argument @param defaultVal: The expected default value of the flag """ assert defaultVal in (True, False) verifyConstructorArgument(testCase=self, cls=self.messageFactory, argName=argName, defaultVal=defaultVal, altVal=not defaultVal,) class CommonConstructorTestsMixin(object): """ Tests for constructor arguments and their associated attributes that are common to both L{twisted.names.dns._EDNSMessage} and L{dns.Message}. TestCase classes that use this mixin must provide a C{messageFactory} method which accepts any argment supported by L{dns.Message.__init__}. TestCases must also mixin ConstructorTestsMixin which provides some custom assertions for testing constructor arguments. """ def test_id(self): """ L{dns._EDNSMessage.id} defaults to C{0} and can be overridden in the constructor. """ self._verifyConstructorArgument('id', defaultVal=0, altVal=1) def test_answer(self): """ L{dns._EDNSMessage.answer} defaults to C{False} and can be overridden in the constructor. """ self._verifyConstructorFlag('answer', defaultVal=False) def test_opCode(self): """ L{dns._EDNSMessage.opCode} defaults to L{dns.OP_QUERY} and can be overridden in the constructor. """ self._verifyConstructorArgument( 'opCode', defaultVal=dns.OP_QUERY, altVal=dns.OP_STATUS) def test_auth(self): """ L{dns._EDNSMessage.auth} defaults to C{False} and can be overridden in the constructor. """ self._verifyConstructorFlag('auth', defaultVal=False) def test_trunc(self): """ L{dns._EDNSMessage.trunc} defaults to C{False} and can be overridden in the constructor. """ self._verifyConstructorFlag('trunc', defaultVal=False) def test_recDes(self): """ L{dns._EDNSMessage.recDes} defaults to C{False} and can be overridden in the constructor. """ self._verifyConstructorFlag('recDes', defaultVal=False) def test_recAv(self): """ L{dns._EDNSMessage.recAv} defaults to C{False} and can be overridden in the constructor. """ self._verifyConstructorFlag('recAv', defaultVal=False) def test_rCode(self): """ L{dns._EDNSMessage.rCode} defaults to C{0} and can be overridden in the constructor. """ self._verifyConstructorArgument('rCode', defaultVal=0, altVal=123) def test_maxSize(self): """ L{dns._EDNSMessage.maxSize} defaults to C{512} and can be overridden in the constructor. """ self._verifyConstructorArgument('maxSize', defaultVal=512, altVal=1024) def test_queries(self): """ L{dns._EDNSMessage.queries} defaults to C{[]}. """ self.assertEqual(self.messageFactory().queries, []) def test_answers(self): """ L{dns._EDNSMessage.answers} defaults to C{[]}. """ self.assertEqual(self.messageFactory().answers, []) def test_authority(self): """ L{dns._EDNSMessage.authority} defaults to C{[]}. """ self.assertEqual(self.messageFactory().authority, []) def test_additional(self): """ L{dns._EDNSMessage.additional} defaults to C{[]}. """ self.assertEqual(self.messageFactory().additional, []) class EDNSMessageConstructorTests(ConstructorTestsMixin, CommonConstructorTestsMixin, unittest.SynchronousTestCase): """ Tests for L{twisted.names.dns._EDNSMessage} constructor arguments that are shared with L{dns.Message}. """ messageFactory = dns._EDNSMessage class MessageConstructorTests(ConstructorTestsMixin, CommonConstructorTestsMixin, unittest.SynchronousTestCase): """ Tests for L{twisted.names.dns.Message} constructor arguments that are shared with L{dns._EDNSMessage}. """ messageFactory = dns.Message class EDNSMessageSpecificsTests(ConstructorTestsMixin, unittest.SynchronousTestCase): """ Tests for L{dns._EDNSMessage}. These tests are for L{dns._EDNSMessage} APIs which are not shared with L{dns.Message}. """ messageFactory = dns._EDNSMessage def test_ednsVersion(self): """ L{dns._EDNSMessage.ednsVersion} defaults to C{0} and can be overridden in the constructor. """ self._verifyConstructorArgument( 'ednsVersion', defaultVal=0, altVal=None) def test_dnssecOK(self): """ L{dns._EDNSMessage.dnssecOK} defaults to C{False} and can be overridden in the constructor. """ self._verifyConstructorFlag('dnssecOK', defaultVal=False) def test_authenticData(self): """ L{dns._EDNSMessage.authenticData} defaults to C{False} and can be overridden in the constructor. """ self._verifyConstructorFlag('authenticData', defaultVal=False) def test_checkingDisabled(self): """ L{dns._EDNSMessage.checkingDisabled} defaults to C{False} and can be overridden in the constructor. """ self._verifyConstructorFlag('checkingDisabled', defaultVal=False) def test_queriesOverride(self): """ L{dns._EDNSMessage.queries} can be overridden in the constructor. """ msg = self.messageFactory(queries=[dns.Query(b'example.com')]) self.assertEqual( msg.queries, [dns.Query(b'example.com')]) def test_answersOverride(self): """ L{dns._EDNSMessage.answers} can be overridden in the constructor. """ msg = self.messageFactory( answers=[ dns.RRHeader( b'example.com', payload=dns.Record_A('1.2.3.4'))]) self.assertEqual( msg.answers, [dns.RRHeader(b'example.com', payload=dns.Record_A('1.2.3.4'))]) def test_authorityOverride(self): """ L{dns._EDNSMessage.authority} can be overridden in the constructor. """ msg = self.messageFactory( authority=[ dns.RRHeader( b'example.com', type=dns.SOA, payload=dns.Record_SOA())]) self.assertEqual( msg.authority, [dns.RRHeader(b'example.com', type=dns.SOA, payload=dns.Record_SOA())]) def test_additionalOverride(self): """ L{dns._EDNSMessage.authority} can be overridden in the constructor. """ msg = self.messageFactory( additional=[ dns.RRHeader( b'example.com', payload=dns.Record_A('1.2.3.4'))]) self.assertEqual( msg.additional, [dns.RRHeader(b'example.com', payload=dns.Record_A('1.2.3.4'))]) def test_reprDefaults(self): """ L{dns._EDNSMessage.__repr__} omits field values and sections which are identical to their defaults. The id field value is always shown. """ self.assertEqual( '<_EDNSMessage id=0>', repr(self.messageFactory()) ) def test_reprFlagsIfSet(self): """ L{dns._EDNSMessage.__repr__} displays flags if they are L{True}. """ m = self.messageFactory(answer=True, auth=True, trunc=True, recDes=True, recAv=True, authenticData=True, checkingDisabled=True, dnssecOK=True) self.assertEqual( '<_EDNSMessage ' 'id=0 ' 'flags=answer,auth,trunc,recDes,recAv,authenticData,' 'checkingDisabled,dnssecOK' '>', repr(m), ) def test_reprNonDefautFields(self): """ L{dns._EDNSMessage.__repr__} displays field values if they differ from their defaults. """ m = self.messageFactory(id=10, opCode=20, rCode=30, maxSize=40, ednsVersion=50) self.assertEqual( '<_EDNSMessage ' 'id=10 ' 'opCode=20 ' 'rCode=30 ' 'maxSize=40 ' 'ednsVersion=50' '>', repr(m), ) def test_reprNonDefaultSections(self): """ L{dns.Message.__repr__} displays sections which differ from their defaults. """ m = self.messageFactory() m.queries = [1, 2, 3] m.answers = [4, 5, 6] m.authority = [7, 8, 9] m.additional = [10, 11, 12] self.assertEqual( '<_EDNSMessage ' 'id=0 ' 'queries=[1, 2, 3] ' 'answers=[4, 5, 6] ' 'authority=[7, 8, 9] ' 'additional=[10, 11, 12]' '>', repr(m), ) def test_fromStrCallsMessageFactory(self): """ L{dns._EDNSMessage.fromString} calls L{dns._EDNSMessage._messageFactory} to create a new L{dns.Message} instance which is used to decode the supplied bytes. """ class FakeMessageFactory(object): """ Fake message factory. """ def fromStr(self, *args, **kwargs): """ Fake fromStr method which raises the arguments it was passed. @param args: positional arguments @param kwargs: keyword arguments """ raise RaisedArgs(args, kwargs) m = dns._EDNSMessage() m._messageFactory = FakeMessageFactory dummyBytes = object() e = self.assertRaises(RaisedArgs, m.fromStr, dummyBytes) self.assertEqual( ((dummyBytes,), {}), (e.args, e.kwargs) ) def test_fromStrCallsFromMessage(self): """ L{dns._EDNSMessage.fromString} calls L{dns._EDNSMessage._fromMessage} with a L{dns.Message} instance """ m = dns._EDNSMessage() class FakeMessageFactory(): """ Fake message factory. """ def fromStr(self, bytes): """ A noop fake version of fromStr @param bytes: the bytes to be decoded """ fakeMessage = FakeMessageFactory() m._messageFactory = lambda: fakeMessage def fakeFromMessage(*args, **kwargs): raise RaisedArgs(args, kwargs) m._fromMessage = fakeFromMessage e = self.assertRaises(RaisedArgs, m.fromStr, b'') self.assertEqual( ((fakeMessage,), {}), (e.args, e.kwargs) ) def test_toStrCallsToMessage(self): """ L{dns._EDNSMessage.toStr} calls L{dns._EDNSMessage._toMessage} """ m = dns._EDNSMessage() def fakeToMessage(*args, **kwargs): raise RaisedArgs(args, kwargs) m._toMessage = fakeToMessage e = self.assertRaises(RaisedArgs, m.toStr) self.assertEqual( ((), {}), (e.args, e.kwargs) ) def test_toStrCallsToMessageToStr(self): """ L{dns._EDNSMessage.toStr} calls C{toStr} on the message returned by L{dns._EDNSMessage._toMessage}. """ m = dns._EDNSMessage() dummyBytes = object() class FakeMessage(object): """ Fake Message """ def toStr(self): """ Fake toStr which returns dummyBytes. @return: dummyBytes """ return dummyBytes def fakeToMessage(*args, **kwargs): return FakeMessage() m._toMessage = fakeToMessage self.assertEqual( dummyBytes, m.toStr() ) class EDNSMessageEqualityTests(ComparisonTestsMixin, unittest.SynchronousTestCase): """ Tests for equality between L(dns._EDNSMessage} instances. These tests will not work with L{dns.Message} because it does not use L{twisted.python.util.FancyEqMixin}. """ messageFactory = dns._EDNSMessage def test_id(self): """ Two L{dns._EDNSMessage} instances compare equal if they have the same id. """ self.assertNormalEqualityImplementation( self.messageFactory(id=1), self.messageFactory(id=1), self.messageFactory(id=2), ) def test_answer(self): """ Two L{dns._EDNSMessage} instances compare equal if they have the same answer flag. """ self.assertNormalEqualityImplementation( self.messageFactory(answer=True), self.messageFactory(answer=True), self.messageFactory(answer=False), ) def test_opCode(self): """ Two L{dns._EDNSMessage} instances compare equal if they have the same opCode. """ self.assertNormalEqualityImplementation( self.messageFactory(opCode=dns.OP_STATUS), self.messageFactory(opCode=dns.OP_STATUS), self.messageFactory(opCode=dns.OP_INVERSE), ) def test_auth(self): """ Two L{dns._EDNSMessage} instances compare equal if they have the same auth flag. """ self.assertNormalEqualityImplementation( self.messageFactory(auth=True), self.messageFactory(auth=True), self.messageFactory(auth=False), ) def test_trunc(self): """ Two L{dns._EDNSMessage} instances compare equal if they have the same trunc flag. """ self.assertNormalEqualityImplementation( self.messageFactory(trunc=True), self.messageFactory(trunc=True), self.messageFactory(trunc=False), ) def test_recDes(self): """ Two L{dns._EDNSMessage} instances compare equal if they have the same recDes flag. """ self.assertNormalEqualityImplementation( self.messageFactory(recDes=True), self.messageFactory(recDes=True), self.messageFactory(recDes=False), ) def test_recAv(self): """ Two L{dns._EDNSMessage} instances compare equal if they have the same recAv flag. """ self.assertNormalEqualityImplementation( self.messageFactory(recAv=True), self.messageFactory(recAv=True), self.messageFactory(recAv=False), ) def test_rCode(self): """ Two L{dns._EDNSMessage} instances compare equal if they have the same rCode. """ self.assertNormalEqualityImplementation( self.messageFactory(rCode=16), self.messageFactory(rCode=16), self.messageFactory(rCode=15), ) def test_ednsVersion(self): """ Two L{dns._EDNSMessage} instances compare equal if they have the same ednsVersion. """ self.assertNormalEqualityImplementation( self.messageFactory(ednsVersion=1), self.messageFactory(ednsVersion=1), self.messageFactory(ednsVersion=None), ) def test_dnssecOK(self): """ Two L{dns._EDNSMessage} instances compare equal if they have the same dnssecOK. """ self.assertNormalEqualityImplementation( self.messageFactory(dnssecOK=True), self.messageFactory(dnssecOK=True), self.messageFactory(dnssecOK=False), ) def test_authenticData(self): """ Two L{dns._EDNSMessage} instances compare equal if they have the same authenticData flags. """ self.assertNormalEqualityImplementation( self.messageFactory(authenticData=True), self.messageFactory(authenticData=True), self.messageFactory(authenticData=False), ) def test_checkingDisabled(self): """ Two L{dns._EDNSMessage} instances compare equal if they have the same checkingDisabled flags. """ self.assertNormalEqualityImplementation( self.messageFactory(checkingDisabled=True), self.messageFactory(checkingDisabled=True), self.messageFactory(checkingDisabled=False), ) def test_maxSize(self): """ Two L{dns._EDNSMessage} instances compare equal if they have the same maxSize. """ self.assertNormalEqualityImplementation( self.messageFactory(maxSize=2048), self.messageFactory(maxSize=2048), self.messageFactory(maxSize=1024), ) def test_queries(self): """ Two L{dns._EDNSMessage} instances compare equal if they have the same queries. """ self.assertNormalEqualityImplementation( self.messageFactory(queries=[dns.Query(b'example.com')]), self.messageFactory(queries=[dns.Query(b'example.com')]), self.messageFactory(queries=[dns.Query(b'example.org')]), ) def test_answers(self): """ Two L{dns._EDNSMessage} instances compare equal if they have the same answers. """ self.assertNormalEqualityImplementation( self.messageFactory(answers=[dns.RRHeader( b'example.com', payload=dns.Record_A('1.2.3.4'))]), self.messageFactory(answers=[dns.RRHeader( b'example.com', payload=dns.Record_A('1.2.3.4'))]), self.messageFactory(answers=[dns.RRHeader( b'example.org', payload=dns.Record_A('4.3.2.1'))]), ) def test_authority(self): """ Two L{dns._EDNSMessage} instances compare equal if they have the same authority records. """ self.assertNormalEqualityImplementation( self.messageFactory(authority=[dns.RRHeader( b'example.com', type=dns.SOA, payload=dns.Record_SOA())]), self.messageFactory(authority=[dns.RRHeader( b'example.com', type=dns.SOA, payload=dns.Record_SOA())]), self.messageFactory(authority=[dns.RRHeader( b'example.org', type=dns.SOA, payload=dns.Record_SOA())]), ) def test_additional(self): """ Two L{dns._EDNSMessage} instances compare equal if they have the same additional records. """ self.assertNormalEqualityImplementation( self.messageFactory(additional=[dns.RRHeader( b'example.com', payload=dns.Record_A('1.2.3.4'))]), self.messageFactory(additional=[dns.RRHeader( b'example.com', payload=dns.Record_A('1.2.3.4'))]), self.messageFactory(additional=[dns.RRHeader( b'example.org', payload=dns.Record_A('1.2.3.4'))]), ) class StandardEncodingTestsMixin(object): """ Tests for the encoding and decoding of various standard (not EDNS) messages. These tests should work with both L{dns._EDNSMessage} and L{dns.Message}. TestCase classes that use this mixin must provide a C{messageFactory} method which accepts any argment supported by L{dns._EDNSMessage.__init__}. EDNS specific arguments may be discarded if not supported by the message class under construction. """ def test_emptyMessageEncode(self): """ An empty message can be encoded. """ self.assertEqual( self.messageFactory(**MessageEmpty.kwargs()).toStr(), MessageEmpty.bytes()) def test_emptyMessageDecode(self): """ An empty message byte sequence can be decoded. """ m = self.messageFactory() m.fromStr(MessageEmpty.bytes()) self.assertEqual(m, self.messageFactory(**MessageEmpty.kwargs())) def test_completeQueryEncode(self): """ A fully populated query message can be encoded. """ self.assertEqual( self.messageFactory(**MessageComplete.kwargs()).toStr(), MessageComplete.bytes()) def test_completeQueryDecode(self): """ A fully populated message byte string can be decoded. """ m = self.messageFactory() m.fromStr(MessageComplete.bytes()), self.assertEqual(m, self.messageFactory(**MessageComplete.kwargs())) def test_NULL(self): """ A I{NULL} record with an arbitrary payload can be encoded and decoded as part of a message. """ bytes = b''.join([dns._ord2bytes(i) for i in range(256)]) rec = dns.Record_NULL(bytes) rr = dns.RRHeader(b'testname', dns.NULL, payload=rec) msg1 = self.messageFactory() msg1.answers.append(rr) s = msg1.toStr() msg2 = self.messageFactory() msg2.fromStr(s) self.assertIsInstance(msg2.answers[0].payload, dns.Record_NULL) self.assertEqual(msg2.answers[0].payload.payload, bytes) def test_nonAuthoritativeMessageEncode(self): """ If the message C{authoritative} attribute is set to 0, the encoded bytes will have AA bit 0. """ self.assertEqual( self.messageFactory(**MessageNonAuthoritative.kwargs()).toStr(), MessageNonAuthoritative.bytes()) def test_nonAuthoritativeMessageDecode(self): """ The L{dns.RRHeader} instances created by a message from a non-authoritative message byte string are marked as not authoritative. """ m = self.messageFactory() m.fromStr(MessageNonAuthoritative.bytes()) self.assertEqual( m, self.messageFactory(**MessageNonAuthoritative.kwargs())) def test_authoritativeMessageEncode(self): """ If the message C{authoritative} attribute is set to 1, the encoded bytes will have AA bit 1. """ self.assertEqual( self.messageFactory(**MessageAuthoritative.kwargs()).toStr(), MessageAuthoritative.bytes()) def test_authoritativeMessageDecode(self): """ The message and its L{dns.RRHeader} instances created by C{decode} from an authoritative message byte string, are marked as authoritative. """ m = self.messageFactory() m.fromStr(MessageAuthoritative.bytes()) self.assertEqual( m, self.messageFactory(**MessageAuthoritative.kwargs())) def test_truncatedMessageEncode(self): """ If the message C{trunc} attribute is set to 1 the encoded bytes will have TR bit 1. """ self.assertEqual( self.messageFactory(**MessageTruncated.kwargs()).toStr(), MessageTruncated.bytes()) def test_truncatedMessageDecode(self): """ The message instance created by decoding a truncated message is marked as truncated. """ m = self.messageFactory() m.fromStr(MessageTruncated.bytes()) self.assertEqual(m, self.messageFactory(**MessageTruncated.kwargs())) class EDNSMessageStandardEncodingTests(StandardEncodingTestsMixin, unittest.SynchronousTestCase): """ Tests for the encoding and decoding of various standard (non-EDNS) messages by L{dns._EDNSMessage}. """ messageFactory = dns._EDNSMessage class MessageStandardEncodingTests(StandardEncodingTestsMixin, unittest.SynchronousTestCase): """ Tests for the encoding and decoding of various standard (non-EDNS) messages by L{dns.Message}. """ @staticmethod def messageFactory(**kwargs): """ This function adapts constructor arguments expected by _EDNSMessage.__init__ to arguments suitable for use with the Message.__init__. Also handles the fact that unlike L{dns._EDNSMessage}, L{dns.Message.__init__} does not accept queries, answers etc as arguments. Also removes any L{dns._EDNSMessage} specific arguments. @param args: The positional arguments which will be passed to L{dns.Message.__init__}. @param kwargs: The keyword arguments which will be stripped of EDNS specific arguments before being passed to L{dns.Message.__init__}. @return: An L{dns.Message} instance. """ queries = kwargs.pop('queries', []) answers = kwargs.pop('answers', []) authority = kwargs.pop('authority', []) additional = kwargs.pop('additional', []) kwargs.pop('ednsVersion', None) m = dns.Message(**kwargs) m.queries = queries m.answers = answers m.authority = authority m.additional = additional return MessageComparable(m) class EDNSMessageEDNSEncodingTests(unittest.SynchronousTestCase): """ Tests for the encoding and decoding of various EDNS messages. These test will not work with L{dns.Message}. """ messageFactory = dns._EDNSMessage def test_ednsMessageDecodeStripsOptRecords(self): """ The L(_EDNSMessage} instance created by L{dns._EDNSMessage.decode} from an EDNS query never includes OPT records in the additional section. """ m = self.messageFactory() m.fromStr(MessageEDNSQuery.bytes()) self.assertEqual(m.additional, []) def test_ednsMessageDecodeMultipleOptRecords(self): """ An L(_EDNSMessage} instance created from a byte string containing multiple I{OPT} records will discard all the C{OPT} records. C{ednsVersion} will be set to L{None}. @see: U{https://tools.ietf.org/html/rfc6891#section-6.1.1} """ m = dns.Message() m.additional = [ dns._OPTHeader(version=2), dns._OPTHeader(version=3)] ednsMessage = dns._EDNSMessage() ednsMessage.fromStr(m.toStr()) self.assertIsNone(ednsMessage.ednsVersion) def test_fromMessageCopiesSections(self): """ L{dns._EDNSMessage._fromMessage} returns an L{_EDNSMessage} instance whose queries, answers, authority and additional lists are copies (not references to) the original message lists. """ standardMessage = dns.Message() standardMessage.fromStr(MessageEDNSQuery.bytes()) ednsMessage = dns._EDNSMessage._fromMessage(standardMessage) duplicates = [] for attrName in ('queries', 'answers', 'authority', 'additional'): if (getattr(standardMessage, attrName) is getattr(ednsMessage, attrName)): duplicates.append(attrName) if duplicates: self.fail( 'Message and _EDNSMessage shared references to the following ' 'section lists after decoding: %s' % (duplicates,)) def test_toMessageCopiesSections(self): """ L{dns._EDNSMessage.toStr} makes no in place changes to the message instance. """ ednsMessage = dns._EDNSMessage(ednsVersion=1) ednsMessage.toStr() self.assertEqual(ednsMessage.additional, []) def test_optHeaderPosition(self): """ L{dns._EDNSMessage} can decode OPT records, regardless of their position in the additional records section. "The OPT RR MAY be placed anywhere within the additional data section." @see: U{https://tools.ietf.org/html/rfc6891#section-6.1.1} """ # XXX: We need an _OPTHeader.toRRHeader method. See #6779. b = BytesIO() optRecord = dns._OPTHeader(version=1) optRecord.encode(b) optRRHeader = dns.RRHeader() b.seek(0) optRRHeader.decode(b) m = dns.Message() m.additional = [optRRHeader] actualMessages = [] actualMessages.append(dns._EDNSMessage._fromMessage(m).ednsVersion) m.additional.append(dns.RRHeader(type=dns.A)) actualMessages.append( dns._EDNSMessage._fromMessage(m).ednsVersion) m.additional.insert(0, dns.RRHeader(type=dns.A)) actualMessages.append( dns._EDNSMessage._fromMessage(m).ednsVersion) self.assertEqual( [1] * 3, actualMessages ) def test_ednsDecode(self): """ The L(_EDNSMessage} instance created by L{dns._EDNSMessage.fromStr} derives its edns specific values (C{ednsVersion}, etc) from the supplied OPT record. """ m = self.messageFactory() m.fromStr(MessageEDNSComplete.bytes()) self.assertEqual(m, self.messageFactory(**MessageEDNSComplete.kwargs())) def test_ednsEncode(self): """ The L(_EDNSMessage} instance created by L{dns._EDNSMessage.toStr} encodes its edns specific values (C{ednsVersion}, etc) into an OPT record added to the additional section. """ self.assertEqual( self.messageFactory(**MessageEDNSComplete.kwargs()).toStr(), MessageEDNSComplete.bytes()) def test_extendedRcodeEncode(self): """ The L(_EDNSMessage.toStr} encodes the extended I{RCODE} (>=16) by assigning the lower 4bits to the message RCODE field and the upper 4bits to the OPT pseudo record. """ self.assertEqual( self.messageFactory(**MessageEDNSExtendedRCODE.kwargs()).toStr(), MessageEDNSExtendedRCODE.bytes()) def test_extendedRcodeDecode(self): """ The L(_EDNSMessage} instance created by L{dns._EDNSMessage.fromStr} derives RCODE from the supplied OPT record. """ m = self.messageFactory() m.fromStr(MessageEDNSExtendedRCODE.bytes()) self.assertEqual( m, self.messageFactory(**MessageEDNSExtendedRCODE.kwargs())) def test_extendedRcodeZero(self): """ Note that EXTENDED-RCODE value 0 indicates that an unextended RCODE is in use (values 0 through 15). https://tools.ietf.org/html/rfc6891#section-6.1.3 """ ednsMessage = self.messageFactory(rCode=15, ednsVersion=0) standardMessage = ednsMessage._toMessage() self.assertEqual( (15, 0), (standardMessage.rCode, standardMessage.additional[0].extendedRCODE) ) class ResponseFromMessageTests(unittest.SynchronousTestCase): """ Tests for L{dns._responseFromMessage}. """ def test_responseFromMessageResponseType(self): """ L{dns.Message._responseFromMessage} is a constructor function which generates a new I{answer} message from an existing L{dns.Message} like instance. """ request = dns.Message() response = dns._responseFromMessage(responseConstructor=dns.Message, message=request) self.assertIsNot(request, response) def test_responseType(self): """ L{dns._responseFromMessage} returns a new instance of C{cls} """ class SuppliedClass(object): id = 1 queries = [] expectedClass = dns.Message self.assertIsInstance( dns._responseFromMessage(responseConstructor=expectedClass, message=SuppliedClass()), expectedClass ) def test_responseId(self): """ L{dns._responseFromMessage} copies the C{id} attribute of the original message. """ self.assertEqual( 1234, dns._responseFromMessage(responseConstructor=dns.Message, message=dns.Message(id=1234)).id ) def test_responseAnswer(self): """ L{dns._responseFromMessage} sets the C{answer} flag to L{True} """ request = dns.Message() response = dns._responseFromMessage(responseConstructor=dns.Message, message=request) self.assertEqual( (False, True), (request.answer, response.answer) ) def test_responseQueries(self): """ L{dns._responseFromMessage} copies the C{queries} attribute of the original message. """ request = dns.Message() expectedQueries = [object(), object(), object()] request.queries = expectedQueries[:] self.assertEqual( expectedQueries, dns._responseFromMessage(responseConstructor=dns.Message, message=request).queries ) def test_responseKwargs(self): """ L{dns._responseFromMessage} accepts other C{kwargs} which are assigned to the new message before it is returned. """ self.assertEqual( 123, dns._responseFromMessage( responseConstructor=dns.Message, message=dns.Message(), rCode=123).rCode ) class Foo(object): """ An example class for use in L{dns._compactRepr} tests. It follows the pattern of initialiser settable flags, fields and sections found in L{dns.Message} and L{dns._EDNSMessage}. """ def __init__(self, field1=1, field2=2, alwaysShowField='AS', flagTrue=True, flagFalse=False, section1=None): """ Set some flags, fields and sections as public attributes. """ self.field1 = field1 self.field2 = field2 self.alwaysShowField = alwaysShowField self.flagTrue = flagTrue self.flagFalse = flagFalse if section1 is None: section1 = [] self.section1 = section1 def __repr__(self): """ Call L{dns._compactRepr} to generate a string representation. """ return dns._compactRepr( self, alwaysShow='alwaysShowField'.split(), fieldNames='field1 field2 alwaysShowField'.split(), flagNames='flagTrue flagFalse'.split(), sectionNames='section1 section2'.split() ) class CompactReprTests(unittest.SynchronousTestCase): """ Tests for L[dns._compactRepr}. """ messageFactory = Foo def test_defaults(self): """ L{dns._compactRepr} omits field values and sections which have the default value. Flags which are True are always shown. """ self.assertEqual( "<Foo alwaysShowField='AS' flags=flagTrue>", repr(self.messageFactory()) ) def test_flagsIfSet(self): """ L{dns._compactRepr} displays flags if they have a non-default value. """ m = self.messageFactory(flagTrue=True, flagFalse=True) self.assertEqual( '<Foo ' "alwaysShowField='AS' " 'flags=flagTrue,flagFalse' '>', repr(m), ) def test_nonDefautFields(self): """ L{dns._compactRepr} displays field values if they differ from their defaults. """ m = self.messageFactory(field1=10, field2=20) self.assertEqual( '<Foo ' 'field1=10 ' 'field2=20 ' "alwaysShowField='AS' " 'flags=flagTrue' '>', repr(m), ) def test_nonDefaultSections(self): """ L{dns._compactRepr} displays sections which differ from their defaults. """ m = self.messageFactory() m.section1 = [1, 1, 1] m.section2 = [2, 2, 2] self.assertEqual( '<Foo ' "alwaysShowField='AS' " 'flags=flagTrue ' 'section1=[1, 1, 1] ' 'section2=[2, 2, 2]' '>', repr(m), )
whitehorse-io/encarnia
pyenv/lib/python2.7/site-packages/twisted/names/test/test_dns.py
Python
mit
154,060
#------------------------------------------------------------------------------- # Name: Heuristic_Coeff.py # Purpose: Implements FIH algorithm found in "An Integer Linear Programming Scheme to Sanitize Sensitive Frequent Itemsets" by Kagklis et al. # Author: Vasileios Kagklis # Created: 20/03/2014 # Copyright: (c) Vasileios Kagklis #------------------------------------------------------------------------------- from __future__ import print_function from time import clock from math import ceil import cplex from cplex import SparsePair from fim import apriori import myiolib import hcba_ext from SetOp import * ################################################### def findMin(S): result = [] for i in xrange(len(S)): flag = True for j in xrange(len(S)): if i == j: continue if len(S[i]) >= len(S[j]) and S[i].issuperset(S[j]): flag = False break elif len(S[i]) < len(S[j]) and S[i].issubset(S[j]): flag = True elif len(S[i]) == len(S[j]): flag = True if flag: result.append(S[i]) if len(result) == 0: return(S) else: return(result) ################################################### def convert2frozen(rev_fd): result = [] for itemset in rev_fd: for item in itemset: if isinstance(item, float): temp = itemset - frozenset([item]) result.append(temp) return(result) ################################################### def Heuristic_Coeff_main(fname1, fname2, fname3, sup, mod_name): change_raw_data = 0 L = [] solution = None k =0 # Read dataset and identify discrete items lines, tid = myiolib.readDataset(fname3) I = hcba_ext.get_1itemsets(tid) # Calculate support count abs_supp = ceil(sup*lines-0.5) # Load F from file F = myiolib.readLargeData(fname1) # Load S from file S = minSet(myiolib.readSensitiveSet(fname2)) # Calculate the revised F start_time = clock() SS = supersets(S, F) Rev_Fd = list(set(F)-SS) rev_t = clock() - start_time Rev_Fd.sort(key = len, reverse = True) # Calculate minimal set of S sens_ind =[] for i in xrange(lines): for itemset in S: if itemset.issubset(tid[i]): sens_ind.append(i) break start_time = clock() coeffs, rem = hcba_ext.calculateCoeffs(tid, sup, sens_ind, S, F, Rev_Fd) # The initial objective => Elastic filtering cpx = cplex.Cplex() cpx.set_results_stream(None) # Add obj. sense and columns cpx.objective.set_sense(cpx.objective.sense.minimize) cpx.variables.add(obj = coeffs, lb =[0]*len(coeffs), ub=[1]*len(coeffs), types=[cpx.variables.type.integer]*len(coeffs)) # Build constraints for minimal S for itemset in S: ind = [] cur_supp = 0 for i in xrange(len(sens_ind)): if itemset.issubset(tid[sens_ind[i]]): ind.append(i) cur_supp += 1 cpx.linear_constraints.add(lin_expr = [SparsePair(ind = ind, val=[1]*len(ind))], senses=["G"], rhs=[cur_supp - abs_supp + 1], names=["c"+str(k)]) k+=1 cpx.solve() solution = map(int, cpx.solution.get_values()) # Apply sanitization for i in hcba_ext.get_indices(solution, 1): tid[sens_ind[i]] = tid[sens_ind[i]] - rem[i] change_raw_data += len(rem[i]) coeffs = None cpx = None F = None Rev_Fd = None exec_time = clock()-start_time ######----create out files-----###### out_file = open(mod_name+'_results.txt', 'w') for i in xrange(lines): k = ' '.join(sorted(tid[i])) print(k, file = out_file) out_file.close() tid = None return("Not Applicable", change_raw_data, rev_t+exec_time)
kagklis/Frequent-Itemset-Hiding-Toolbox-x86
Heuristic_Coeff.py
Python
mit
4,188
#!/usr/bin/env python """Exponential and Quaternion code for Lab 6. Course: EE 106, Fall 2015 Author: Victor Shia, 9/24/15 This Python file is a code skeleton Lab 6 which calculates the rigid body transform given a rotation / translation and computes the twist from rigid body transform. When you think you have the methods implemented correctly, you can test your code by running "python exp_quat_func.py at the command line. This code requires the NumPy and SciPy libraries and kin_func_skeleton which you should have written in lab 3. If you don't already have these installed on your personal computer, you can use the lab machines or the Ubuntu+ROS VM on the course page to complete this portion of the homework. """ import tf import rospy import sys from math import * import numpy as np from tf2_msgs.msg import TFMessage from geometry_msgs.msg import Transform, Vector3 import kin_func_skeleton as kfs def quaternion_to_exp(rot): """ Converts a quaternion vector in 3D to its corresponding omega and theta. This uses the quaternion -> exponential coordinate equation given in Lab 6 Args: rot - a (4,) nd array or 4x1 array: the quaternion vector (\vec{q}, q_o) Returns: omega - (3,) ndarray: the rotation vector theta - a scalar """ #YOUR CODE HERE theta = 2.0 * np.arccos(rot[-1]) if theta == 0: omega = np.array([0.0, 0.0, 0.0]) else: omega = ((1.0/sin(theta/2.0)) * rot[:-1]) return (omega, theta) def create_rbt(omega, theta, p): """ Creates a rigid body transform using omega, theta, and the translation component. g = [R,p; 0,1], where R = exp(omega * theta), p = trans Args: omega - (3,) ndarray : the axis you want to rotate about theta - scalar value trans - (3,) ndarray or 3x1 array: the translation component of the rigid body motion Returns: g - (4,4) ndarray : the rigid body transform """ #YOUR CODE HERE R = kfs.rotation_3d(omega, theta) g = np.array([[R[0][0], R[0][1], R[0][2], p[0]], [R[1][0], R[1][1], R[1][2], p[1]], [R[2][0], R[2][1], R[2][2], p[2]], [0, 0, 0, 1]]) return g def compute_gab(g0a,g0b): """ Creates a rigid body transform g_{ab} the converts between frame A and B given the coordinate frame A,B in relation to the origin Args: g0a - (4,4) ndarray : the rigid body transform from the origin to frame A g0b - (4,4) ndarray : the rigid body transform from the origin to frame B Returns: gab - (4,4) ndarray : the rigid body transform """ #YOUR CODE HERE gab = np.dot(np.linalg.inv(g0a),g0b) return gab def find_omega_theta(R): """ Given a rotation matrix R, finds the omega and theta such that R = exp(omega * theta) Args: R - (3,3) ndarray : the rotational component of the rigid body transform Returns: omega - (3,) ndarray : the axis you want to rotate about theta - scalar value """ #YOUR CODE HERE theta = np.arccos((np.trace(R) - 1)/2) omega = (1/(2*sin(theta)))*np.array([R[2][1] - R[1][2],R[0][2] - R[2][0],R[1][0] - R[0][1]]) return (omega, theta) def find_v(omega, theta, trans): """ Finds the linear velocity term of the twist (v,omega) given omega, theta and translation Args: omega - (3,) ndarray : the axis you want to rotate about theta - scalar value trans - (3,) ndarray of 3x1 list : the translation component of the rigid body transform Returns: v - (3,1) ndarray : the linear velocity term of the twist (v,omega) """ #YOUR CODE HERE A_1 = np.eye(3) - kfs.rotation_3d(omega, theta) #print A_1 A_1 = A_1.dot(kfs.skew_3d(omega)) #print A_1 A_2 = np.outer(omega, omega.T)*theta #print A_2 A = A_1 + A_2 #print A #print np.linalg.inv(A) v = np.dot(np.linalg.inv(A), trans) #print v return np.array([v]).T #-----------------------------Testing code-------------------------------------- #-------------(you shouldn't need to modify anything below here)---------------- def array_func_test(func_name, args, ret_desired): ret_value = func_name(*args) if not isinstance(ret_value, np.ndarray): print('[FAIL] ' + func_name.__name__ + '() returned something other than a NumPy ndarray') elif ret_value.shape != ret_desired.shape: print('[FAIL] ' + func_name.__name__ + '() returned an ndarray with incorrect dimensions') elif not np.allclose(ret_value, ret_desired, rtol=1e-3): print('[FAIL] ' + func_name.__name__ + '() returned an incorrect value') else: print('[PASS] ' + func_name.__name__ + '() returned the correct value!') def array_func_test_two_outputs(func_name, args, ret_desireds): ret_values = func_name(*args) for i in range(2): ret_value = ret_values[i] ret_desired = ret_desireds[i] if i == 0 and not isinstance(ret_value, np.ndarray): print('[FAIL] ' + func_name.__name__ + '() returned something other than a NumPy ndarray') elif i == 1 and not isinstance(ret_value, float): print('[FAIL] ' + func_name.__name__ + '() returned something other than a float') elif i == 0 and ret_value.shape != ret_desired.shape: print('[FAIL] ' + func_name.__name__ + '() returned an ndarray with incorrect dimensions') elif not np.allclose(ret_value, ret_desired, rtol=1e-3): print('[FAIL] ' + func_name.__name__ + '() returned an incorrect value') else: print('[PASS] ' + func_name.__name__ + '() returned the argument %d value!' % i) if __name__ == "__main__": print('Testing...') #Test quaternion_to_exp() arg1 = np.array([1.0, 2, 3, 0.1]) func_args = (arg1,) ret_desired = (np.array([1.005, 2.0101, 3.0151]), 2.94125) array_func_test_two_outputs(quaternion_to_exp, func_args, ret_desired) #Test create_rbt() arg1 = np.array([1.0, 2, 3]) arg2 = 2 arg3 = np.array([0.5,-0.5,1]) func_args = (arg1,arg2,arg3) ret_desired = np.array( [[ 0.4078, -0.6562, 0.6349, 0.5 ], [ 0.8384, 0.5445, 0.0242, -0.5 ], [-0.3616, 0.5224, 0.7722, 1. ], [ 0. , 0. , 0. , 1. ]]) array_func_test(create_rbt, func_args, ret_desired) #Test compute_gab(g0a,g0b) g0a = np.array( [[ 0.4078, -0.6562, 0.6349, 0.5 ], [ 0.8384, 0.5445, 0.0242, -0.5 ], [-0.3616, 0.5224, 0.7722, 1. ], [ 0. , 0. , 0. , 1. ]]) g0b = np.array( [[-0.6949, 0.7135, 0.0893, 0.5 ], [-0.192 , -0.3038, 0.9332, -0.5 ], [ 0.693 , 0.6313, 0.3481, 1. ], [ 0. , 0. , 0. , 1. ]]) func_args = (g0a, g0b) ret_desired = np.array([[-0.6949, -0.192 , 0.693 , 0. ], [ 0.7135, -0.3038, 0.6313, 0. ], [ 0.0893, 0.9332, 0.3481, 0. ], [ 0. , 0. , 0. , 1. ]]) array_func_test(compute_gab, func_args, ret_desired) #Test find_omega_theta R = np.array( [[ 0.4078, -0.6562, 0.6349 ], [ 0.8384, 0.5445, 0.0242 ], [-0.3616, 0.5224, 0.7722 ]]) func_args = (R,) ret_desired = (np.array([ 0.2673, 0.5346, 0.8018]), 1.2001156089449496) array_func_test_two_outputs(find_omega_theta, func_args, ret_desired) #Test find_v arg1 = np.array([1.0, 2, 3]) arg2 = 1 arg3 = np.array([0.5,-0.5,1]) func_args = (arg1,arg2,arg3) ret_desired = np.array([[-0.1255], [ 0.0431], [ 0.0726]]) array_func_test(find_v, func_args, ret_desired)
AravindK95/ee106b
project1/src/lab1/src/exp_quat_func.py
Python
mit
7,708
from struct import pack from sqlite3 import Binary def pts(c): return ["dd",[c.X,c.Y]] def pt4mp(c): return ["Bidd",[1,1,c.X,c.Y]] def mp(coordinates): partCount=coordinates.partCount i=0 out = ["I",[0]] while i<partCount: pt = coordinates.getPart(i) [ptrn,c]=pt4mp(pt) out[0]+=ptrn out[1][0]+=1 out[1].extend(c) i+=1 return out def lineSt(coordinates): partCount=coordinates.count i=0 out = ["I",[0]] while i<partCount: pt = coordinates[i] [ptrn,c]=pts(pt) out[0]+=ptrn out[1][0]+=1 out[1].extend(c) i+=1 return out def multiLine(coordinates): partCount=coordinates.partCount i=0 out = ["I",[0]] while i<partCount: part = coordinates.getPart(i) [ptrn,c]=lineSt(part) out[0]+="BI" out[0]+=ptrn out[1][0]+=1 out[1].extend([1,2]) out[1].extend(c) i+=1 return out def linearRing(coordinates): partCount=coordinates.count i=0 values =[0] outnum = "I" out = ["I",[0]] while i<partCount: pt = coordinates[i] if pt: [ptrn,c]=pts(pt) outnum+=ptrn values[0]+=1 values.extend(c) else: if values[0]<4: return False out[0]+=outnum out[1][0]+=1 out[1].extend(values) values =[0] outnum = "I" i+=1 if values[0]<4: return False out[0]+=outnum out[1][0]+=1 out[1].extend(values) return out def multiRing(coordinates): partCount=coordinates.partCount i=0 out = ["I",[0]] while i<partCount: part = coordinates.getPart(i) [ptrn,c]=linearRing(part) out[0]+="BI" out[0]+=ptrn out[1][0]+=1 out[1].extend([1,3]) out[1].extend(c) i+=1 return out return out def makePoint(c): values = ["<BI",1,1] [ptrn,coords] = pts(c.getPart(0)) values[0]+=ptrn values.extend(coords) return Binary(pack(*values)) def makeMultiPoint(c): values = ["<BI",1,4] [ptrn,coords]=mp(c) values[0]+=ptrn values.extend(coords) return Binary(pack(*values)) def makeMultiLineString(c): if c.partCount==1: values = ["<BI",1,2] [ptrn,coords]=lineSt(c.getPart(0)) elif c.partCount>1: values = ["<BI",1,5] [ptrn,coords]=multiLine(c) else: return False values[0]+=ptrn values.extend(coords) return Binary(pack(*values)) def makeMultiPolygon(c): if c.partCount==1: values = ["<BI",1,3] [ptrn,coords]=linearRing(c.getPart(0)) elif c.partCount>1: values = ["<BI",1,6] [ptrn,coords]=multiRing(c) else: return False values[0]+=ptrn values.extend(coords) return Binary(pack(*values)) def getWKBFunc(type,field): if type == "point": return lambda row:makePoint(row.getValue(field)) elif type == "multipoint": return lambda row: makeMultiPoint(row.getValue(field)) elif type == "polyline": return lambda row: makeMultiLineString(row.getValue(field)) elif type == "polygon": return lambda row: makeMultiPolygon(row.getValue(field))
calvinmetcalf/arcsqlite
wkb.py
Python
mit
3,451
import os from lib.base_plugin import BasePlugin from lib.paths import SteamCloudPath, SteamGamesPath class CogsPlugin(BasePlugin): Name = "Cogs" support_os = ["Windows"] def backup(self, _): _.add_folder('Data', os.path.join(SteamCloudPath, '26500'), 'remote') def restore(self, _): _.restore_folder('Data', os.path.join(SteamCloudPath, '26500'), 'remote') def detect(self): if os.path.isdir(os.path.join(SteamGamesPath, 'cogs')): return True return False
Pr0Ger/SGSB
plugins/Cogs.py
Python
mit
526
# Config.py file for motion-track.py # Display Settings debug = True # Set to False for no data display window_on = False # Set to True displays opencv windows (GUI desktop reqd) diff_window_on = False # Show OpenCV image difference window thresh_window_on = False # Show OpenCV image Threshold window SHOW_CIRCLE = True # show a circle otherwise show bounding rectancle on window CIRCLE_SIZE = 8 # diameter of circle to show motion location in window LINE_THICKNESS = 1 # thickness of bounding line in pixels WINDOW_BIGGER = 1 # Resize multiplier for Movement Status Window # if gui_window_on=True then makes opencv window bigger # Note if the window is larger than 1 then a reduced frame rate will occur # Camera Settings CAMERA_WIDTH = 320 CAMERA_HEIGHT = 240 big_w = int(CAMERA_WIDTH * WINDOW_BIGGER) big_h = int(CAMERA_HEIGHT * WINDOW_BIGGER) CAMERA_HFLIP = False CAMERA_VFLIP = True CAMERA_ROTATION=0 CAMERA_FRAMERATE = 35 FRAME_COUNTER = 1000 # Motion Tracking Settings MIN_AREA = 200 # excludes all contours less than or equal to this Area THRESHOLD_SENSITIVITY = 25 BLUR_SIZE = 10
lustigerluke/motion-track
config.py
Python
mit
1,176
import unittest import doctest import spiralx.fileproc # ----------------------------------------------------------------------------- def load_tests(loader, tests, ignore): fileprocTestSuite = unittest.TestSuite() fileprocTestSuite.addTests(doctest.DocTestSuite(spiralx.fileproc)) return fileprocTestSuite #suite = get_tests() #suite.run()
spiralx/mypy
mypy/spiralx/fileproc/__test.py
Python
mit
358
""" The MIT License (MIT) Copyright (c) 2015 Robert Hodgen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from ndb_users import users import webapp2 from google.appengine.ext import ndb import json import logging from datetime import datetime, timedelta import model import re import utilities import setup from google.appengine.api import mail class Projects(webapp2.RequestHandler): def get(self, project_id=None): """ Return a list of Projects this User has access to. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) if project_id: project_key = utilities.key_for_urlsafe_id(project_id) if not project_key: self.abort(400) project = project_key.get() if not (project and isinstance(project, model.Project)): self.abort(404) if user.email not in project.users: self.abort(401) response_object = project.json_object() else: # Query for Projects this User owns, contributes to, or may observe projects = model.Project.query(model.Project.users == user.email) response_object = [] for project in projects: response_object.append(project.json_object()) # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) def post(self): """ Create a new Project for this User. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) # Get JSON request body if not self.request.body: szelf.abort(400) request_object = json.loads(self.request.body) name = request_object.get('name') if not name: self.abort(400) new_project_key = model.Project.create_project(name) new_project = new_project_key.get() if len(request_object.keys()) > 1: # Process optional items... description = request_object.get('description') if description: new_project.description = description new_project.put() setup.default_project_labels(new_project) response_object = new_project.json_object() # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) def put(self, project_id): """ Update a Project. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) # GET JSON request body if not project_id or not self.request.body: self.abort(400) request_object = json.loads(self.request.body) project_key = utilities.key_for_urlsafe_id(project_id) if not project_key or len(request_object) < 1: self.abort(400) project = project_key.get() if not (project and isinstance(project, model.Project)): self.abort(404) if (not project.is_owner(user.email) and not project.has_contributor(user.email)): self.abort(401) # Process changes... name = request_object.get('name') if name: project.name = name description = request_object.get('description') if description: project.description = description active = request_object.get('active') if isinstance(active, bool): project.active = active project.put() response_object = project.json_object() # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) def delete(self, project_id): """ Delete this user's Project. """ response_object = {} user = users.get_current_user() if not user: # No user self.abort(401) return None # Get JSON request body if not project_id: self.abort(400) project_key = utilities.key_for_urlsafe_id(project_id) if not project_key: self.abort(400) project = project.get() if not (project and isinstance(project, model.Project)): self.abort(404) if not project.is_owner(user.email): self.abort(401) ndb.delete_multi(ndb.Query(ancestor=project_key).iter(keys_only=True)) # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) class Contributors(webapp2.RequestHandler): def post(self, project_id, contributor_email): """ Add Contributors to this Project. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) # Get JSON request body if not project_id or not contributor_email: self.abort(400) project_key = utilities.key_for_urlsafe_id(project_id) if not project_key: self.abort(400) project = project_key.get() if not (project and isinstance(project, model.Project)): self.abort(404) # new_contributor = users.User.user_for_email(contributor_email) # if not new_contributor: # self.abort(404) if not mail.is_email_valid(contributor_email): self.abort(400) if (not project.is_owner(user.email) and not project.has_contributor(user.email)): self.abort(401) project.add_contributors([contributor_email]) utilities.send_project_contributor_email(contributor_email, user, project) response_object = project.json_object() # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) def delete(self, project_id, contributor_email): """ Remove Contributors from this Project. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) # Get JSON request body if not project_id or not contributor_email: self.abort(400) project_key = utilities.key_for_urlsafe_id(project_id) if not project_key: self.abort(400) project = project_key.get() if not (project and isinstance(project, model.Project)): self.abort(404) if not project.is_owner(user.email): self.abort(401) project.remove_contributors([contributor_email]) response_object = project.json_object() # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) class TimeRecords(webapp2.RequestHandler): def get(self, project_id, time_record_id=None): """ List the Time Records associated with a Project. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) if not project_id: self.abort(400) project_key = utilities.key_for_urlsafe_id(project_id) project = project_key.get() if not (project and isinstance(project, model.Project)): self.abort(404) if user.email not in project.users: self.abort(401) if time_record_id: # Give a specific Time Record time_record_key = utilities.key_for_urlsafe_id(time_record_id) if not time_record_key or (project_key != time_record_key.parent()): self.abort(400) time_record = time_record_key.get() if not (time_record or isinstance(time_record, model.TimeRecord)): self.abort(404) response_object = time_record.json_object() else: if self.request.GET.get('cursor'): # Cursor-based request cursor = ndb.Cursor(urlsafe=self.request.GET.get('cursor')) time_records, next_cursor, more = model.TimeRecord.query( ancestor=project_key).order(-model.TimeRecord.created)\ .fetch_page(15, start_cursor=cursor) response_object = [] for time_record in time_records: response_object.append(time_record.json_object()) if more: self.response.headers.add('X-Cursor', next_cursor.urlsafe()) else: # List all Time Records time_records, next_cursor, more = model.TimeRecord.query( ancestor=project_key).order(-model.TimeRecord.created)\ .fetch_page(15) response_object = [] for time_record in time_records: response_object.append(time_record.json_object()) if more: self.response.headers.add('X-Cursor', next_cursor.urlsafe()) # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) def post(self, project_id): """ Create a new Time Record associated with this Project. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) if not project_id: self.abort(400) project_key = utilities.key_for_urlsafe_id(project_id) if not project_key: self.abort(400) project = project_key.get() if not (project and isinstance(project, model.Project)): self.abort(404) if ((user.email not in project.contributors) and not project.is_owner(user.email)): self.abort(401) request_object = {} if self.request.body: request_object = json.loads(self.request.body) completed = request_object.get('completed') new_time_record_key = model.TimeRecord.create_time_record( project_key, user.email, completed=request_object.get('completed'), name=request_object.get('name')) else: new_time_record_key = model.TimeRecord.create_time_record( project_key, user.email) new_time_record = new_time_record_key.get() response_object = new_time_record.json_object() # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) def put(self, project_id, time_record_id): """ Update the Time Record. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) if not project_id or not time_record_id or not self.request.body: self.abort(400) request_object = json.loads(self.request.body) project_key = utilities.key_for_urlsafe_id(project_id) time_record_key = utilities.key_for_urlsafe_id(time_record_id) if (not project_key or not time_record_key or (project_key != time_record_key.parent())): self.abort(400) project = project_key.get() time_record = time_record_key.get() if (not (project and isinstance(project, model.Project)) or not (time_record and isinstance(time_record, model.TimeRecord))): self.abort(404) if ((user.email not in project.contributors) and not project.is_owner(user.email)): self.abort(401) # Process optional items... name = request_object.get('name') if name: time_record.name = name project.put() end = request_object.get('end') time_record.put() # Check `end` after updating the Project and Time Record; # avoids a bug whereby the Project's original `completed` time is saved. if end: if end is True: time_record.complete_time_record() response_object = time_record.json_object() # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) class Comments(webapp2.RequestHandler): def get(self, project_id, parent_type=None, parent_id=None): response_object = {} user = users.get_current_user() if not user: self.abort(401) if not project_id: self.abort(400) project_key = utilities.key_for_urlsafe_id(project_id) if not project_key: self.abort(400) project = project_key.get() if not (project and isinstance(project, model.Project)): self.abort(404) if parent_id: # Fetch by Parent ID if parent_type == 'milestones': # Milestones milestone = model.Milestone.for_number(project_key, int(parent_id)) if not milestone: self.abort(404) parent_key = milestone.key else: # assume other... parent_key = utilities.key_for_urlsafe_id(parent_id) if not parent_key or (project_key != parent_key.parent()): self.abort(400) parent = parent_key.get() if not parent and not isinstance(parent, model.TimeRecord): self.abort(404) comments = model.Comment.query(ancestor=parent_key) response_object = [] for comment in comments: response_object.append(comment.json_object()) else: # Rely upon Project comments = model.Comment.query(ancestor=project_key) response_object = [] for comment in comments: response_object.append(comment.json_object()) # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) def post(self, project_id, parent_type=None, parent_id=None): """ Create a new Comment in the specified Project, bound to another object (either a Time Record or a Milestone. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) # Get JSON request body if not project_id or not self.request.body: self.abort(400) request_object = json.loads(self.request.body) comment_content = request_object.get('comment') if not comment_content: self.abort(400) project_key = utilities.key_for_urlsafe_id(project_id) if not project_key: self.abort(400) project = project_key.get() if not (project and isinstance(project, model.Project)): self.abort(404) if ((user.email not in project.contributors) and not project.is_owner(user.email)): self.abort(401) if parent_id: # Create with a Object other than the Project as this Comment's parent if parent_type == 'milestones': # Milestones milestone = model.Milestone.for_number(project_key, int(parent_id)) if not milestone: self.abort(404) parent_key = milestone.key else: # assume other... parent_key = utilities.key_for_urlsafe_id(parent_id) if (not parent_key or (project_key != parent_key.parent())): self.abort(400) parent = parent_key.get() if not (parent and isinstance(parent, model.TimeRecord)): self.abort(404) # Create with `Project` and `Parent` new_comment_key = model.Comment.create_comment( comment_content, parent_key, project_key, user.email) comment = new_comment_key.get() response_object = comment.json_object() else: # Create with `Project` as parent new_comment_key = model.Comment.create_comment( comment_content, project_key, project_key, user.email) comment = new_comment_key.get() response_object = comment.json_object() # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) def put(self, project_id, comment_id): """ Update a Comment. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) # Get JSON request body if not project_id or not comment_id or not self.request.body: self.abort(400) project_key = utilities.key_for_urlsafe_id(project_id) comment_key = utilities.key_for_urlsafe_id(comment_id) request_object = json.loads(self.request.body) comment_content = request_object.get('comment') if (not project_key or not comment_key or not comment_content or (project_key not in comment_key.parent())): # TODO: Test this! self.abort(400) project = project_key.get() comment = comment_key.get() if (not (project and isinstance(project, model.Project)) or not (comment and isinstance(comment, model.Comment))): self.abort(404) if ((user.email not in project.contributors) and not project.is_owner(user.email)): self.abort(401) # if comment.project != project_key: # Replaced by check above # self.abort(409) comment.comment = comment_content comment.put() response_object = comment.json_object() # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) def delete(self, project_id, comment_id): """ Delete a Comment. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) if not project_id or not comment_id: self.abort(400) project_key = utilities.key_for_urlsafe_id(project_id) comment_key = utilities.key_for_urlsafe_id(comment_id) if (not project_key or not comment_key or (project_key not in comment_key.parent())): # TODO: Test this! self.abort(400) project = project_key.get() comment = comment_key.get() if (not (project and isinstance(project, model.Project)) or not (comment and isinstance(comment, model.Comment))): self.abort(404) comment_key.delete() # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) class Milestones(webapp2.RequestHandler): def get(self, project_id, milestone_id=None): """ List the Milestones associated with a Project. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) if not project_id: self.abort(400) project_key = utilities.key_for_urlsafe_id(project_id) if not project_key: self.abort(400) project = project_key.get() if not (project and isinstance(project, model.Project)): self.abort(404) if user.email not in project.users: self.abort(401) if milestone_id: # Give a specific Milestone milestone = model.Milestone.for_number(project_key, int(milestone_id)) if not milestone: self.abort(404) response_object = milestone.json_object() else: # Check if we're filtering... label_ids = self.request.GET.getall('label') open_str = self.request.GET.get('open') filters = [] if len(label_ids) > 0 or open_str is not None: # Use filters open_bool = utilities.str_to_bool(open_str, allow_none=True) if open_bool is True or open_bool is False: filters.append(model.Milestone.open == open_bool) for label_id in label_ids: filters.append(model.Milestone.labels == ndb.Key( model.Label, int(label_id), parent=project_key)) query = model.Milestone.query( ndb.AND(*filters), ancestor=project_key).order( -model.Milestone.created) else: # No filters query = model.Milestone.query( ancestor=project_key).order(-model.Milestone.created) if self.request.GET.get('cursor'): # Cursor-based request cursor = ndb.Cursor(urlsafe=self.request.GET.get('cursor')) milestones, next_cursor, more = query.fetch_page( 15, start_cursor=cursor) response_object = [] for milestone in milestones: response_object.append(milestone.json_object()) if more: self.response.headers.add('X-Cursor', next_cursor.urlsafe()) else: # List all Milestones milestones, next_cursor, more = query.fetch_page(15) response_object = [] for milestone in milestones: response_object.append(milestone.json_object()) if more: self.response.headers.add('X-Cursor', next_cursor.urlsafe()) # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) def post(self, project_id): """ Create a new Milestone associated with this Project. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) # Get JSON request body if not project_id or not self.request.body: self.abort(400) request_object = json.loads(self.request.body) project_key = utilities.key_for_urlsafe_id(project_id) name = request_object.get('name') if not project_key or not name: self.abort(400) project = project_key.get() if not (project and isinstance(project, model.Project)): self.abort(404) if ((user.email not in project.contributors) and not project.is_owner(user.email)): self.abort(401) new_milestone_key = model.Milestone.create_milestone( name, project_key, user.email) new_milestone = new_milestone_key.get() if len(request_object) > 1: # Process optional items... description = request_object.get('description') if description: new_milestone.description = description labels = request_object.get('labels') if isinstance(labels, list): for label_key_id in labels: label_key = ndb.Key(urlsafe=label_key_id) new_milestone.labels.append(label_key) new_milestone.put() response_object = new_milestone.json_object() # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) def put(self, project_id, milestone_id): """ Update a Milestone. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) if not project_id or not milestone_id or not self.request.body: self.abort(400) project_key = utilities.key_for_urlsafe_id(project_id) request_object = json.loads(self.request.body) milestone = model.Milestone.for_number(project_key, int(milestone_id)) if not project_key: self.abort(400) project = project_key.get() if (not (project and isinstance(project, model.Project)) or not milestone): self.abort(404) if ((user.email not in project.contributors) and not project.is_owner(user.email)): self.abort(401) # Process optional items... if len(request_object) > 0: name = request_object.get('name') if name: milestone.name = name description = request_object.get('description') if description: milestone.description = description open = request_object.get('open') if open is not None: milestone.open = bool(open) # labels = request_object.get('labels') # if isinstance(labels, list): # for label_key_id in labels: # label_key = ndb.Key(urlsafe=label_key_id) # new_milestone.labels.append(label_key) milestone.put() response_object = milestone.json_object() # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) @ndb.transactional(xg=True) def delete(self, project_id, milestone_id): """ Delete a Milestone. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) if not project_id or not milestone_id: self.abort(400) project_key = utilities.key_for_urlsafe_id(project_id) if not project_key: self.abort(400) project = project_key.get() milestone = model.Milestone.for_number(project_key, int(milestone_id)) if (not (project and isinstance(project, model.Project)) or not milestone): self.abort(404) if ((user.email not in project.contributors) and not project.is_owner(user.email)): self.abort(401) # Get all Comments associated with this Milestone comments = model.Comment.query(ancestor=milestone_key) for comment in comments: comment.key.delete() milestone_key.delete() # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) class Labels(webapp2.RequestHandler): def get(self, project_id, milestone_id=None): """ List the Labels associated with this Project. """ response_array = [] user = users.get_current_user() if not user: self.abort(401) # Try getting the associated Project project_key = utilities.key_for_urlsafe_id(project_id) if not project_key: self.abort(400) project = project_key.get() if not project or not isinstance(project, model.Project): self.abort(404) if user.email not in project.users: self.abort(401) if milestone_id: # Return all Labels assigned to this Milestone milestone = model.Milestone.for_number(project_key, int(milestone_id)) if not milestone: self.abort(404) label_keys = milestone.labels for label_key in label_keys: label = label_key.get() if label: response_array.append(label.json_object()) else: # Query for Projects this User owns, contributes to, or may observe labels = model.Label.query(ancestor=project.key) for label in labels: response_array.append(label.json_object()) # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_array)) def post(self, project_id, milestone_id=None): """ creates a Label associated with this Project. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) # Try getting the associated Project project_key = utilities.key_for_urlsafe_id(project_id) project = project_key.get() if not project or not self.request.body: self.abort(400) request_object = json.loads(self.request.body) label_id = request_object.get('label_id') if milestone_id and label_id: # Add an existing Label to a Milestone label_key = utilities.key_for_urlsafe_id(label_id) if not label_key: self.abort(400) milestone = model.Milestone.for_number(project_key, int(milestone_id)) label = label_key.get() if not milestone or not (label and isinstance(label, model.Label)): self.abort(404) milestone.labels.append(label_key) milestone.put() response_object = label.json_object() else: # Create a new Label name = request_object.get('name') color = request_object.get('color') if not name or not color: self.abort(400) color_pattern = r'^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$' if not re.match(color_pattern, color): self.abort(400) if ((user.email not in project.contributors) and not project.is_owner(user.email)): self.abort(401) new_label = model.Label.create_label(name, color, project.key) new_label = new_label.get() response_object = new_label.json_object() # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) def put(self, project_id, label_id): """ Update a Label associated with this Project. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) if not project_id or not label_id or not self.request.body: self.abort(400) project_key = utilities.key_for_urlsafe_id(project_id) label_key = utilities.key_for_urlsafe_id(label_id) request_object = json.loads(self.request.body) if (not project_key or not label_key or (project_key != label_key.parent())): self.abort(400) project = project_key.get() label = label_key.get() if (not (project and isinstance(project, model.Project)) or not (label and isinstance(label, model.Label))): self.abort(404) if ((user.email not in project.contributors) and not project.is_owner(user.email)): self.abort(401) # Process optional items... if len(request_object) > 0: name = request_object.get('name') if name: label.name = name color = request_object.get('color') if color: label.color = color label.put() response_object = label.json_object() # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) def delete(self, project_id, label_id, milestone_id=None,): """ Deletes a Label associated with this Project. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) # Try getting the associated Label... if not project_id or not label_id: self.abort(400) project_key = utilities.key_for_urlsafe_id(project_id) label_key = utilities.key_for_urlsafe_id(label_id) if (not project_key or not label_key or (project_key != label_key.parent())): self.abort(400) project = project_key.get() label = label_key.get() if (not (project and isinstance(project, model.Project)) or not (label and isinstance(label, model.Label)) or (project.key != label.key.parent())): self.abort(404) if ((user.email not in project.contributors) and not project.is_owner(user.email)): self.abort(401) if milestone_id: # Delete a label only from a Milestone's `labels` array milestone = model.Milestone.for_number(project_key, int(milestone_id)) if not milestone or (project.key != label.key.parent()): self.abort(404) if label_key in milestone.labels: milestone.labels.remove(label_key) milestone.put() else: # Delete an entire label label.delete_label() # Send response self.response.content_type = 'application/json' self.response.out.write(json.dumps(response_object)) app = webapp2.WSGIApplication([ webapp2.Route( '/api/v2/projects', handler=Projects, methods=['GET', 'POST'] ), webapp2.Route( '/api/v2/projects/<project_id:([a-zA-Z0-9-_]+)>', handler=Projects, methods=['GET', 'PUT', 'DELETE'] ), webapp2.Route( '/api/v2/projects/<project_id:([a-zA-Z0-9-_]+)>/contributors/<contributor_email>', handler=Contributors, methods=['POST', 'DELETE'] ), webapp2.Route( '/api/v2/projects/<project_id:([a-zA-Z0-9-_]+)>/time-records', handler=TimeRecords, methods=['GET', 'POST'] ), webapp2.Route( '/api/v2/projects/<project_id:([a-zA-Z0-9-_]+)>/time-records/<time_record_id:([a-zA-Z0-9-_]+)>', handler=TimeRecords, methods=['GET', 'PUT', 'DELETE'] ), webapp2.Route( '/api/v2/projects/<project_id:([a-zA-Z0-9-_]+)>/<parent_type:(time-records|milestones)>/<parent_id:([a-zA-Z0-9-_]+)>/comments', handler=Comments, methods=['GET', 'POST'] ), webapp2.Route( '/api/v2/projects/<project_id:([a-zA-Z0-9-_]+)>/comments', handler=Comments, methods=['GET', 'POST'] ), webapp2.Route( '/api/v2/projects/<project_id:([a-zA-Z0-9-_]+)>/comments/<comment_id:([a-zA-Z0-9-_]+)>', handler=Comments, methods=['PUT', 'DELETE'] ), webapp2.Route( '/api/v2/projects/<project_id:([a-zA-Z0-9-_]+)>/milestones', handler=Milestones, methods=['GET', 'POST'] ), webapp2.Route( '/api/v2/projects/<project_id:([a-zA-Z0-9-_]+)>/milestones/<milestone_id:([a-zA-Z0-9-_]+)>', handler=Milestones, methods=['GET', 'PUT', 'DELETE'] ), webapp2.Route( '/api/v2/projects/<project_id:([a-zA-Z0-9-_]+)>/labels', handler=Labels, methods=['GET', 'POST'] ), webapp2.Route( '/api/v2/projects/<project_id:([a-zA-Z0-9-_]+)>/labels/<label_id:([a-zA-Z0-9-_]+)>', handler=Labels, methods=['PUT', 'DELETE'] ), webapp2.Route( '/api/v2/projects/<project_id:([a-zA-Z0-9-_]+)>/milestones/<milestone_id:([a-zA-Z0-9-_]+)>/labels', handler=Labels, methods=['GET', 'POST'] ), webapp2.Route( '/api/v2/projects/<project_id:([a-zA-Z0-9-_]+)>/milestones/<milestone_id:([a-zA-Z0-9-_]+)>/labels/<label_id:([a-zA-Z0-9-_]+)>', handler=Labels, methods=['DELETE'] ) ]) def error_handler_unauthorized(request, response, exception): """ HTTP/1.1 401 Unauthorized """ logging.exception(exception) response.content_type = 'application/json' response.set_status(401) response.write(json.dumps({ 'status': 401, 'message': 'HTTP/1.1 401 Unauthorized' })) def error_handler_server_error(request, response, exception): """ HTTP/1.1 500 Internal Server Error """ logging.exception(exception) response.content_type = 'application/json' response.set_status(500) response.write(json.dumps({ 'status': 500, 'message': 'HTTP/1.1 500 Internal Server Error' })) app.error_handlers[401] = error_handler_unauthorized app.error_handlers[500] = error_handler_server_error
roberthodgen/thought-jot
src/api_v2.py
Python
mit
37,593
import warnings from apification.utils import Noninstantiable, NoninstantiableMeta def test_noninstantiable(): e, o = None, None try: o = Noninstantiable() except TypeError as e: pass assert o is None assert isinstance(e, TypeError) def test_noninstantiable_keyword_self_check_invalid(): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") class C(Noninstantiable): def func(self, a, b=1): pass assert len(w) == 1 assert issubclass(w[0].category, SyntaxWarning) assert issubclass(C, Noninstantiable) def test_noninstantiable_keyword_self_check_valid(): C = None with warnings.catch_warnings(record=True) as w: class C(Noninstantiable): def func(cls, self, b=1): # self as non first argument is allowed for whatever reasons pass assert not w assert issubclass(C, Noninstantiable) def test_noninstantiable_classmethods(): class A(Noninstantiable): def a(cls): return cls assert A.a() is A def test_noninstantiable_keyword_self_check_suppression(): C = None class C(Noninstantiable): _allow_self_as_first_arg = True def func(self, a, b=1): pass assert issubclass(C, Noninstantiable) def test_noninstantable_inheritance(): class A(object): _allow_self_as_first_arg = True e = None try: class B(A): __metaclass__ = NoninstantiableMeta def a(self): pass except TypeError as e: pass assert e is None
Quantify-world/apification
src/apification/utils/tests/test_noninstantiable.py
Python
mit
1,632
# Functions to download yesterday's races and associated raceforms from host import configparser import requests import re import sys import time import pymongo import random from datetime import datetime, timedelta from hracing.db import parse_racesheet from hracing.db import mongo_insert_race from hracing.tools import delay_scraping from hracing.tools import shuffle_ids def download_list_of_races(header,pastdays=3,datestr=None): """ Fetch a list of all raceIDs and raceURLs listed on host for a given day. Date is selected either as: a) pastdays (e.g. pastdays=1 means yesterday). OR b) by specifying a datestr of the format YYYY-MM-DD. Default is to download races from THREE DAYS AGO, which is useful for data-base building since this avoids unfinished US/CAN races Returns a lists of raceids and a lists of raceid_urls, nested in a list of race-locations""" # Compose URL if datestr == None: d = datetime.today()-timedelta(days=int(pastdays)) datestr = d.strftime('%Y-%m-%d') yesterdayurl = '/races?date=' + datestr baseurl = 'https://' + header['host'] url = baseurl + yesterdayurl # Actual download tpage=requests.get(url) #Console feedback print("Time: " + d.strftime(('%Y-%m-%d-%H-%M'))) print("Import race IDs for " + datestr) print("From " + url) #Get list of race-locations (TR) tr_urls_raw=re.split('\<div class\=\"dayHeader\"\>',tpage.text) tr_urls=re.findall( '\<div class\=\"meetingRaces\" ' 'data-url\=\"(/meetings/meeting\?id\=\d+)\">', tr_urls_raw[1]) # Loop through race-locations, get raceIDs and urls raceid_urls=[] raceids=[] for tr_url in tr_urls: url=baseurl+tr_url temp_race=requests.get(url) raceid_urls.extend( re.findall( '\<li\sclass\=\"raceli\s*status_.*\s*clearfix\"\s*data-url\=\"' '(\/race\?id\=\d*\&country\=.+\&track\=.*\&date=\d\d\d\d-\d\d-\d\d)\"', temp_race.text)) raceids.extend( re.findall( '\<li\sclass\=\"raceli\s*status_.*\s*clearfix\"\s*data-url\=\"' '\/race\?id\=(\d*)\&country\=.+\&track\=.*\&date=\d\d\d\d-\d\d-\d\d\"', temp_race.text)) print("Finished importing raceIDs: " + d.strftime(('%Y-%m-%d-%H-%M'))) return raceids, raceid_urls def scrape_races(raceids,raceid_urls,header,payload): """ Fetch a list of all races from host for a given day. Date is selected either as: a) pastdays (e.g. pastdays=1 means yesterday). OR b) by specifying a datestr of the format YYYY-MM-DD. Default is to download races from TWO DAYS AGO, which is useful for data-base building since this avoids US/CAN races are not finished Return a list of raceids and raceid_urls, which are clustered according to race-location""" baseurl='https://'+header['host'] race_min_dur=40 # minimum time(s)/race download to avoid getting kicked form_min_dur=10 # minimum time(s)/form download to avoid getting kicked reconnect_dur=500 # minimum time ind s to wait before reconnecting after losing connection d=datetime.today() a=time.monotonic() tries=1 #Shuffle order of races raceids,raceid_urls=shuffle_ids(raceids,raceid_urls) #Open new session... with requests.Session() as s: p = s.post(baseurl+'/auth/validatepostajax', headers = header, data=payload) #For each race location... for (i, raceid_url) in enumerate(raceid_urls): if not re.search('"login":true',p.text): with requests.Session() as s: p = s.post(baseurl+'/auth/validatepostajax', headers = header, data=payload) try: #For each single race... print("Start downloading race_ID: "+raceids[i]+ " ("+str(i) +"/"+str(len(raceid_urls))+")") #Check current time start_time=time.monotonic() #Get current racesheet racesheet=s.get(baseurl+raceid_url, headers = header, cookies=s.cookies) #Get horseforms urls for that race horseform_urls=(re.findall("window.open\(\'(.+?)', \'Formguide\'", racesheet.text)) forms=[] #Get horseforms-sheets for that race for (k, horseform_url) in enumerate(horseform_urls): start_time_2=time.monotonic() forms.append(s.get(baseurl+horseform_url, headers = header, cookies=s.cookies)) delay_scraping(start_time_2,form_min_dur) # Try parsing current race and add to mogodb. If something fails # Save race as .txt in folder for troubleshooting. # UNCOMMENT TRY/EXCEPT WHEN UP AND RUNNING #try: race=parse_racesheet(racesheet,forms) mongo_insert_race(race) # except Exception as e: # #Save raw html text to file for debugging purposes, overwrite every time # errordump='../hracing_private/failed_parsing/' # rawtextFilename=errordump+str(raceids[i][j])+'.txt' # print('Error when parsing race_ID: '+str(raceids[i][j])+'. Page saved in '+errordump) # print('Error msg for '+str(raceids[i][j])+': \n'+str(e)) # # with open(rawtextFilename, 'wb') as text_file: # text_file.write(racesheet.content) delay_scraping(start_time,race_min_dur)# Slow scraping to avoid getting kicked from server. # Print current runtime, current race, and number of forms extracted print("Finished: " +str(time.monotonic()-a)) # +" n forms: "+str(len(curr_forms))) #Exception of Request except requests.exceptions.RequestException as e: print(e) tries=tries+1 time.sleep(reconnect_dur) # wait ten minutes before next try print("Download exception, trying to continue in 10 mins" +d.strftime('%Y-%m-%d-%H-%M')) if tries > 10: print(str(tries) + "Download exceptions, exiting loop") break print("Finished: Download race xmls: " + d.strftime('%Y-%m-%d-%H-%M')) def get_races_IDs_not_in_db(raceids, raceid_urls): client = pymongo.MongoClient() db = client.races race_IDs_db=[] for race in db.races.find({},{'race_ID':1, '_id': 0}): race_IDs_db.append(race['race_ID']) race_zip=zip(raceids,raceid_urls) filtered_race_zip = filter(lambda x: int(x[0]) not in race_IDs_db,race_zip) novel_raceids,novel_raceid_urls =zip(*filtered_race_zip) return list(novel_raceids), list(novel_raceid_urls) def main(): # get scraping target and login info from config file configFile='../hracing_private/scraping_payload.ini' pageConfig = configparser.ConfigParser() pageConfig.read(configFile) header=dict(pageConfig['header']) payload=dict(pageConfig['payload']) raceids, raceid_urls = download_list_of_races(header) filtered_raceids, filtered_raceid_urls = get_races_IDs_not_in_db(raceids,raceid_urls) scrape_races(filtered_raceids, filtered_raceid_urls, header, payload) if __name__ == "__main__": main()
mzunhammer/hracing
hracing/scrape.py
Python
mit
7,747
#!/usr/bin/env python from algorithms.sorting.selection_sort import * from __prototype__ import * if __name__ == '__main__': test_all(selection_sort)
pymber/algorithms
tests/run-test-sort-selection.py
Python
mit
154