text
stringlengths 6
947k
| repo_name
stringlengths 5
100
| path
stringlengths 4
231
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 6
947k
| score
float64 0
0.34
|
---|---|---|---|---|---|---|
# Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory
# 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.
import binascii
from castellan.common.objects import symmetric_key as key
import mock
from oslo_concurrency import processutils
import uuid
from nova.tests.unit.volume.encryptors import test_cryptsetup
from nova.volume.encryptors import luks
class LuksEncryptorTestCase(test_cryptsetup.CryptsetupEncryptorTestCase):
def _create(self, connection_info):
return luks.LuksEncryptor(connection_info)
@mock.patch('nova.utils.execute')
def test_is_luks(self, mock_execute):
luks.is_luks(self.dev_path)
mock_execute.assert_has_calls([
mock.call('cryptsetup', 'isLuks', '--verbose', self.dev_path,
run_as_root=True, check_exit_code=True),
], any_order=False)
self.assertEqual(1, mock_execute.call_count)
@mock.patch('nova.volume.encryptors.luks.LOG')
@mock.patch('nova.utils.execute')
def test_is_luks_with_error(self, mock_execute, mock_log):
error_msg = "Device %s is not a valid LUKS device." % self.dev_path
mock_execute.side_effect = \
processutils.ProcessExecutionError(exit_code=1,
stderr=error_msg)
luks.is_luks(self.dev_path)
mock_execute.assert_has_calls([
mock.call('cryptsetup', 'isLuks', '--verbose', self.dev_path,
run_as_root=True, check_exit_code=True),
])
self.assertEqual(1, mock_execute.call_count)
self.assertEqual(1, mock_log.warning.call_count) # warning logged
@mock.patch('nova.utils.execute')
def test__format_volume(self, mock_execute):
self.encryptor._format_volume("passphrase")
mock_execute.assert_has_calls([
mock.call('cryptsetup', '--batch-mode', 'luksFormat',
'--key-file=-', self.dev_path,
process_input='passphrase',
run_as_root=True, check_exit_code=True, attempts=3),
])
self.assertEqual(1, mock_execute.call_count)
@mock.patch('nova.utils.execute')
def test__open_volume(self, mock_execute):
self.encryptor._open_volume("passphrase")
mock_execute.assert_has_calls([
mock.call('cryptsetup', 'luksOpen', '--key-file=-', self.dev_path,
self.dev_name, process_input='passphrase',
run_as_root=True, check_exit_code=True),
])
self.assertEqual(1, mock_execute.call_count)
@mock.patch('nova.utils.execute')
def test_attach_volume(self, mock_execute):
fake_key = uuid.uuid4().hex
self.encryptor._get_key = mock.MagicMock()
self.encryptor._get_key.return_value = test_cryptsetup.fake__get_key(
None, fake_key)
self.encryptor.attach_volume(None)
mock_execute.assert_has_calls([
mock.call('cryptsetup', 'luksOpen', '--key-file=-', self.dev_path,
self.dev_name, process_input=fake_key,
run_as_root=True, check_exit_code=True),
mock.call('ln', '--symbolic', '--force',
'/dev/mapper/%s' % self.dev_name, self.symlink_path,
run_as_root=True, check_exit_code=True),
])
self.assertEqual(2, mock_execute.call_count)
@mock.patch('nova.utils.execute')
def test_attach_volume_not_formatted(self, mock_execute):
fake_key = uuid.uuid4().hex
self.encryptor._get_key = mock.MagicMock()
self.encryptor._get_key.return_value = test_cryptsetup.fake__get_key(
None, fake_key)
mock_execute.side_effect = [
processutils.ProcessExecutionError(exit_code=1), # luksOpen
processutils.ProcessExecutionError(exit_code=1), # isLuks
mock.DEFAULT, # luksFormat
mock.DEFAULT, # luksOpen
mock.DEFAULT, # ln
]
self.encryptor.attach_volume(None)
mock_execute.assert_has_calls([
mock.call('cryptsetup', 'luksOpen', '--key-file=-', self.dev_path,
self.dev_name, process_input=fake_key,
run_as_root=True, check_exit_code=True),
mock.call('cryptsetup', 'isLuks', '--verbose', self.dev_path,
run_as_root=True, check_exit_code=True),
mock.call('cryptsetup', '--batch-mode', 'luksFormat',
'--key-file=-', self.dev_path, process_input=fake_key,
run_as_root=True, check_exit_code=True, attempts=3),
mock.call('cryptsetup', 'luksOpen', '--key-file=-', self.dev_path,
self.dev_name, process_input=fake_key,
run_as_root=True, check_exit_code=True),
mock.call('ln', '--symbolic', '--force',
'/dev/mapper/%s' % self.dev_name, self.symlink_path,
run_as_root=True, check_exit_code=True),
], any_order=False)
self.assertEqual(5, mock_execute.call_count)
@mock.patch('nova.utils.execute')
def test_attach_volume_fail(self, mock_execute):
fake_key = uuid.uuid4().hex
self.encryptor._get_key = mock.MagicMock()
self.encryptor._get_key.return_value = test_cryptsetup.fake__get_key(
None, fake_key)
mock_execute.side_effect = [
processutils.ProcessExecutionError(exit_code=1), # luksOpen
mock.DEFAULT, # isLuks
]
self.assertRaises(processutils.ProcessExecutionError,
self.encryptor.attach_volume, None)
mock_execute.assert_has_calls([
mock.call('cryptsetup', 'luksOpen', '--key-file=-', self.dev_path,
self.dev_name, process_input=fake_key,
run_as_root=True, check_exit_code=True),
mock.call('cryptsetup', 'isLuks', '--verbose', self.dev_path,
run_as_root=True, check_exit_code=True),
], any_order=False)
self.assertEqual(2, mock_execute.call_count)
@mock.patch('nova.utils.execute')
def test__close_volume(self, mock_execute):
self.encryptor.detach_volume()
mock_execute.assert_has_calls([
mock.call('cryptsetup', 'luksClose', self.dev_name,
attempts=3, run_as_root=True, check_exit_code=True),
])
self.assertEqual(1, mock_execute.call_count)
@mock.patch('nova.utils.execute')
def test_detach_volume(self, mock_execute):
self.encryptor.detach_volume()
mock_execute.assert_has_calls([
mock.call('cryptsetup', 'luksClose', self.dev_name,
attempts=3, run_as_root=True, check_exit_code=True),
])
self.assertEqual(1, mock_execute.call_count)
def test_get_mangled_passphrase(self):
# Confirm that a mangled passphrase is provided as per bug#1633518
unmangled_raw_key = bytes(binascii.unhexlify('0725230b'))
symmetric_key = key.SymmetricKey('AES', len(unmangled_raw_key) * 8,
unmangled_raw_key)
unmangled_encoded_key = symmetric_key.get_encoded()
encryptor = luks.LuksEncryptor(self.connection_info)
self.assertEqual(encryptor._get_mangled_passphrase(
unmangled_encoded_key), '72523b')
@mock.patch('nova.utils.execute')
def test_attach_volume_unmangle_passphrase(self, mock_execute):
fake_key = '0725230b'
fake_key_mangled = '72523b'
self.encryptor._get_key = mock.MagicMock(name='mock_execute')
self.encryptor._get_key.return_value = \
test_cryptsetup.fake__get_key(None, fake_key)
mock_execute.side_effect = [
processutils.ProcessExecutionError(exit_code=2), # luksOpen
mock.DEFAULT, # luksOpen
mock.DEFAULT, # luksClose
mock.DEFAULT, # luksAddKey
mock.DEFAULT, # luksOpen
mock.DEFAULT, # luksClose
mock.DEFAULT, # luksRemoveKey
mock.DEFAULT, # luksOpen
mock.DEFAULT, # ln
]
self.encryptor.attach_volume(None)
mock_execute.assert_has_calls([
mock.call('cryptsetup', 'luksOpen', '--key-file=-', self.dev_path,
self.dev_name, process_input=fake_key,
run_as_root=True, check_exit_code=True),
mock.call('cryptsetup', 'luksOpen', '--key-file=-', self.dev_path,
self.dev_name, process_input=fake_key_mangled,
run_as_root=True, check_exit_code=True),
mock.call('cryptsetup', 'luksClose', self.dev_name,
run_as_root=True, check_exit_code=True, attempts=3),
mock.call('cryptsetup', 'luksAddKey', self.dev_path,
process_input=''.join([fake_key_mangled,
'\n', fake_key,
'\n', fake_key]),
run_as_root=True, check_exit_code=True),
mock.call('cryptsetup', 'luksOpen', '--key-file=-', self.dev_path,
self.dev_name, process_input=fake_key,
run_as_root=True, check_exit_code=True),
mock.call('cryptsetup', 'luksClose', self.dev_name,
run_as_root=True, check_exit_code=True, attempts=3),
mock.call('cryptsetup', 'luksRemoveKey', self.dev_path,
process_input=fake_key_mangled, run_as_root=True,
check_exit_code=True),
mock.call('cryptsetup', 'luksOpen', '--key-file=-', self.dev_path,
self.dev_name, process_input=fake_key,
run_as_root=True, check_exit_code=True),
mock.call('ln', '--symbolic', '--force',
'/dev/mapper/%s' % self.dev_name, self.symlink_path,
run_as_root=True, check_exit_code=True),
], any_order=False)
self.assertEqual(9, mock_execute.call_count)
|
hanlind/nova
|
nova/tests/unit/volume/encryptors/test_luks.py
|
Python
|
apache-2.0
| 10,988 | 0.000091 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutSandwichCode in the Ruby Koans
#
from runner.koan import *
import re # For regular expression string comparisons
class AboutWithStatements(Koan):
def count_lines(self, file_name):
try:
file = open(file_name)
try:
return len(file.readlines())
finally:
file.close()
except IOError:
# should never happen
self.fail()
def test_counting_lines(self):
self.assertEqual(4, self.count_lines("example_file.txt"))
# ------------------------------------------------------------------
def find_line(self, file_name):
try:
file = open(file_name)
try:
for line in file.readlines():
match = re.search('e', line)
if match:
return line
finally:
file.close()
except IOError:
# should never happen
self.fail()
def test_finding_lines(self):
self.assertEqual('test\n', self.find_line("example_file.txt"))
## ------------------------------------------------------------------
## THINK ABOUT IT:
##
## The count_lines and find_line are similar, and yet different.
## They both follow the pattern of "sandwich code".
##
## Sandwich code is code that comes in three parts: (1) the top slice
## of bread, (2) the meat, and (3) the bottom slice of bread.
## The bread part of the sandwich almost always goes together, but
## the meat part changes all the time.
##
## Because the changing part of the sandwich code is in the middle,
## abstracting the top and bottom bread slices to a library can be
## difficult in many languages.
##
## (Aside for C++ programmers: The idiom of capturing allocated
## pointers in a smart pointer constructor is an attempt to deal with
## the problem of sandwich code for resource allocation.)
##
## Python solves the problem using Context Managers. Consider the
## following code:
##
class FileContextManager():
def __init__(self, file_name):
self._file_name = file_name
self._file = None
def __enter__(self):
self._file = open(self._file_name)
return self._file
def __exit__(self, cls, value, tb):
self._file.close()
# Now we write:
def count_lines2(self, file_name):
with self.FileContextManager(file_name) as file:
return len(file.readlines())
def test_counting_lines2(self):
self.assertEqual(4, self.count_lines2("example_file.txt"))
# ------------------------------------------------------------------
def find_line2(self, file_name):
# Rewrite find_line using the Context Manager.
with self.FileContextManager(file_name) as file:
for line in file.readlines():
if re.search('e', line):
return line
def test_finding_lines2(self):
self.assertEqual('test\n', self.find_line2("example_file.txt"))
self.assertNotEqual('a', self.find_line2("example_file.txt"))
# ------------------------------------------------------------------
def count_lines3(self, file_name):
with open(file_name) as file:
return len(file.readlines())
def test_open_already_has_its_own_built_in_context_manager(self):
self.assertEqual(4, self.count_lines3("example_file.txt"))
|
kimegitee/python-koans
|
python3/koans/about_with_statements.py
|
Python
|
mit
| 3,602 | 0.004997 |
'''
Copyright 2015 University of Auckland
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 PySide import QtCore, QtGui
from opencmiss.zinc.sceneviewer import Sceneviewer
from opencmiss.zinc.spectrum import Spectrum, Spectrumcomponent
from opencmiss.zinc.status import OK as ZINC_OK
from opencmiss.neon.ui.editors.ui_spectrumeditorwidget import Ui_SpectrumEditorWidget
from opencmiss.neon.settings.mainsettings import FLOAT_STRING_FORMAT
from opencmiss.neon.core.neonlogger import NeonLogger
COMPONENT_NAME_FORMAT = '{:d}. '
SPECTRUM_DATA_ROLE = QtCore.Qt.UserRole + 1
class SpectrumEditorWidget(QtGui.QWidget):
def __init__(self, parent=None, shared_context=None):
super(SpectrumEditorWidget, self).__init__(parent)
self._ui = Ui_SpectrumEditorWidget()
self._ui.setupUi(self, shared_context)
self._ui.comboBoxColourMap.addItems(extractColourMappingEnum())
self._ui.comboBoxScale.addItems(extractScaleTypeEnum())
self._spectrums = None
self._zincContext = None
self._selected_spectrum_row = -1
self._selected_spectrum_components_row = -1
self._previewZincRegion = None
self._previewZincScene = None
self._spectrummodulenotifier = None
self._currentSpectrumName = None
self._updateUi()
self._makeConnections()
def _makeConnections(self):
self._ui.pushButtonAddSpectrum.clicked.connect(self._addSpectrumClicked)
self._ui.pushButtonDeleteSpectrum.clicked.connect(self._deleteSpectrumClicked)
self._ui.pushButtonAddSpectrumComponent.clicked.connect(self._addSpectrumComponentClicked)
self._ui.pushButtonDeleteSpectrumComponent.clicked.connect(self._deleteSpectrumComponentClicked)
self._ui.listWidgetSpectrums.itemClicked.connect(self._spectrumItemClicked)
self._ui.listWidgetSpectrums.itemChanged.connect(self._spectrumChanged)
self._ui.checkBoxOverwrite.clicked.connect(self._overwriteClicked)
self._ui.checkBoxDefault.clicked.connect(self._defaultClicked)
self._ui.pushButtonAutorange.clicked.connect(self._autorangeClicked)
self._ui.listWidgetSpectrumComponents.itemClicked.connect(self._spectrumComponentItemClicked)
self._ui.pushButtonMoveDownSpectrumComponent.clicked.connect(self._moveDownSpectrumComponentClicked)
self._ui.pushButtonMoveUpSpectrumComponent.clicked.connect(self._moveUpSpectrumComponentClicked)
self._ui.comboBoxColourMap.currentIndexChanged.connect(self._colourMapIndexChanged)
self._ui.pushButtonReverseColours.clicked.connect(self._reverseColoursClicked)
self._ui.spinBoxDataFieldComponent.valueChanged.connect(self._dataFieldComponentValueChanged)
self._ui.lineEditDataRangeMin.editingFinished.connect(self._dataRangeMinEntered)
self._ui.lineEditDataRangeMax.editingFinished.connect(self._dataRangeMaxEntered)
self._ui.lineEditColourRangeMin.editingFinished.connect(self._colourRangeMinEntered)
self._ui.lineEditColourRangeMax.editingFinished.connect(self._colourRangeMaxEntered)
self._ui.checkBoxExtendBelow.clicked.connect(self._extendBelowClicked)
self._ui.checkBoxExtendAbove.clicked.connect(self._extendAboveClicked)
self._ui.checkBoxFixMinimum.clicked.connect(self._fixMinimumClicked)
self._ui.checkBoxFixMaximum.clicked.connect(self._fixMaximumClicked)
self._ui.comboBoxScale.currentIndexChanged.connect(self._scaleIndexChanged)
self._ui.lineEditExaggeration.editingFinished.connect(self._exaggerationEntered)
self._ui.sceneviewerWidgetPreview.graphicsInitialized.connect(self._graphicsInitialised)
def _getCurrentSpectrum(self):
currentItem = self._ui.listWidgetSpectrums.currentItem()
if not currentItem:
return None
name = currentItem.text()
sm = self._zincContext.getSpectrummodule()
spectrum = sm.findSpectrumByName(name)
if spectrum.isValid():
return spectrum
return None
def _clearSpectrumUi(self):
self._ui.listWidgetSpectrumComponents.clear()
self._ui.checkBoxOverwrite.setChecked(False)
self._clearSpectrumComponentUi()
def _clearSpectrumComponentUi(self):
self._ui.comboBoxColourMap.setCurrentIndex(0)
self._ui.comboBoxScale.setCurrentIndex(0)
def _spectrummoduleCallback(self, spectrummoduleevent):
'''
Callback for change in spectrums; may need to rebuild spectrum list
'''
changeSummary = spectrummoduleevent.getSummarySpectrumChangeFlags()
# print("Spectrum Editor: _spectrummoduleCallback changeSummary " + str(changeSummary))
if 0 != (changeSummary & (Spectrum.CHANGE_FLAG_IDENTIFIER | Spectrum.CHANGE_FLAG_ADD | Spectrum.CHANGE_FLAG_REMOVE)):
self._buildSpectrumList()
def _buildSpectrumList(self):
sm = self._zincContext.getSpectrummodule()
si = sm.createSpectrumiterator()
lws = self._ui.listWidgetSpectrums
lws.clear()
s = si.next()
selectedItem = None
while s.isValid():
name = s.getName()
item = createSpectrumListItem(name)
lws.addItem(item)
if name == self._currentSpectrumName:
selectedItem = item
s = si.next()
if not selectedItem:
if lws.count() > 0:
selectedItem = lws.item(0)
self._currentSpectrumName = selectedItem.text()
else:
self._currentSpectrumName = None
if selectedItem:
lws.setCurrentItem(selectedItem)
selectedItem.setSelected(True)
self._updateUi()
def _updateUi(self):
self._clearSpectrumUi()
spectrum = self._getCurrentSpectrum()
spectrum_selected = spectrum is not None
self._ui.pushButtonDeleteSpectrum.setEnabled(spectrum_selected)
self._ui.sceneviewerWidgetPreview.setEnabled(spectrum_selected)
self._ui.groupBoxSpectrumProperties.setEnabled(spectrum_selected)
self._ui.groupBoxComponents.setEnabled(spectrum_selected)
self._ui.groupBoxComponentProperties.setEnabled(spectrum_selected)
if spectrum_selected:
# Only one spectrum can be selected at a time.
sm = self._zincContext.getSpectrummodule()
is_default_spectrum = (spectrum == sm.getDefaultSpectrum())
self._ui.pushButtonDeleteSpectrum.setEnabled(not is_default_spectrum)
self._ui.checkBoxDefault.setChecked(is_default_spectrum)
self._ui.checkBoxOverwrite.setChecked(spectrum.isMaterialOverwrite())
sc = spectrum.getFirstSpectrumcomponent()
while sc.isValid():
count = self._ui.listWidgetSpectrumComponents.count() + 1
self._ui.listWidgetSpectrumComponents.addItem(createItem(getComponentString(sc, count), sc))
sc = spectrum.getNextSpectrumcomponent(sc)
if self._ui.listWidgetSpectrumComponents.count():
self._ui.listWidgetSpectrumComponents.setCurrentRow(0)
self._previewSpectrum(spectrum)
self._updateComponentUi()
def _previewSpectrum(self, spectrum):
if self._previewZincScene is None:
return
if (spectrum is None) or (not spectrum.isValid()):
self._previewZincScene.removeAllGraphics()
return
points = self._previewZincScene.getFirstGraphics()
self._previewZincScene.beginChange()
if not points.isValid():
points = self._previewZincScene.createGraphicsPoints()
pointsattr = points.getGraphicspointattributes()
pointsattr.setBaseSize(1.0)
else:
pointsattr = points.getGraphicspointattributes()
colourBar = self._spectrums.findOrCreateSpectrumGlyphColourBar(spectrum)
pointsattr.setGlyph(colourBar)
self._previewZincScene.endChange()
sceneviewer = self._ui.sceneviewerWidgetPreview.getSceneviewer()
if sceneviewer:
sceneviewer.beginChange()
sceneviewer.setScene(self._previewZincScene)
sceneviewer.setProjectionMode(Sceneviewer.PROJECTION_MODE_PARALLEL)
_, centre = colourBar.getCentre(3)
eye = [centre[0], centre[1], centre[2] + 5.0]
up = [-1.0, 0.0, 0.0]
sceneviewer.setLookatParametersNonSkew(eye, centre, up)
sceneviewer.setNearClippingPlane(1.0)
sceneviewer.setFarClippingPlane(10.0)
sceneviewer.setViewAngle(0.25)
sceneviewer.endChange()
def _getCurrentSpectrumcomponent(self):
spectrum_component_items = self._ui.listWidgetSpectrumComponents.selectedItems()
if len(spectrum_component_items) > 0:
active_item = spectrum_component_items[0]
return active_item.data(SPECTRUM_DATA_ROLE)
return None
def _updateComponentUi(self):
spectrum_component_items = self._ui.listWidgetSpectrumComponents.selectedItems()
spectrum_component_selected = (len(spectrum_component_items) > 0)
self._ui.pushButtonDeleteSpectrumComponent.setEnabled(spectrum_component_selected)
self._ui.comboBoxColourMap.setEnabled(spectrum_component_selected)
self._ui.pushButtonAutorange.setEnabled(spectrum_component_selected)
self._ui.comboBoxScale.setEnabled(spectrum_component_selected)
self._ui.spinBoxDataFieldComponent.setEnabled(spectrum_component_selected)
self._ui.pushButtonReverseColours.setEnabled(spectrum_component_selected)
self._ui.lineEditDataRangeMin.setEnabled(spectrum_component_selected)
self._ui.lineEditDataRangeMax.setEnabled(spectrum_component_selected)
self._ui.lineEditColourRangeMin.setEnabled(spectrum_component_selected)
self._ui.lineEditColourRangeMax.setEnabled(spectrum_component_selected)
self._ui.checkBoxExtendBelow.setEnabled(spectrum_component_selected)
self._ui.checkBoxExtendAbove.setEnabled(spectrum_component_selected)
self._ui.checkBoxFixMinimum.setEnabled(spectrum_component_selected)
self._ui.checkBoxFixMaximum.setEnabled(spectrum_component_selected)
self._ui.pushButtonMoveDownSpectrumComponent.setEnabled(spectrum_component_selected)
self._ui.pushButtonMoveUpSpectrumComponent.setEnabled(spectrum_component_selected)
if spectrum_component_selected:
active_spectrum_component = spectrum_component_items[0]
sc = active_spectrum_component.data(SPECTRUM_DATA_ROLE)
self._ui.comboBoxColourMap.blockSignals(True)
self._ui.comboBoxColourMap.setCurrentIndex(sc.getColourMappingType())
self._ui.comboBoxColourMap.blockSignals(False)
self._ui.spinBoxDataFieldComponent.setValue(sc.getFieldComponent())
self._ui.lineEditDataRangeMin.setText(FLOAT_STRING_FORMAT.format(sc.getRangeMinimum()))
self._ui.lineEditDataRangeMax.setText(FLOAT_STRING_FORMAT.format(sc.getRangeMaximum()))
self._ui.lineEditColourRangeMin.setText(FLOAT_STRING_FORMAT.format(sc.getColourMinimum()))
self._ui.lineEditColourRangeMax.setText(FLOAT_STRING_FORMAT.format(sc.getColourMaximum()))
self._ui.checkBoxExtendBelow.setChecked(sc.isExtendBelow())
self._ui.checkBoxExtendAbove.setChecked(sc.isExtendAbove())
self._ui.checkBoxFixMinimum.setChecked(sc.isFixMinimum())
self._ui.checkBoxFixMaximum.setChecked(sc.isFixMaximum())
self._ui.comboBoxScale.setCurrentIndex(sc.getScaleType())
self._ui.lineEditExaggeration.setText(FLOAT_STRING_FORMAT.format(sc.getExaggeration()))
row = self._ui.listWidgetSpectrumComponents.row(active_spectrum_component)
self._ui.pushButtonMoveUpSpectrumComponent.setEnabled(row > 0)
self._ui.pushButtonMoveDownSpectrumComponent.setEnabled(row < (self._ui.listWidgetSpectrumComponents.count() - 1))
active_spectrum_component.setText(getComponentString(sc, row + 1))
def _spectrumChanged(self, item):
newName = item.text()
sm = self._zincContext.getSpectrummodule()
spectrum = sm.findSpectrumByName(self._currentSpectrumName)
# spectrum = item.data(SPECTRUM_DATA_ROLE)
if self._spectrums.renameSpectrum(spectrum, newName):
self._currentSpectrumName = newName
else:
item.setText(spectrum.getName())
def _spectrumItemClicked(self, item):
item.setSelected(True)
self._currentSpectrumName = item.text()
self._selected_spectrum_row = self._ui.listWidgetSpectrums.row(item)
self._updateUi()
def _spectrumComponentItemClicked(self, item):
lwsc = self._ui.listWidgetSpectrumComponents
item.setSelected(True)
selected_items = lwsc.selectedItems()
if len(selected_items):
if self._selected_spectrum_components_row == lwsc.row(item):
# self._ui.listWidgetSpectrumComponents.clearSelection()
# self._selected_spectrum_components_row = -1
# self._clearSpectrumComponentUi()
pass
else:
self._selected_spectrum_components_row = lwsc.row(item)
self._updateComponentUi()
def _selectSpectrumByName(self, name):
lws = self._ui.listWidgetSpectrums
for row in range(lws.count()):
item = lws.item(row)
if item.text() == name:
item.setSelected(True)
self._currentSpectrumName = name
self._updateUi()
return
self._currentSpectrumName = None
def _selectSpectrum(self, spectrum):
if (spectrum is None) or (not spectrum.isValid()):
return
self._selectSpectrumByName(spectrum.getName())
def _addSpectrumClicked(self):
sm = self._zincContext.getSpectrummodule()
sm.beginChange()
spectrum = sm.createSpectrum()
spectrum.setManaged(True)
self._currentSpectrumName = spectrum.getName()
sm.endChange()
self._selectSpectrum(spectrum)
self._updateUi()
def _deleteSpectrumClicked(self):
self._previewSpectrum(None) # preview graphics references spectrum
if not self._spectrums.removeSpectrumByName(self._currentSpectrumName):
NeonLogger.getLogger().error("Can't delete spectrum " + self._currentSpectrumName + " as it is in use")
self._updateUi()
def _addSpectrumComponentClicked(self):
s = self._getCurrentSpectrum()
sc = s.createSpectrumcomponent()
count = self._ui.listWidgetSpectrumComponents.count() + 1
item = createItem(getComponentString(sc, count), sc)
self._ui.listWidgetSpectrumComponents.addItem(item)
item.setSelected(True)
self._spectrumComponentItemClicked(item)
def _deleteSpectrumComponentClicked(self):
selected_items = self._ui.listWidgetSpectrumComponents.selectedItems()
if len(selected_items):
row = self._ui.listWidgetSpectrumComponents.row(selected_items[0])
item = self._ui.listWidgetSpectrumComponents.takeItem(row)
sc = item.data(SPECTRUM_DATA_ROLE)
s = self._getCurrentSpectrum()
if s:
s.removeSpectrumcomponent(sc)
self._updateComponentUi()
def _defaultClicked(self):
if self._ui.checkBoxDefault.isChecked():
s = self._getCurrentSpectrum()
sm = self._ui.sceneviewerWidgetPreview.getContext().getSpectrummodule()
sm.setDefaultSpectrum(s)
else:
# Can't un-set default; need to make another one default
self._ui.checkBoxDefault.setChecked(True)
def _overwriteClicked(self):
s = self._getCurrentSpectrum()
s.setMaterialOverwrite(self._ui.checkBoxOverwrite.isChecked())
def _autorangeClicked(self):
"""
Autorange all components of spectrum.
Maintains proportions of minimums and miximums for spectrum components, fixed minimums and maximums.
"""
s = self._getCurrentSpectrum()
region = self._zincContext.getDefaultRegion()
scene = region.getScene()
scenefiltermodule = self._zincContext.getScenefiltermodule()
scenefilter = scenefiltermodule.getDefaultScenefilter()
s.autorange(scene, scenefilter)
self._updateComponentUi()
def _reverseColoursClicked(self):
sc = self._getCurrentSpectrumcomponent()
if sc:
sm = self._zincContext.getSpectrummodule()
sm.beginChange()
newColourMaximum = sc.getColourMinimum()
newColourMinimum = sc.getColourMaximum()
sc.setColourMaximum(newColourMaximum)
sc.setColourMinimum(newColourMinimum)
sm.endChange()
self._updateComponentUi()
def _dataFieldComponentValueChanged(self, value):
selected_items = self._ui.listWidgetSpectrumComponents.selectedItems()
if len(selected_items):
active_item = selected_items[0]
sc = active_item.data(SPECTRUM_DATA_ROLE)
sc.setFieldComponent(value)
self._updateComponentUi()
def _colourMapIndexChanged(self, index):
selected_items = self._ui.listWidgetSpectrumComponents.selectedItems()
if len(selected_items):
active_item = selected_items[0]
sc = active_item.data(SPECTRUM_DATA_ROLE)
sc.setColourMappingType(index)
self._updateComponentUi()
def _dataRangeMinEntered(self):
sc = self._getCurrentSpectrumcomponent()
try:
valueText = self._ui.lineEditDataRangeMin.text()
value = float(valueText)
result = sc.setRangeMinimum(value)
if result != ZINC_OK:
raise ValueError("")
except ValueError:
NeonLogger.getLogger().error("Error setting spectrum component data range minimum")
self._ui.lineEditDataRangeMin.setText(FLOAT_STRING_FORMAT.format(sc.getRangeMinimum()))
def _dataRangeMaxEntered(self):
sc = self._getCurrentSpectrumcomponent()
try:
valueText = self._ui.lineEditDataRangeMax.text()
value = float(valueText)
result = sc.setRangeMaximum(value)
if result != ZINC_OK:
raise ValueError("")
except ValueError:
NeonLogger.getLogger().error("Error setting spectrum component data range maximum")
self._ui.lineEditDataRangeMax.setText(FLOAT_STRING_FORMAT.format(sc.getRangeMaximum()))
def _colourRangeMinEntered(self):
sc = self._getCurrentSpectrumcomponent()
try:
valueText = self._ui.lineEditColourRangeMin.text()
value = float(valueText)
result = sc.setColourMinimum(value)
if result != ZINC_OK:
raise ValueError("")
except ValueError:
NeonLogger.getLogger().error("Error setting spectrum component colour range minimum")
self._ui.lineEditColourRangeMin.setText(FLOAT_STRING_FORMAT.format(sc.getColourMinimum()))
def _colourRangeMaxEntered(self):
sc = self._getCurrentSpectrumcomponent()
try:
valueText = self._ui.lineEditColourRangeMax.text()
value = float(valueText)
result = sc.setColourMaximum(value)
if result != ZINC_OK:
raise ValueError("")
except ValueError:
NeonLogger.getLogger().error("Error setting spectrum component colour range maximum")
self._ui.lineEditColourRangeMax.setText(FLOAT_STRING_FORMAT.format(sc.getColourMaximum()))
def _extendBelowClicked(self):
sc = self._getCurrentSpectrumcomponent()
sc.setExtendBelow(self._ui.checkBoxExtendBelow.isChecked())
def _extendAboveClicked(self):
sc = self._getCurrentSpectrumcomponent()
sc.setExtendAbove(self._ui.checkBoxExtendAbove.isChecked())
def _fixMinimumClicked(self):
sc = self._getCurrentSpectrumcomponent()
sc.setFixMinimum(self._ui.checkBoxFixMinimum.isChecked())
def _fixMaximumClicked(self):
sc = self._getCurrentSpectrumcomponent()
sc.setFixMaximum(self._ui.checkBoxFixMaximum.isChecked())
def _scaleIndexChanged(self, index):
selected_items = self._ui.listWidgetSpectrumComponents.selectedItems()
if len(selected_items):
active_item = selected_items[0]
sc = active_item.data(SPECTRUM_DATA_ROLE)
sc.setScaleType(index)
self._updateComponentUi()
def _exaggerationEntered(self):
sc = self._getCurrentSpectrumcomponent()
try:
valueText = self._ui.lineEditExaggeration.text()
value = float(valueText)
result = sc.setExaggeration(value)
if result != ZINC_OK:
raise ValueError("")
except ValueError:
NeonLogger.getLogger().error("Error setting log scale exaggeration")
self._ui.lineEditExaggeration.setText(FLOAT_STRING_FORMAT.format(sc.getExaggeration()))
def _moveDownSpectrumComponentClicked(self):
self._moveSpectrumComponent(1)
def _moveSpectrumComponent(self, direction):
selected_items = self._ui.listWidgetSpectrumComponents.selectedItems()
if len(selected_items):
active_item = selected_items[0]
row = self._ui.listWidgetSpectrumComponents.row(active_item)
next_row = row + direction
self._ui.listWidgetSpectrumComponents.takeItem(row)
self._ui.listWidgetSpectrumComponents.insertItem(next_row, active_item)
item = self._ui.listWidgetSpectrumComponents.item(row)
sc = item.data(SPECTRUM_DATA_ROLE)
item.setText(getComponentString(sc, row + 1))
self._ui.listWidgetSpectrumComponents.setCurrentRow(next_row)
self._selected_spectrum_components_row = next_row
self._updateComponentUi()
def _moveUpSpectrumComponentClicked(self):
self._moveSpectrumComponent(-1)
def _graphicsInitialised(self):
if self._ui.listWidgetSpectrums.count():
self._ui.listWidgetSpectrums.setCurrentRow(0)
first_item = self._ui.listWidgetSpectrums.item(0)
self._spectrumItemClicked(first_item)
def setSpectrums(self, spectrums):
"""
Sets the Neon spectrums object which supplies the zinc context and has utilities for
managing spectrums.
:param spectrums: NeonSpectrums object
"""
self._spectrums = spectrums
self._currentSpectrumName = None
self._zincContext = spectrums.getZincContext()
self._ui.sceneviewerWidgetPreview.setContext(self._zincContext)
self._previewZincRegion = self._zincContext.createRegion()
self._previewZincRegion.setName("Spectrum editor preview region")
self._previewZincScene = self._previewZincRegion.getScene()
sceneviewer = self._ui.sceneviewerWidgetPreview.getSceneviewer()
if sceneviewer:
sceneviewer.setScene(self._previewZincScene)
spectrummodule = self._zincContext.getSpectrummodule()
self._spectrummodulenotifier = spectrummodule.createSpectrummodulenotifier()
self._spectrummodulenotifier.setCallback(self._spectrummoduleCallback)
self._buildSpectrumList()
INVALID_POSTFIX = '_INVALID'
COLOUR_MAPPING_PREFIX = 'COLOUR_MAPPING_TYPE_'
SCALE_TYPE_PREFIX = 'SCALE_TYPE_'
PRIVATE_SPECTRUM_FORMAT = 'spectrum_{0}'
def createSpectrumListItem(name):
i = QtGui.QListWidgetItem(name)
i.setFlags(i.flags() | QtCore.Qt.ItemIsEditable)
return i
def createItem(name, data, editable=False):
i = QtGui.QListWidgetItem(name)
i.setData(SPECTRUM_DATA_ROLE, data)
if editable:
i.setFlags(i.flags() | QtCore.Qt.ItemIsEditable)
return i
def getComponentString(sc, row):
name = COMPONENT_NAME_FORMAT.format(row)
name += ' ' + stringFromColourMappingInt(sc.getColourMappingType())
name += ' ' + stringFromScaleInt(sc.getScaleType())
if sc.isColourReverse():
name += ' reverse'
return name
def stringFromColourMappingInt(value):
attr_dict = Spectrumcomponent.__dict__
for key in attr_dict:
if key.startswith(COLOUR_MAPPING_PREFIX) and attr_dict[key] == value:
return key.replace(COLOUR_MAPPING_PREFIX, '').lower()
return 'invalid'
def stringFromScaleInt(value):
attr_dict = Spectrumcomponent.__dict__
for key in attr_dict:
if key.startswith(SCALE_TYPE_PREFIX) and attr_dict[key] == value:
return key.replace(SCALE_TYPE_PREFIX, '').lower()
return 'invalid'
def extractColourMappingEnum():
enum = []
attr_dict = Spectrumcomponent.__dict__
for key in attr_dict:
if key.startswith(COLOUR_MAPPING_PREFIX):
if key.endswith(INVALID_POSTFIX):
enum.append((attr_dict[key], '---'))
else:
enum.append((attr_dict[key], key.replace(COLOUR_MAPPING_PREFIX, '')))
sorted_enum = sorted(enum)
return [a[1] for a in sorted_enum]
def extractScaleTypeEnum():
enum = []
attr_dict = Spectrumcomponent.__dict__
for key in attr_dict:
if key.startswith(SCALE_TYPE_PREFIX):
if key.endswith(INVALID_POSTFIX):
enum.append((attr_dict[key], '---'))
else:
enum.append((attr_dict[key], key.replace(SCALE_TYPE_PREFIX, '')))
sorted_enum = sorted(enum)
return [a[1] for a in sorted_enum]
|
alan-wu/neon
|
src/opencmiss/neon/ui/editors/spectrumeditorwidget.py
|
Python
|
apache-2.0
| 26,338 | 0.002202 |
# -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2013 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# ####################################################################
import editor
import pdb
import math
from fife import fife
import editor
import events
import undomanager
from fife.extensions.pychan.tools import callbackWithArguments as cbwa
from fife.extensions.fife_settings import Setting
TDS = Setting(app_name="editor")
class MapController(object):
""" MapController provides an interface for editing maps """
def __init__(self, map):
self._editor = editor.getEditor()
self._engine = self._editor.getEngine()
self._camera = None # currently selected camera
self._layer = None # currently selected layer
self._selection = [] # currently selected cells
self._single_instance = False # flag to force selection of one single instance
self._instance = None # current selected single instance
self._map = None
self._undo = False
self._undomanager = undomanager.UndoManager()
undomanager.preUndo.connect(self._startUndo, sender=self._undomanager)
undomanager.preRedo.connect(self._startUndo, sender=self._undomanager)
undomanager.postUndo.connect(self._endUndo, sender=self._undomanager)
undomanager.postRedo.connect(self._endUndo, sender=self._undomanager)
self.debug = False
self._settings = TDS
self.overwriteInstances = True # Remove instances on cell before placing new instance
self.importList = {} # used to keep track of current imports needed by the map
if map is not None:
self.setMap(map.getId())
def cleanUp(self):
undomanager.preUndo.disconnect(self._startUndo, sender=self._undomanager)
undomanager.preRedo.disconnect(self._startUndo, sender=self._undomanager)
undomanager.postUndo.disconnect(self._endUndo, sender=self._undomanager)
undomanager.postRedo.disconnect(self._endUndo, sender=self._undomanager)
self._undomanager.clear()
self._editor = None
self._engine = None
self._map = None
self._selection = []
self._layer = None
self._camera = None
def setMap(self, mapid):
""" Set the map to be edited """
self._camera = None
self._map = None
self._layer = None
self._selection = []
self._map = self._engine.getModel().getMap(mapid)
if not self._map.getLayers():
raise AttributeError('Editor error: map ' + self._map.getId() + ' has no layers. Cannot edit.')
for cam in self._map.getCameras():
if cam.getLocationRef().getMap().getId() == self._map.getId():
self._camera = cam
break
# remove imports from previous map
self.importList.clear()
# keep track of imports that were loaded with the map
for layer in self._map.getLayers():
for i in layer.getInstances():
self.incrementReferenceCountForObject(i.getObject())
self._layer = self._map.getLayers()[0]
gridrenderer = fife.GridRenderer.getInstance(self._camera)
gridrenderer.activateAllLayers(self._map)
color = str(self._settings.get("Colors", "Grid", "0,255,0"))
gridrenderer.setColor(*[int(c) for c in color.split(',')])
blockrenderer = fife.BlockingInfoRenderer.getInstance(self._camera)
blockrenderer.activateAllLayers(self._map)
color = str(self._settings.get("Colors", "Blocking", "0,255,0"))
blockrenderer.setColor(*[int(c) for c in color.split(',')])
coordinaterenderer = fife.CoordinateRenderer.getInstance(self._camera)
coordinaterenderer.activateAllLayers(self._map)
color = str(self._settings.get("Colors", "Coordinate", "255,255,255"))
coordinaterenderer.setColor(*[int(c) for c in color.split(',')])
cellrenderer = fife.CellSelectionRenderer.getInstance(self._camera)
cellrenderer.activateAllLayers(self._map)
color = str(self._settings.get("Colors", "CellSelection", "255,0,0"))
cellrenderer.setColor(*[int(c) for c in color.split(',')])
cellrenderer.setEnabled(True)
def getMap(self):
return self._map
def selectLayer(self, layerid):
""" Select layer to be edited """
self.deselectSelection()
self._layer = None
layers = [l for l in self._map.getLayers() if l.getId() == layerid]
if len(layers) == 1:
self._layer = layers[0]
def deselectSelection(self):
""" Deselects all selected cells """
if not self._camera:
if self.debug: print 'No camera bind yet, cannot select any cell'
return
self._selection = []
fife.CellSelectionRenderer.getInstance(self._camera).reset()
def clearSelection(self):
""" Removes all instances on selected cells """
instances = self.getInstancesFromSelection()
self._undomanager.startGroup("Cleared selection")
self.removeInstances(instances)
self._undomanager.endGroup()
def fillSelection(self, object):
""" Adds an instance of object on each selected cell """
self._undomanager.startGroup("Filled selection")
for loc in self._selection:
self.placeInstance(loc.getLayerCoordinates(), object)
self._undomanager.endGroup()
def selectCell(self, screenx, screeny):
""" Selects a cell at a position on screen """
if not self._camera:
if self.debug: print 'No camera bind yet, cannot select any cell'
return
if not self._layer:
if self.debug: print 'No layer assigned in selectCell'
return
loc = fife.Location(self._layer)
loc.setLayerCoordinates(self._layer.getCellGrid().toLayerCoordinates(self.screenToMapCoordinates(screenx, screeny)))
for i in self._selection:
if loc.getLayerCoordinates() == i.getLayerCoordinates(): return
self._selection.append(loc)
fife.CellSelectionRenderer.getInstance(self._camera).selectLocation(loc)
def deselectCell(self, screenx, screeny):
""" Deselects a cell at a position on screen """
if not self._camera:
if self.debug: print 'No camera bind yet, cannot select any cell'
return
if not self._layer:
if self.debug: print 'No layer assigned in selectCell'
return
loc = fife.Location(self._layer)
loc.setLayerCoordinates(self._layer.getCellGrid().toLayerCoordinates(self.screenToMapCoordinates(screenx, screeny)))
for i in self._selection[:]:
if loc.getLayerCoordinates() == i.getLayerCoordinates():
self._selection.remove(i)
fife.CellSelectionRenderer.getInstance(self._camera).deselectLocation(i)
return
def getLocationsFromSelection(self):
""" Returns all locations in the selected cells """
return self._selection
def getInstance(self):
""" Returns a single instance packed into a list (compat to API) """
if self._instance:
return [self._instance, ]
return []
def getInstancesFromSelection(self):
""" Returns all instances in the selected cells """
instances = []
for loc in self._selection:
instances.extend(self.getInstancesFromPosition(loc.getExactLayerCoordinates(), loc.getLayer()))
return instances
def getInstancesFromPosition(self, position, layer=None):
""" Returns all instances on a specified position
Interprets ivar _single_instance and returns only the
first instance if flag is set to True
"""
if not self._layer and not layer:
if self.debug: print 'No layer assigned in getInstancesFromPosition'
return
if not position:
if self.debug: print 'No position assigned in getInstancesFromPosition'
return
if layer:
loc = fife.Location(layer)
else:
loc = fife.Location(self._layer)
if isinstance(position, fife.ExactModelCoordinate):
loc.setExactLayerCoordinates(position)
else:
loc.setLayerCoordinates(position)
instances = self._camera.getMatchingInstances(loc)
if self._single_instance and instances:
return [instances[0], ]
return instances
def getAllInstances(self):
""" Returns all instances """
return self._layer.getInstances()
def getUndoManager(self):
""" Returns undo manager """
return self._undomanager
def undo(self):
""" Undo one level """
self._undomanager.undo()
def redo(self):
""" Redo one level """
self._undomanager.redo()
def _startUndo(self):
""" Called before a undo operation is performed. Makes sure undo stack does not get corrupted """
self._undo = True
def _endUndo(self):
""" Called when a undo operation is done """
self._undo = False
def placeInstance(self, position, object, layer=None):
""" Places an instance of object at position. Any existing instances on position are removed. """
mname = 'placeInstance'
if not object:
if self.debug: print 'No object assigned in %s' % mname
return
if not position:
if self.debug: print 'No position assigned in %s' % mname
return
if not self._layer:
if self.debug: print 'No layer assigned in %s' % mname
return
if self.debug: print 'Placing instance of ' + object.getId() + ' at ' + str(position)
# Remove instances from target position
if not self._undo:
instances = self.getInstancesFromPosition(position)
if len(instances) == 1:
# Check if the only instance at position has the same object
objectId = instances[0].getObject().getId()
objectNs = instances[0].getObject().getNamespace()
if objectId == object.getId() and objectNs == object.getNamespace():
if self.debug: print "Tried to place duplicate instance"
return
self._undomanager.startGroup("Placed instance")
self.removeInstances(instances)
if layer:
inst = layer.createInstance(object, position)
else:
inst = self._layer.createInstance(object, position)
fife.InstanceVisual.create(inst)
# update reference count in import list for object
self.incrementReferenceCountForObject(object)
if not self._undo:
redocall = cbwa(self.placeInstance, position, object, inst.getLocation().getLayer())
undocall = cbwa(self.removeInstanceOfObjectAt, position, object, inst.getLocation().getLayer())
undoobject = undomanager.UndoObject(undocall, redocall, "Placed instance")
self._undomanager.addAction(undoobject)
self._undomanager.endGroup()
def removeInstanceOfObjectAt(self, position, object, layer=None):
""" Removes the first instance of object it can find on position """
instances = self.getInstancesFromPosition(position, layer)
for i in instances:
if i.getObject().getId() == object.getId() and i.getObject().getNamespace() == object.getNamespace():
self.removeInstances([i],layer)
return
def removeInstances(self, instances, layer=None):
""" Removes all provided instances """
mname = 'removeInstances'
if not instances:
if self.debug: print 'No instances assigned in %s' % mname
return
for i in instances:
if self.debug: print 'Deleting instance ' + i.getObject().getId() + ' at ' + str(i.getLocation().getExactLayerCoordinates())
if not self._undo:
object = i.getObject()
position = i.getLocation().getExactLayerCoordinates()
undocall = cbwa(self.placeInstance, position, object, i.getLocation().getLayer())
redocall = cbwa(self.removeInstanceOfObjectAt, position, object, i.getLocation().getLayer())
undoobject = undomanager.UndoObject(undocall, redocall, "Removed instance")
self._undomanager.addAction(undoobject)
if layer:
layer.deleteInstance(i)
else:
self._layer.deleteInstance(i)
self.decrementReferenceCountForObject(i.getObject())
def moveInstances(self, instances, moveBy, exact=False, origLoc=None, origFacing=None):
""" Moves provided instances by moveBy. If exact is false, the instances are
snapped to closest cell. origLoc and origFacing are only set when an undo/redo
operation takes place and will have no effect and should not be used under normal
circumstances.
@type instances: list
@param instances: a bunch of selected fife.Instance objects
@type moveBy: fife.Point3D
@param moveBy: diff of last and current exact model coordinate relative to the cursor
@type exact: bool
@param exact: flag to either set exactLayerCoordinates or LayerCoordinates
@rtype result: bool
@return result: flag wether the instances were moved or not (always True if exact=True)
"""
result = True
mname = 'moveInstances'
if not self._layer:
if self.debug: print 'No layer assigned in %s' % mname
return not result
moveBy = fife.ExactModelCoordinate(float(moveBy.x), float(moveBy.y), float(moveBy.z))
for i in instances:
loc = i.getLocation()
f = i.getFacingLocation()
nloc = fife.Location(self._layer)
nloc.setMapCoordinates(loc.getMapCoordinates() + moveBy)
if loc.getLayerCoordinates() == nloc.getLayerCoordinates() and not exact:
result = False
break
if exact:
loc.setMapCoordinates(nloc.getMapCoordinates())
f.setMapCoordinates(loc.getMapCoordinates())
else:
loc.setLayerCoordinates(nloc.getLayerCoordinates())
f.setLayerCoordinates(loc.getLayerCoordinates())
if not self._undo:
undocall = cbwa(self.moveInstances, [i], moveBy, exact, i.getLocation(), i.getFacingLocation())
redocall = cbwa(self.moveInstances, [i], moveBy, exact, i.getLocation(), i.getFacingLocation())
undoobject = undomanager.UndoObject(undocall, redocall, "Moved instance")
self._undomanager.addAction(undoobject)
i.setLocation(loc)
i.setFacingLocation(f)
else:
assert(origLoc)
assert(origFacing)
i.setLocation(origLoc)
i.setFacingLocation(origFacing)
return result
def rotateCounterClockwise(self):
""" Rotates map counterclockwise by 90 degrees """
currot = self._camera.getRotation()
self._camera.setRotation((currot + 270) % 360)
def rotateClockwise(self):
""" Rotates map clockwise by 90 degrees """
currot = self._camera.getRotation()
self._camera.setRotation((currot + 90) % 360)
def getZoom(self):
""" Returns camera zoom """
if not self._camera:
if self.debug: print 'No camera bind yet, cannot get zoom'
return 0
return self._camera.getZoom()
def setZoom(self, zoom):
""" Sets camera zoom """
if not self._camera:
if self.debug: print 'No camera bind yet, cannot get zoom'
return
self._camera.setZoom(zoom)
def moveCamera(self, screen_x, screen_y):
""" Move camera (scroll) by screen_x, screen_y """
if not self._camera:
return
coords = self._camera.getLocationRef().getMapCoordinates()
z = self._camera.getZoom()
r = self._camera.getRotation()
if screen_x:
coords.x -= screen_x / z * math.cos(r / 180.0 * math.pi) / 100
coords.y -= screen_x / z * math.sin(r / 180.0 * math.pi) / 100
if screen_y:
coords.x -= screen_y / z * math.sin(-r / 180.0 * math.pi) / 100
coords.y -= screen_y / z * math.cos(-r / 180.0 * math.pi) / 100
coords = self._camera.getLocationRef().setMapCoordinates(coords)
self._camera.refresh()
def screenToMapCoordinates(self, screenx, screeny):
""" Convert screen coordinates to map coordinates, including z """
if not self._camera:
if self.debug: print 'No camera bind yet in screenToMapCoordinates'
return
if not self._layer:
if self.debug: print 'No layer assigned in screenToMapCoordinates'
return
screencoords = fife.ScreenPoint(screenx, screeny)
z_offset = self._camera.getZOffset(self._layer)
if self._layer == self._camera.getLocation().getLayer():
instance_z = float(-self._camera.getLocation().getExactLayerCoordinates().z)
layer_z = float(self._layer.getCellGrid().getZShift() - (self._camera.getLocation().getMapCoordinates().z - self._camera.getLocation().getExactLayerCoordinates().z))
z_offset.x *= int(instance_z + layer_z * self._layer.getCellGrid().getXScale())
z_offset.y *= int(instance_z + layer_z * self._layer.getCellGrid().getYScale())
else:
instance_z = float(-self._camera.getLocation().getExactLayerCoordinates(self._layer).z)
layer_z = float(self._layer.getCellGrid().getZShift() - (self._camera.getLocation().getMapCoordinates().z - self._camera.getLocation().getExactLayerCoordinates(self._layer).z))
z_offset.x *= int(instance_z + layer_z * self._layer.getCellGrid().getXScale())
z_offset.y *= int(instance_z + layer_z * self._layer.getCellGrid().getYScale())
if (z_offset.z <= 0):
screencoords.y += int(z_offset.y)
else:
screencoords.y -= int(z_offset.y)
mapCoords = self._camera.toMapCoordinates(screencoords, False)
mapCoords.z = self._layer.getCellGrid().getZShift()
return mapCoords
def incrementReferenceCountForObject(self, object):
""" updates the import count for the object passed in """
objFilename = object.getFilename()
if objFilename not in self.importList.keys():
self.importList[objFilename] = 1
else:
self.importList[objFilename] += 1
def decrementReferenceCountForObject(self, object):
""" decrements the reference count for the object passed in
and removes the object from the import list if the reference count hits 0 """
objFilename = object.getFilename()
if objFilename in self.importList.keys():
self.importList[objFilename] -= 1
if self.importList[objFilename] == 0:
del self.importList[objFilename]
|
whiterabbitengine/fifeplusplus
|
tools/editor/scripts/mapcontroller.py
|
Python
|
lgpl-2.1
| 18,203 | 0.02983 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
import slopos
class TestTagger(unittest.TestCase):
def setUp(self):
slopos.load_from_path("slopos/sl-tagger.pickle")
def testSentenceTagging(self):
tagged = slopos.tag("To je test.")
self.assertEqual(tagged, [('To', 'ZK-SEI'), ('je', 'GP-STE-N'), ('test', 'SOMETN'), ('.', '-None-')])
def testListTagging(self):
tagged = slopos.tag(["To", "je", "test"])
self.assertEqual(tagged, [('To', 'ZK-SEI'), ('je', 'GP-STE-N'), ('test', 'SOMETN')])
def testUnicodeSentenceTagging(self):
tagged = slopos.tag("V kožuščku zelene lisice stopiclja jezen otrok.")
self.assertEqual(tagged, [('V', 'DM'), ('kožuščku', 'SOMEM'), ('zelene', 'PPNZER'), ('lisice', 'SOZER,'),
('stopiclja', 'GGNSTE'), ('jezen', 'PPNMEIN'), ('otrok', 'SOMEI.'), ('.', '-None-')])
if __name__ == "__main__":
unittest.main()
|
izacus/slo_pos
|
tests.py
|
Python
|
lgpl-2.1
| 987 | 0.007136 |
# Copyright 2015 Huawei Technologies Co., Ltd.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from mock import patch
import six
import unittest
from six.moves import xrange
import neutron.conf.common as q_config
from neutron.db import db_base_plugin_v2
from neutron_lib.api.definitions import portbindings
from neutron_lib.plugins import directory
from neutron_lib.plugins import utils
from oslo_config import cfg
from oslo_utils import uuidutils
from tricircle.common import client
from tricircle.common import constants
from tricircle.common import context
import tricircle.db.api as db_api
from tricircle.db import core
from tricircle.db import models
from tricircle.network import central_plugin
import tricircle.network.central_trunk_plugin as trunk_plugin
from tricircle.network import helper
import tricircle.tests.unit.utils as test_utils
from tricircle.xjob import xmanager
_resource_store = test_utils.get_resource_store()
TOP_TRUNKS = _resource_store.TOP_TRUNKS
TOP_SUBPORTS = _resource_store.TOP_SUBPORTS
TOP_PORTS = _resource_store.TOP_PORTS
BOTTOM1_TRUNKS = _resource_store.BOTTOM1_TRUNKS
BOTTOM2_TRUNKS = _resource_store.BOTTOM2_TRUNKS
BOTTOM1_SUBPORTS = _resource_store.BOTTOM1_SUBPORTS
BOTTOM2_SUBPORTS = _resource_store.BOTTOM2_SUBPORTS
BOTTOM1_PORTS = _resource_store.BOTTOM1_PORTS
BOTTOM2_PORTS = _resource_store.BOTTOM2_PORTS
TEST_TENANT_ID = test_utils.TEST_TENANT_ID
class FakeBaseXManager(xmanager.XManager):
def __init__(self):
self.clients = {constants.TOP: client.Client()}
def _get_client(self, region_name=None):
return FakeClient(region_name)
class FakeXManager(FakeBaseXManager):
def __init__(self, fake_plugin):
super(FakeXManager, self).__init__()
self.xjob_handler = FakeBaseRPCAPI(fake_plugin)
self.helper = helper.NetworkHelper()
class FakeBaseRPCAPI(object):
def __init__(self, fake_plugin):
self.xmanager = FakeBaseXManager()
def sync_trunk(self, ctxt, project_id, trunk_id, pod_id):
combine_id = '%s#%s' % (pod_id, trunk_id)
self.xmanager.sync_trunk(
ctxt, payload={constants.JT_TRUNK_SYNC: combine_id})
def configure_security_group_rules(self, ctxt, project_id):
pass
class FakeRPCAPI(FakeBaseRPCAPI):
def __init__(self, fake_plugin):
self.xmanager = FakeXManager(fake_plugin)
class FakeNeutronClient(test_utils.FakeNeutronClient):
_resource = 'trunk'
trunks_path = ''
class FakeClient(test_utils.FakeClient):
def __init__(self, region_name=None):
super(FakeClient, self).__init__(region_name)
self.client = FakeNeutronClient(self.region_name)
def get_native_client(self, resource, ctx):
return self.client
def get_trunks(self, ctx, trunk_id):
return self.get_resource(constants.RT_TRUNK, ctx, trunk_id)
def update_trunks(self, context, trunk_id, trunk):
self.update_resources(constants.RT_TRUNK, context, trunk_id, trunk)
def delete_trunks(self, context, trunk_id):
self.delete_resources(constants.RT_TRUNK, context, trunk_id)
def action_trunks(self, ctx, action, resource_id, body):
if self.region_name == 'pod_1':
btm_trunks = BOTTOM1_TRUNKS
else:
btm_trunks = BOTTOM2_TRUNKS
for trunk in btm_trunks:
if trunk['id'] == resource_id:
subports = body['sub_ports']
if action == 'add_subports':
for subport in subports:
subport['trunk_id'] = resource_id
trunk['sub_ports'].extend(subports)
return
elif action == 'remove_subports':
for subport in subports:
for b_subport in trunk['sub_ports']:
if subport['port_id'] == b_subport['port_id']:
trunk['sub_ports'].remove(b_subport)
return
def list_trunks(self, ctx, filters=None):
filter_dict = {}
filters = filters or []
for query_filter in filters:
key = query_filter['key']
# when querying trunks, "fields" is passed in the query string to
# ask the server to only return necessary fields, which can reduce
# the data being transferred. In test, we just return all the
# fields since there's no need to optimize
if key != 'fields':
value = query_filter['value']
filter_dict[key] = value
return self.client.get('', filter_dict)['trunks']
def get_ports(self, ctx, port_id):
pass
def list_ports(self, ctx, filters=None):
fake_plugin = FakePlugin()
q_ctx = FakeNeutronContext()
_filters = {}
for f in filters:
_filters[f['key']] = [f['value']]
return fake_plugin.get_trunk_subports(q_ctx, _filters)
def create_ports(self, ctx, body):
if 'ports' in body:
ret = []
for port in body['ports']:
p = self.create_resources('port', ctx, {'port': port})
p['id'] = p['device_id']
ret.append(p)
return ret
return self.create_resources('port', ctx, body)
class FakeNeutronContext(test_utils.FakeNeutronContext):
def session_class(self):
return FakeSession
class FakeSession(test_utils.FakeSession):
def add_hook(self, model_obj, model_dict):
if model_obj.__tablename__ == 'subports':
for top_trunk in TOP_TRUNKS:
if top_trunk['id'] == model_dict['trunk_id']:
top_trunk['sub_ports'].append(model_dict)
def delete_top_subport(self, port_id):
for res_list in self.resource_store.store_map.values():
for res in res_list:
sub_ports = res.get('sub_ports')
if sub_ports:
for sub_port in sub_ports:
if sub_port['port_id'] == port_id:
sub_ports.remove(sub_port)
def delete_hook(self, model_obj):
if model_obj.get('segmentation_type'):
self.delete_top_subport(model_obj['port_id'])
return 'port_id'
class FakePlugin(trunk_plugin.TricircleTrunkPlugin):
def __init__(self):
self._segmentation_types = {'vlan': utils.is_valid_vlan_tag}
self.xjob_handler = FakeRPCAPI(self)
self.helper = helper.NetworkHelper(self)
def _get_client(self, region_name):
return FakeClient(region_name)
def fake_get_context_from_neutron_context(q_context):
ctx = context.get_db_context()
return ctx
def fake_get_min_search_step(self):
return 2
class FakeCorePlugin(central_plugin.TricirclePlugin):
def __init__(self):
self.type_manager = test_utils.FakeTypeManager()
def get_port(self, context, port_id):
return {portbindings.HOST_ID: None,
'device_id': None}
def get_ports(self, ctx, filters):
top_client = FakeClient()
_filters = []
for key, values in six.iteritems(filters):
for v in values:
_filters.append({'key': key, 'comparator': 'eq', 'value': v})
return top_client.list_resources('port', ctx, _filters)
def update_port(self, context, id, port):
port_body = port['port']
for _port in TOP_PORTS:
if _port['id'] == id:
for key, value in six.iteritems(port_body):
_port[key] = value
class PluginTest(unittest.TestCase):
def setUp(self):
core.initialize()
core.ModelBase.metadata.create_all(core.get_engine())
cfg.CONF.register_opts(q_config.core_opts)
self.context = context.Context()
cfg.CONF.set_override('tenant_network_types', ['local', 'vlan'],
group='tricircle')
cfg.CONF.set_override('bridge_network_type', 'vlan',
group='tricircle')
xmanager.IN_TEST = True
def fake_get_plugin(alias='core'):
if alias == 'trunk':
return FakePlugin()
return FakeCorePlugin()
directory.get_plugin = fake_get_plugin
def _basic_pod_setup(self):
pod1 = {'pod_id': 'pod_id_1',
'region_name': 'pod_1',
'az_name': 'az_name_1'}
pod2 = {'pod_id': 'pod_id_2',
'region_name': 'pod_2',
'az_name': 'az_name_2'}
pod3 = {'pod_id': 'pod_id_0',
'region_name': 'top_pod',
'az_name': ''}
for pod in (pod1, pod2, pod3):
db_api.create_pod(self.context, pod)
def _prepare_port_test(self, tenant_id, ctx, pod_name, index,
device_onwer='compute:None', create_bottom=True):
t_port_id = uuidutils.generate_uuid()
t_subnet_id = uuidutils.generate_uuid()
t_net_id = uuidutils.generate_uuid()
t_port = {
'id': t_port_id,
'name': 'top_port_%d' % index,
'description': 'old_top_description',
'extra_dhcp_opts': [],
'device_owner': device_onwer,
'security_groups': [],
'device_id': '68f46ee4-d66a-4c39-bb34-ac2e5eb85470',
'admin_state_up': True,
'network_id': t_net_id,
'tenant_id': tenant_id,
'mac_address': 'fa:16:3e:cd:76:4%s' % index,
'project_id': 'tenant_id',
'binding:host_id': 'zhiyuan-5',
'status': 'ACTIVE',
'network_id': t_net_id,
'fixed_ips': [{'subnet_id': t_subnet_id}]
}
TOP_PORTS.append(test_utils.DotDict(t_port))
if create_bottom:
b_port = {
'id': t_port_id,
'name': t_port_id,
'description': 'old_bottom_description',
'extra_dhcp_opts': [],
'device_owner': device_onwer,
'security_groups': [],
'device_id': '68f46ee4-d66a-4c39-bb34-ac2e5eb85470',
'admin_state_up': True,
'network_id': t_net_id,
'tenant_id': tenant_id,
'device_owner': 'compute:None',
'extra_dhcp_opts': [],
'mac_address': 'fa:16:3e:cd:76:40',
'project_id': 'tenant_id',
'binding:host_id': 'zhiyuan-5',
'status': 'ACTIVE',
'network_id': t_net_id,
'fixed_ips': [{'subnet_id': t_subnet_id}]
}
if pod_name == 'pod_1':
BOTTOM1_PORTS.append(test_utils.DotDict(b_port))
else:
BOTTOM2_PORTS.append(test_utils.DotDict(b_port))
pod_id = 'pod_id_1' if pod_name == 'pod_1' else 'pod_id_2'
core.create_resource(ctx, models.ResourceRouting,
{'top_id': t_port_id,
'bottom_id': t_port_id,
'pod_id': pod_id,
'project_id': tenant_id,
'resource_type': constants.RT_PORT})
return t_port_id
def _prepare_trunk_test(self, project_id, ctx, pod_name, index,
is_create_bottom, t_uuid=None, b_uuid=None):
t_trunk_id = t_uuid or uuidutils.generate_uuid()
b_trunk_id = b_uuid or uuidutils.generate_uuid()
t_parent_port_id = uuidutils.generate_uuid()
t_sub_port_id = self._prepare_port_test(
project_id, ctx, pod_name, index, create_bottom=is_create_bottom)
t_subport = {
'segmentation_type': 'vlan',
'port_id': t_sub_port_id,
'segmentation_id': 164,
'trunk_id': t_trunk_id}
t_trunk = {
'id': t_trunk_id,
'name': 'top_trunk_%d' % index,
'status': 'DOWN',
'description': 'created',
'admin_state_up': True,
'port_id': t_parent_port_id,
'tenant_id': project_id,
'project_id': project_id,
'sub_ports': [t_subport]
}
TOP_TRUNKS.append(test_utils.DotDict(t_trunk))
TOP_SUBPORTS.append(test_utils.DotDict(t_subport))
b_trunk = None
if is_create_bottom:
b_subport = {
'segmentation_type': 'vlan',
'port_id': t_sub_port_id,
'segmentation_id': 164,
'trunk_id': b_trunk_id}
b_trunk = {
'id': b_trunk_id,
'name': 'top_trunk_%d' % index,
'status': 'UP',
'description': 'created',
'admin_state_up': True,
'port_id': t_parent_port_id,
'tenant_id': project_id,
'project_id': project_id,
'sub_ports': [b_subport]
}
if pod_name == 'pod_1':
BOTTOM1_SUBPORTS.append(test_utils.DotDict(t_subport))
BOTTOM1_TRUNKS.append(test_utils.DotDict(b_trunk))
else:
BOTTOM2_SUBPORTS.append(test_utils.DotDict(t_subport))
BOTTOM2_TRUNKS.append(test_utils.DotDict(b_trunk))
pod_id = 'pod_id_1' if pod_name == 'pod_1' else 'pod_id_2'
core.create_resource(ctx, models.ResourceRouting,
{'top_id': t_trunk_id,
'bottom_id': b_trunk_id,
'pod_id': pod_id,
'project_id': project_id,
'resource_type': constants.RT_TRUNK})
return t_trunk, b_trunk
@patch.object(context, 'get_context_from_neutron_context',
new=fake_get_context_from_neutron_context)
def test_get_trunk(self):
project_id = TEST_TENANT_ID
q_ctx = FakeNeutronContext()
t_ctx = context.get_db_context()
self._basic_pod_setup()
fake_plugin = FakePlugin()
t_trunk, b_trunk = self._prepare_trunk_test(project_id, t_ctx,
'pod_1', 1, True)
res = fake_plugin.get_trunk(q_ctx, t_trunk['id'])
t_trunk['status'] = b_trunk['status']
t_trunk['sub_ports'][0].pop('trunk_id')
six.assertCountEqual(self, t_trunk, res)
@patch.object(context, 'get_context_from_neutron_context',
new=fake_get_context_from_neutron_context)
def test_get_trunks(self):
project_id = TEST_TENANT_ID
q_ctx = FakeNeutronContext()
t_ctx = context.get_db_context()
self._basic_pod_setup()
fake_plugin = FakePlugin()
t_trunk1, _ = self._prepare_trunk_test(project_id, t_ctx,
'pod_1', 1, True)
t_trunk2, _ = self._prepare_trunk_test(project_id, t_ctx,
'pod_1', 2, True)
t_trunk3, _ = self._prepare_trunk_test(project_id, t_ctx,
'pod_2', 3, True)
t_trunk4, _ = self._prepare_trunk_test(project_id, t_ctx,
'pod_2', 4, True)
t_trunk5, _ = self._prepare_trunk_test(project_id, t_ctx,
'pod_1', 5, False)
t_trunk6, _ = self._prepare_trunk_test(project_id, t_ctx,
'pod_1', 6, False)
res = fake_plugin.get_trunks(q_ctx)
self.assertEqual(len(res), 6)
res = fake_plugin.get_trunks(
q_ctx, filters={'id': [t_trunk1['id']]}, limit=3)
t_trunk1['status'] = 'UP'
res[0]['sub_ports'][0]['trunk_id'] = t_trunk1['id']
six.assertCountEqual(self, [t_trunk1], res)
res = fake_plugin.get_trunks(q_ctx, filters={'id': [t_trunk5['id']]})
t_trunk5['sub_ports'][0].pop('trunk_id')
six.assertCountEqual(self, [t_trunk5], res)
trunks = fake_plugin.get_trunks(q_ctx,
filters={'status': ['UP'],
'description': ['created']})
self.assertEqual(len(trunks), 4)
@patch.object(context, 'get_context_from_neutron_context',
new=fake_get_context_from_neutron_context)
@patch.object(FakePlugin, '_get_min_search_step',
new=fake_get_min_search_step)
def test_get_trunks_pagination(self):
project_id = TEST_TENANT_ID
q_ctx = FakeNeutronContext()
t_ctx = context.get_db_context()
self._basic_pod_setup()
fake_plugin = FakePlugin()
t_trunk1, _ = self._prepare_trunk_test(
project_id, t_ctx, 'pod_1', 1, True,
'101779d0-e30e-495a-ba71-6265a1669701',
'1b1779d0-e30e-495a-ba71-6265a1669701')
t_trunk2, _ = self._prepare_trunk_test(
project_id, t_ctx, 'pod_1', 2, True,
'201779d0-e30e-495a-ba71-6265a1669701',
'2b1779d0-e30e-495a-ba71-6265a1669701')
t_trunk3, _ = self._prepare_trunk_test(
project_id, t_ctx, 'pod_2', 3, True,
'301779d0-e30e-495a-ba71-6265a1669701',
'3b1779d0-e30e-495a-ba71-6265a1669701')
t_trunk4, _ = self._prepare_trunk_test(
project_id, t_ctx, 'pod_2', 4, True,
'401779d0-e30e-495a-ba71-6265a1669701',
'4b1779d0-e30e-495a-ba71-6265a1669701')
t_trunk5, _ = self._prepare_trunk_test(
project_id, t_ctx, 'pod_2', 5, False,
'501779d0-e30e-495a-ba71-6265a1669701')
t_trunk6, _ = self._prepare_trunk_test(
project_id, t_ctx, 'pod_2', 6, False,
'601779d0-e30e-495a-ba71-6265a1669701')
t_trunk7, _ = self._prepare_trunk_test(
project_id, t_ctx, 'pod_2', 7, False,
'601779d0-e30e-495a-ba71-6265a1669701')
# limit no marker
res = fake_plugin.get_trunks(q_ctx, limit=3)
res_trunk_ids = [trunk['id'] for trunk in res]
except_trunk_ids = [t_trunk1['id'], t_trunk2['id'], t_trunk3['id']]
self.assertEqual(res_trunk_ids, except_trunk_ids)
# limit and top pod's marker
res = fake_plugin.get_trunks(q_ctx, limit=3, marker=t_trunk5['id'])
res_trunk_ids = [trunk['id'] for trunk in res]
except_trunk_ids = [t_trunk6['id'], t_trunk7['id']]
self.assertEqual(res_trunk_ids, except_trunk_ids)
# limit and bottom pod's marker
res = fake_plugin.get_trunks(q_ctx, limit=6, marker=t_trunk1['id'])
res_trunk_ids = [trunk['id'] for trunk in res]
except_trunk_ids = [t_trunk2['id'], t_trunk3['id'], t_trunk4['id'],
t_trunk5['id'], t_trunk6['id'], t_trunk7['id']]
self.assertEqual(res_trunk_ids, except_trunk_ids)
# limit and bottom pod's marker and filters
res = fake_plugin.get_trunks(q_ctx, limit=6, marker=t_trunk1['id'],
filters={'status': ['UP']})
res_trunk_ids = [trunk['id'] for trunk in res]
except_trunk_ids = [t_trunk2['id'], t_trunk3['id'], t_trunk4['id']]
self.assertEqual(res_trunk_ids, except_trunk_ids)
@patch.object(context, 'get_context_from_neutron_context',
new=fake_get_context_from_neutron_context)
def test_update_trunk(self):
project_id = TEST_TENANT_ID
q_ctx = FakeNeutronContext()
t_ctx = context.get_db_context()
self._basic_pod_setup()
fake_plugin = FakePlugin()
t_trunk, b_trunk = self._prepare_trunk_test(project_id, t_ctx,
'pod_1', 1, True)
update_body = {'trunk': {
'name': 'new_name',
'description': 'updated',
'admin_state_up': False}
}
updated_top_trunk = fake_plugin.update_trunk(q_ctx, t_trunk['id'],
update_body)
self.assertEqual(updated_top_trunk['name'], 'new_name')
self.assertEqual(updated_top_trunk['description'], 'updated')
self.assertFalse(updated_top_trunk['admin_state_up'])
updated_btm_trunk = fake_plugin.get_trunk(q_ctx, t_trunk['id'])
self.assertEqual(updated_btm_trunk['name'], 'new_name')
self.assertEqual(updated_btm_trunk['description'], 'updated')
self.assertFalse(updated_btm_trunk['admin_state_up'])
@patch.object(db_base_plugin_v2.NeutronDbPluginV2, 'get_ports',
new=FakeCorePlugin.get_ports)
@patch.object(db_base_plugin_v2.NeutronDbPluginV2, 'update_port',
new=FakeCorePlugin.update_port)
@patch.object(context, 'get_context_from_neutron_context',
new=fake_get_context_from_neutron_context)
def test_action_subports(self):
project_id = TEST_TENANT_ID
t_ctx = context.get_db_context()
self._basic_pod_setup()
t_trunk, b_trunk = self._prepare_trunk_test(project_id, t_ctx,
'pod_1', 1, True)
add_subport_id1 = self._prepare_port_test(project_id, t_ctx, 'pod_1',
1, create_bottom=False)
add_subport_id2 = self._prepare_port_test(project_id, t_ctx, 'pod_1',
2, create_bottom=False)
add_subport_id3 = self._prepare_port_test(project_id, t_ctx, 'pod_1',
3, create_bottom=False)
add_subport_id4 = self._prepare_port_test(project_id, t_ctx, 'pod_1',
4, create_bottom=False)
add_subport_id5 = self._prepare_port_test(project_id, t_ctx, 'pod_1',
5, create_bottom=False)
add_subport_id6 = self._prepare_port_test(project_id, t_ctx, 'pod_1',
6, create_bottom=True)
add_subport_id7 = self._prepare_port_test(project_id, t_ctx, 'pod_1',
7, create_bottom=True)
add_subport_id8 = self._prepare_port_test(project_id, t_ctx, 'pod_1',
8, create_bottom=False)
add_subport_id9 = self._prepare_port_test(project_id, t_ctx, 'pod_1',
9, create_bottom=False)
# Avoid warning: assigned to but never used
ids = [add_subport_id1, add_subport_id2, add_subport_id3,
add_subport_id4, add_subport_id5, add_subport_id6,
add_subport_id7, add_subport_id8, add_subport_id9]
ids.sort()
remove_subports = {'segmentation_type': 'vlan',
'port_id': uuidutils.generate_uuid(),
'segmentation_id': 165}
b_trunk['sub_ports'].append(remove_subports)
add_subports = []
for _id in xrange(1, 10):
port_id = eval("add_subport_id%d" % _id)
subport = {
'segmentation_type': 'vlan',
'port_id': port_id,
'segmentation_id': _id}
add_subports.append(subport)
def tearDown(self):
core.ModelBase.metadata.drop_all(core.get_engine())
test_utils.get_resource_store().clean()
cfg.CONF.unregister_opts(q_config.core_opts)
xmanager.IN_TEST = False
|
stackforge/tricircle
|
tricircle/tests/unit/network/test_central_trunk_plugin.py
|
Python
|
apache-2.0
| 24,196 | 0 |
# -*- coding: utf-8 -*-
__license__ = 'GPL v3'
__copyright__ = '2009, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
'''
Read content from txt file.
'''
import os, re
from calibre import prepare_string_for_xml, isbytestring
from calibre.ebooks.metadata.opf2 import OPFCreator
from calibre.ebooks.conversion.preprocess import DocAnalysis
from calibre.utils.cleantext import clean_ascii_chars
HTML_TEMPLATE = u'<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>%s </title></head><body>\n%s\n</body></html>'
def clean_txt(txt):
'''
Run transformations on the text to put it into
consistent state.
'''
if isbytestring(txt):
txt = txt.decode('utf-8', 'replace')
# Strip whitespace from the end of the line. Also replace
# all line breaks with \n.
txt = '\n'.join([line.rstrip() for line in txt.splitlines()])
# Replace whitespace at the beginning of the line with
txt = re.sub('(?m)(?<=^)([ ]{2,}|\t+)(?=.)', ' ' * 4, txt)
# Condense redundant spaces
txt = re.sub('[ ]{2,}', ' ', txt)
# Remove blank space from the beginning and end of the document.
txt = re.sub('^\s+(?=.)', '', txt)
txt = re.sub('(?<=.)\s+$', '', txt)
# Remove excessive line breaks.
txt = re.sub('\n{5,}', '\n\n\n\n', txt)
#remove ASCII invalid chars : 0 to 8 and 11-14 to 24
txt = clean_ascii_chars(txt)
return txt
def split_txt(txt, epub_split_size_kb=0):
'''
Ensure there are split points for converting
to EPUB. A misdetected paragraph type can
result in the entire document being one giant
paragraph. In this case the EPUB parser will not
be able to determine where to split the file
to accomidate the EPUB file size limitation
and will fail.
'''
#Takes care if there is no point to split
if epub_split_size_kb > 0:
if isinstance(txt, unicode):
txt = txt.encode('utf-8')
length_byte = len(txt)
#Calculating the average chunk value for easy splitting as EPUB (+2 as a safe margin)
chunk_size = long(length_byte / (int(length_byte / (epub_split_size_kb * 1024) ) + 2 ))
#if there are chunks with a superior size then go and break
if (len(filter(lambda x: len(x) > chunk_size, txt.split('\n\n')))) :
txt = '\n\n'.join([split_string_separator(line, chunk_size)
for line in txt.split('\n\n')])
if isbytestring(txt):
txt = txt.decode('utf-8')
return txt
def convert_basic(txt, title='', epub_split_size_kb=0):
'''
Converts plain text to html by putting all paragraphs in
<p> tags. It condense and retains blank lines when necessary.
Requires paragraphs to be in single line format.
'''
txt = clean_txt(txt)
txt = split_txt(txt, epub_split_size_kb)
lines = []
blank_count = 0
# Split into paragraphs based on having a blank line between text.
for line in txt.split('\n'):
if line.strip():
blank_count = 0
lines.append(u'<p>%s</p>' % prepare_string_for_xml(line.replace('\n', ' ')))
else:
blank_count += 1
if blank_count == 2:
lines.append(u'<p> </p>')
return HTML_TEMPLATE % (title, u'\n'.join(lines))
def convert_markdown(txt, title='', disable_toc=False):
from calibre.ebooks.markdown import markdown
extensions=['footnotes', 'tables']
if not disable_toc:
extensions.append('toc')
md = markdown.Markdown(
extensions,
safe_mode=False)
return HTML_TEMPLATE % (title, md.convert(txt))
def convert_textile(txt, title=''):
from calibre.ebooks.textile import textile
html = textile(txt, encoding='utf-8')
return HTML_TEMPLATE % (title, html)
def normalize_line_endings(txt):
txt = txt.replace('\r\n', '\n')
txt = txt.replace('\r', '\n')
return txt
def separate_paragraphs_single_line(txt):
txt = txt.replace('\n', '\n\n')
return txt
def separate_paragraphs_print_formatted(txt):
txt = re.sub(u'(?miu)^(?P<indent>\t+|[ ]{2,})(?=.)', lambda mo: '\n%s' % mo.group('indent'), txt)
return txt
def separate_hard_scene_breaks(txt):
def sep_break(line):
if len(line.strip()) > 0:
return '\n%s\n' % line
else:
return line
txt = re.sub(u'(?miu)^[ \t-=~\/_]+$', lambda mo: sep_break(mo.group()), txt)
return txt
def block_to_single_line(txt):
txt = re.sub(r'(?<=.)\n(?=.)', ' ', txt)
return txt
def preserve_spaces(txt):
'''
Replaces spaces multiple spaces with entities.
'''
txt = re.sub('(?P<space>[ ]{2,})', lambda mo: ' ' + (' ' * (len(mo.group('space')) - 1)), txt)
txt = txt.replace('\t', ' ')
return txt
def remove_indents(txt):
'''
Remove whitespace at the beginning of each line.
'''
txt = re.sub('(?miu)^\s+', '', txt)
return txt
def opf_writer(path, opf_name, manifest, spine, mi):
opf = OPFCreator(path, mi)
opf.create_manifest(manifest)
opf.create_spine(spine)
with open(os.path.join(path, opf_name), 'wb') as opffile:
opf.render(opffile)
def split_string_separator(txt, size):
'''
Splits the text by putting \n\n at the point size.
'''
if len(txt) > size:
txt = ''.join([re.sub(u'\.(?P<ends>[^.]*)$', '.\n\n\g<ends>',
txt[i:i+size], 1) for i in
xrange(0, len(txt), size)])
return txt
def detect_paragraph_type(txt):
'''
Tries to determine the paragraph type of the document.
block: Paragraphs are separated by a blank line.
single: Each line is a paragraph.
print: Each paragraph starts with a 2+ spaces or a tab
and ends when a new paragraph is reached.
unformatted: most lines have hard line breaks, few/no blank lines or indents
returns block, single, print, unformatted
'''
txt = txt.replace('\r\n', '\n')
txt = txt.replace('\r', '\n')
txt_line_count = len(re.findall('(?mu)^\s*.+$', txt))
# Check for hard line breaks - true if 55% of the doc breaks in the same region
docanalysis = DocAnalysis('txt', txt)
hardbreaks = docanalysis.line_histogram(.55)
if hardbreaks:
# Determine print percentage
tab_line_count = len(re.findall('(?mu)^(\t|\s{2,}).+$', txt))
print_percent = tab_line_count / float(txt_line_count)
# Determine block percentage
empty_line_count = len(re.findall('(?mu)^\s*$', txt))
block_percent = empty_line_count / float(txt_line_count)
# Compare the two types - the type with the larger number of instances wins
# in cases where only one or the other represents the vast majority of the document neither wins
if print_percent >= block_percent:
if .15 <= print_percent <= .75:
return 'print'
elif .15 <= block_percent <= .75:
return 'block'
# Assume unformatted text with hardbreaks if nothing else matches
return 'unformatted'
# return single if hardbreaks is false
return 'single'
def detect_formatting_type(txt):
'''
Tries to determine the formatting of the document.
markdown: Markdown formatting is used.
textile: Textile formatting is used.
heuristic: When none of the above formatting types are
detected heuristic is returned.
'''
# Keep a count of the number of format specific object
# that are found in the text.
markdown_count = 0
textile_count = 0
# Check for markdown
# Headings
markdown_count += len(re.findall('(?mu)^#+', txt))
markdown_count += len(re.findall('(?mu)^=+$', txt))
markdown_count += len(re.findall('(?mu)^-+$', txt))
# Images
markdown_count += len(re.findall('(?u)!\[.*?\](\[|\()', txt))
# Links
markdown_count += len(re.findall('(?u)^|[^!]\[.*?\](\[|\()', txt))
# Check for textile
# Headings
textile_count += len(re.findall(r'(?mu)^h[1-6]\.', txt))
# Block quote.
textile_count += len(re.findall(r'(?mu)^bq\.', txt))
# Images
textile_count += len(re.findall(r'(?mu)(?<=\!)\S+(?=\!)', txt))
# Links
textile_count += len(re.findall(r'"[^"]*":\S+', txt))
# paragraph blocks
textile_count += len(re.findall(r'(?mu)^p(<|<>|=|>)?\. ', txt))
# Decide if either markdown or textile is used in the text
# based on the number of unique formatting elements found.
if markdown_count > 5 or textile_count > 5:
if markdown_count > textile_count:
return 'markdown'
else:
return 'textile'
return 'heuristic'
|
yeyanchao/calibre
|
src/calibre/ebooks/txt/processor.py
|
Python
|
gpl-3.0
| 8,709 | 0.006889 |
from binsearch import BinSearch
from nzbclub import NZBClub
from nzbindex import NZBIndex
from bs4 import BeautifulSoup
from couchpotato.core.helpers.variable import getTitle, splitString, tryInt
from couchpotato.core.helpers.encoding import simplifyString
from couchpotato.environment import Env
from couchpotato.core.logger import CPLog
from couchpotato.core.helpers import namer_check
from couchpotato.core.media._base.providers.nzb.base import NZBProvider
log = CPLog(__name__)
import re
import urllib
import urllib2
import traceback
class Base(NZBProvider):
urls = {
'download': 'http://www.binnews.in/',
'detail': 'http://www.binnews.in/',
'search': 'http://www.binnews.in/_bin/search2.php',
}
http_time_between_calls = 4 # Seconds
cat_backup_id = None
def _search(self, movie, quality, results):
nzbDownloaders = [NZBClub(), BinSearch(), NZBIndex()]
MovieTitles = movie['info']['titles']
moviequality = simplifyString(quality['identifier'])
movieyear = movie['info']['year']
if quality['custom']['3d']==1:
threeD= True
else:
threeD=False
if moviequality in ("720p","1080p","bd50"):
cat1='39'
cat2='49'
minSize = 2000
elif moviequality in ("dvdr"):
cat1='23'
cat2='48'
minSize = 3000
else:
cat1='6'
cat2='27'
minSize = 500
for MovieTitle in MovieTitles:
try:
TitleStringReal = str(MovieTitle.encode("latin-1").replace('-',' '))
except:
continue
if threeD:
TitleStringReal = TitleStringReal + ' 3d'
data = 'chkInit=1&edTitre='+TitleStringReal+'&chkTitre=on&chkFichier=on&chkCat=on&cats%5B%5D='+cat1+'&cats%5B%5D='+cat2+'&edAge=&edYear='
try:
soup = BeautifulSoup( urllib2.urlopen(self.urls['search'], data) )
except Exception, e:
log.error(u"Error trying to load BinNewz response: "+e)
return []
tables = soup.findAll("table", id="tabliste")
for table in tables:
rows = table.findAll("tr")
for row in rows:
cells = row.select("> td")
if (len(cells) < 11):
continue
name = cells[2].text.strip()
testname=namer_check.correctName(name,movie)
if testname==0:
continue
language = cells[3].find("img").get("src")
if not "_fr" in language and not "_frq" in language:
continue
detectedlang=''
if "_fr" in language:
detectedlang=' truefrench '
else:
detectedlang=' french '
# blacklist_groups = [ "alt.binaries.multimedia" ]
blacklist_groups = []
newgroupLink = cells[4].find("a")
newsgroup = None
if newgroupLink.contents:
newsgroup = newgroupLink.contents[0]
if newsgroup == "abmulti":
newsgroup = "alt.binaries.multimedia"
elif newsgroup == "ab.moovee":
newsgroup = "alt.binaries.moovee"
elif newsgroup == "abtvseries":
newsgroup = "alt.binaries.tvseries"
elif newsgroup == "abtv":
newsgroup = "alt.binaries.tv"
elif newsgroup == "a.b.teevee":
newsgroup = "alt.binaries.teevee"
elif newsgroup == "abstvdivxf":
newsgroup = "alt.binaries.series.tv.divx.french"
elif newsgroup == "abhdtvx264fr":
newsgroup = "alt.binaries.hdtv.x264.french"
elif newsgroup == "abmom":
newsgroup = "alt.binaries.mom"
elif newsgroup == "abhdtv":
newsgroup = "alt.binaries.hdtv"
elif newsgroup == "abboneless":
newsgroup = "alt.binaries.boneless"
elif newsgroup == "abhdtvf":
newsgroup = "alt.binaries.hdtv.french"
elif newsgroup == "abhdtvx264":
newsgroup = "alt.binaries.hdtv.x264"
elif newsgroup == "absuperman":
newsgroup = "alt.binaries.superman"
elif newsgroup == "abechangeweb":
newsgroup = "alt.binaries.echange-web"
elif newsgroup == "abmdfvost":
newsgroup = "alt.binaries.movies.divx.french.vost"
elif newsgroup == "abdvdr":
newsgroup = "alt.binaries.dvdr"
elif newsgroup == "abmzeromov":
newsgroup = "alt.binaries.movies.zeromovies"
elif newsgroup == "abcfaf":
newsgroup = "alt.binaries.cartoons.french.animes-fansub"
elif newsgroup == "abcfrench":
newsgroup = "alt.binaries.cartoons.french"
elif newsgroup == "abgougouland":
newsgroup = "alt.binaries.gougouland"
elif newsgroup == "abroger":
newsgroup = "alt.binaries.roger"
elif newsgroup == "abtatu":
newsgroup = "alt.binaries.tatu"
elif newsgroup =="abstvf":
newsgroup = "alt.binaries.series.tv.french"
elif newsgroup =="abmdfreposts":
newsgroup="alt.binaries.movies.divx.french.reposts"
elif newsgroup =="abmdf":
newsgroup="alt.binaries.movies.french"
elif newsgroup =="abhdtvfrepost":
newsgroup="alt.binaries.hdtv.french.repost"
elif newsgroup == "abmmkv":
newsgroup = "alt.binaries.movies.mkv"
elif newsgroup == "abf-tv":
newsgroup = "alt.binaries.french-tv"
elif newsgroup == "abmdfo":
newsgroup = "alt.binaries.movies.divx.french.old"
elif newsgroup == "abmf":
newsgroup = "alt.binaries.movies.french"
elif newsgroup == "ab.movies":
newsgroup = "alt.binaries.movies"
elif newsgroup == "a.b.french":
newsgroup = "alt.binaries.french"
elif newsgroup == "a.b.3d":
newsgroup = "alt.binaries.3d"
elif newsgroup == "ab.dvdrip":
newsgroup = "alt.binaries.dvdrip"
elif newsgroup == "ab.welovelori":
newsgroup = "alt.binaries.welovelori"
elif newsgroup == "abblu-ray":
newsgroup = "alt.binaries.blu-ray"
elif newsgroup == "ab.bloaf":
newsgroup = "alt.binaries.bloaf"
elif newsgroup == "ab.hdtv.german":
newsgroup = "alt.binaries.hdtv.german"
elif newsgroup == "abmd":
newsgroup = "alt.binaries.movies.divx"
elif newsgroup == "ab.ath":
newsgroup = "alt.binaries.ath"
elif newsgroup == "a.b.town":
newsgroup = "alt.binaries.town"
elif newsgroup == "a.b.u-4all":
newsgroup = "alt.binaries.u-4all"
elif newsgroup == "ab.amazing":
newsgroup = "alt.binaries.amazing"
elif newsgroup == "ab.astronomy":
newsgroup = "alt.binaries.astronomy"
elif newsgroup == "ab.nospam.cheer":
newsgroup = "alt.binaries.nospam.cheerleaders"
elif newsgroup == "ab.worms":
newsgroup = "alt.binaries.worms"
elif newsgroup == "abcores":
newsgroup = "alt.binaries.cores"
elif newsgroup == "abdvdclassics":
newsgroup = "alt.binaries.dvd.classics"
elif newsgroup == "abdvdf":
newsgroup = "alt.binaries.dvd.french"
elif newsgroup == "abdvds":
newsgroup = "alt.binaries.dvds"
elif newsgroup == "abmdfrance":
newsgroup = "alt.binaries.movies.divx.france"
elif newsgroup == "abmisc":
newsgroup = "alt.binaries.misc"
elif newsgroup == "abnl":
newsgroup = "alt.binaries.nl"
elif newsgroup == "abx":
newsgroup = "alt.binaries.x"
else:
log.error(u"Unknown binnewz newsgroup: " + newsgroup)
continue
if newsgroup in blacklist_groups:
log.error(u"Ignoring result, newsgroup is blacklisted: " + newsgroup)
continue
filename = cells[5].contents[0]
m = re.search("^(.+)\s+{(.*)}$", name)
qualityStr = ""
if m:
name = m.group(1)
qualityStr = m.group(2)
m = re.search("^(.+)\s+\[(.*)\]$", name)
source = None
if m:
name = m.group(1)
source = m.group(2)
m = re.search("(.+)\(([0-9]{4})\)", name)
year = ""
if m:
name = m.group(1)
year = m.group(2)
if int(year) > movieyear + 1 or int(year) < movieyear - 1:
continue
m = re.search("(.+)\((\d{2}/\d{2}/\d{4})\)", name)
dateStr = ""
if m:
name = m.group(1)
dateStr = m.group(2)
year = dateStr[-5:].strip(")").strip("/")
m = re.search("(.+)\s+S(\d{2})\s+E(\d{2})(.*)", name)
if m:
name = m.group(1) + " S" + m.group(2) + "E" + m.group(3) + m.group(4)
m = re.search("(.+)\s+S(\d{2})\s+Ep(\d{2})(.*)", name)
if m:
name = m.group(1) + " S" + m.group(2) + "E" + m.group(3) + m.group(4)
filenameLower = filename.lower()
searchItems = []
if qualityStr=="":
if source in ("Blu Ray-Rip", "HD DVD-Rip"):
qualityStr="brrip"
elif source =="DVDRip":
qualityStr="dvdrip"
elif source == "TS":
qualityStr ="ts"
elif source == "DVDSCR":
qualityStr ="scr"
elif source == "CAM":
qualityStr ="cam"
elif moviequality == "dvdr":
qualityStr ="dvdr"
if year =='':
year = '1900'
if len(searchItems) == 0 and qualityStr == str(moviequality):
searchItems.append( filename )
for searchItem in searchItems:
resultno=1
for downloader in nzbDownloaders:
log.info("Searching for download : " + name + ", search string = "+ searchItem + " on " + downloader.__class__.__name__)
try:
binsearch_result = downloader.search(searchItem, minSize, newsgroup )
if binsearch_result:
new={}
def extra_check(item):
return True
qualitytag=''
if qualityStr.lower() in ['720p','1080p']:
qualitytag=' hd x264 h264 '
elif qualityStr.lower() in ['dvdrip']:
qualitytag=' dvd xvid '
elif qualityStr.lower() in ['brrip']:
qualitytag=' hdrip '
elif qualityStr.lower() in ['ts']:
qualitytag=' webrip '
elif qualityStr.lower() in ['scr']:
qualitytag=''
elif qualityStr.lower() in ['dvdr']:
qualitytag=' pal video_ts '
new['id'] = binsearch_result.nzbid
new['name'] = name + detectedlang + qualityStr + qualitytag + downloader.__class__.__name__
new['url'] = binsearch_result.nzburl
new['detail_url'] = binsearch_result.refererURL
new['size'] = binsearch_result.sizeInMegs
new['age'] = binsearch_result.age
new['extra_check'] = extra_check
results.append(new)
resultno=resultno+1
log.info("Found : " + searchItem + " on " + downloader.__class__.__name__)
if resultno==3:
break
except Exception, e:
log.error("Searching from " + downloader.__class__.__name__ + " failed : " + str(e) + traceback.format_exc())
def download(self, url = '', nzb_id = ''):
if 'binsearch' in url:
data = {
'action': 'nzb',
nzb_id: 'on'
}
try:
return self.urlopen(url, data = data, show_error = False)
except:
log.error('Failed getting nzb from %s: %s', (self.getName(), traceback.format_exc()))
return 'try_next'
else:
values = {
'url' : '/'
}
data_tmp = urllib.urlencode(values)
req = urllib2.Request(url, data_tmp )
try:
#log.error('Failed downloading from %s', self.getName())
return urllib2.urlopen(req).read()
except:
log.error('Failed downloading from %s: %s', (self.getName(), traceback.format_exc()))
return 'try_next'
config = [{
'name': 'binnewz',
'groups': [
{
'tab': 'searcher',
'list': 'nzb_providers',
'name': 'binnewz',
'description': 'Free provider, lots of french nzbs. See <a href="http://www.binnews.in/">binnewz</a>',
'wizard': True,
'icon': 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAgRJREFUOI1t009rVFcYx/HPuffOTGYmMcZoEmNUkiJRSZRAC1ropuimuy6KuHHhShe+EF+CL8AX4LpQCgoiohhMMKKMqHRTtaJJ5k8nudfFnBkjzoEf5zk8PN/zO3+egFGMYX+MS9hFG604d/A/ulG7yFFkqOGgcuUuSJK32q0NPMMaNrE9RC10UxzCedX6767cqDu2MGV8YlFz62ed9iWVkYvy/IyimEUSFaKD3QwV7ENwapmlHymVU5126tNHVh9MW3s8bfXhOW8b16TpliR5otW8jm6GHiSEYOYoF076Zjx6x29/8OHfssZzNp6Ou3XzF8zicxYtZWBislfUKL4CFgIvd5mcYuowed7PjKOSGTYWwiAsij6srChmJI058Q6qyIYD9jgIIQzWxXygPtZPpUj6gGJv/V4HGoViPsLWt77bK9P7FDtg8zPr21RrX48wT3g11OcA0MG2oii8aXB4jiInK5FmSAcOGBUawwFvtFuJO7dpbLBynuM/UK0Jn0YolXtqNfn4vl/bRZ7pfcsXdrqX3f/rhgd/L+m0J8zMdZ1eKTn7U7C4zNg+yhX+ed2/syZ2AkZQ12umSRyI8wpOqdaXdTszRmocOR5Mz2bu/ZnL81/xIsTnyFCOsKpeg9ViPBo1jxMq1UVpEjS3r+K/Pe81aJQ0qhShlQiuxPxOtL+J1heOZZ0e63LUQAAAAABJRU5ErkJggg==',
'options': [
{
'name': 'enabled',
'type': 'enabler',
'default': False,
},
{
'name': 'extra_score',
'advanced': True,
'label': 'Extra Score',
'type': 'int',
'default': 0,
'description': 'Starting score for each release found via this provider.',
}
],
},
],
}]
|
thedep2/CouchPotatoServer
|
couchpotato/core/media/_base/providers/nzb/binnewz/main.py
|
Python
|
gpl-3.0
| 18,081 | 0.008683 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
import tensorflow as tf
from niftynet.layer.downsample import DownSampleLayer
from tests.niftynet_testcase import NiftyNetTestCase
class DownSampleTest(NiftyNetTestCase):
def get_3d_input(self):
input_shape = (2, 16, 16, 16, 8)
x = tf.ones(input_shape)
return x
def get_2d_input(self):
input_shape = (2, 16, 16, 8)
x = tf.ones(input_shape)
return x
def _test_nd_downsample_output_shape(self,
rank,
param_dict,
output_shape):
if rank == 2:
input_data = self.get_2d_input()
elif rank == 3:
input_data = self.get_3d_input()
downsample_layer = DownSampleLayer(**param_dict)
output_data = downsample_layer(input_data)
print(downsample_layer)
with self.cached_session() as sess:
sess.run(tf.global_variables_initializer())
out = sess.run(output_data)
self.assertAllClose(output_shape, out.shape)
def test_3d_max_shape(self):
input_param = {'func': 'MAX',
'kernel_size': 3,
'stride': 3}
self._test_nd_downsample_output_shape(rank=3,
param_dict=input_param,
output_shape=(2, 6, 6, 6, 8))
def test_3d_avg_shape(self):
input_param = {'func': 'AVG',
'kernel_size': [3, 3, 2],
'stride': [3, 2, 1]}
self._test_nd_downsample_output_shape(rank=3,
param_dict=input_param,
output_shape=(2, 6, 8, 16, 8))
def test_3d_const_shape(self):
input_param = {'func': 'CONSTANT',
'kernel_size': [1, 3, 2],
'stride': [3, 2, 2]}
self._test_nd_downsample_output_shape(rank=3,
param_dict=input_param,
output_shape=(2, 6, 8, 8, 8))
def test_2d_max_shape(self):
input_param = {'func': 'CONSTANT',
'kernel_size': [1, 3],
'stride': 3}
self._test_nd_downsample_output_shape(rank=2,
param_dict=input_param,
output_shape=(2, 6, 6, 8))
def test_2d_avg_shape(self):
input_param = {'func': 'AVG',
'kernel_size': [2, 3],
'stride': 2}
self._test_nd_downsample_output_shape(rank=2,
param_dict=input_param,
output_shape=(2, 8, 8, 8))
def test_2d_const_shape(self):
input_param = {'func': 'CONSTANT',
'kernel_size': [2, 3],
'stride': [2, 3]}
self._test_nd_downsample_output_shape(rank=2,
param_dict=input_param,
output_shape=(2, 8, 6, 8))
if __name__ == "__main__":
tf.test.main()
|
NifTK/NiftyNet
|
tests/downsample_test.py
|
Python
|
apache-2.0
| 3,371 | 0.000297 |
#!/usr/bin/env python
# Kai Yu
# github.com/readline
# mafSignature2plot.py
# 150410
from __future__ import division
import os,sys,math
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
matplotlib.use('Agg')
import os,sys,matplotlib,pylab
import matplotlib.pyplot as plt
import numpy as np
def font(size):
return matplotlib.font_manager.FontProperties(size=size,\
fname='/Share/BP/yukai/src/font/ARIAL.TTF')
def fontConsola(size):
return matplotlib.font_manager.FontProperties(size=size,\
fname='/Share/BP/yukai/src/font/consola.ttf')
def getMatrix(sigPath):
infile = open(sigPath,'r')
countn = infile.readline().rstrip().split('=')[1]
mutList, tmpList = [],[]
sumdic = {'TA':0,'TC':0,'TG':0,'CA':0,'CG':0,'CT':0}
while 1:
line = infile.readline().rstrip()
if not line: break
c = line.split('\t')
mutList.append(c[0])
tmpList.append(float(c[1]))
bmut = c[0].split('>')[0][1] + c[0].split('>')[1][1]
sumdic[bmut] += float(c[1])
sumList = []
for bmut in ['TA','TC','TG','CA','CG','CT']:
sumList.append(sumdic[bmut])
infile.close()
return mutList, tmpList, sumList, countn
def getC(c):
tmpdic = []
for n in range(6):
for m in range(16):
tmpdic.append(c[n])
return tmpdic
def main():
try:
sigPath = sys.argv[1]
except:
print sys.argv[0] + ' [input signature path]'
sys.exit()
mutList, mat, sumList,countn = getMatrix(sigPath)
### Start plot
c = ['#FFFF99','#CCCCFF','#FFCC99','#CCFFCC','#CCFFFF','#FF9999']
col = getC(c)
fig = plt.figure(figsize = (20,10))
topy = int((max(mat)//5+1)*5)
ax1 = fig.add_axes([0.08,0.15,0.83,0.7])
ax2 = fig.add_axes([0.1,0.46,0.19,0.38])
ax1.set_xlim([0,96])
ax1.set_ylim([0,topy])
ax1.bar(range(96),mat,width=1,linewidth=0.5,color=col,alpha=1)
ax1.vlines([16,32,48,64,80],0,topy,linestyle='--',linewidth=1,color='black',alpha=0.7)
ax1.hlines(range(0,topy+1,5),0,96,linestyle='--',linewidth=1,color='black',alpha=0.7)
ax3 = ax1.twiny()
ax3.set_xlim([0,96])
ax3.set_ylim([0,topy])
ax3.set_xticks(range(8,96,16))
ax3.set_xticklabels(['T > A','T > C','T > G','C > A','C > G','C > T'],fontproperties=font(30))
plt.setp(ax3.get_xticklines(), visible=False)
mutList1 = []
for n in mutList:
mutList1.append(n[:3])
mutList0 = []
for n in range(96):
mutList0.append(n+0.7)
ax1.set_xticks(mutList0)
plt.setp(ax1.get_xticklines(), visible=False)
ax1.set_xticklabels(mutList1, fontproperties=fontConsola(16),rotation='vertical')
ax1.set_yticks(range(0,topy+1,5))
ax1.set_yticklabels(range(0,topy+1,5),fontproperties=font(24))
ax1.set_ylabel('Normalized rate / Mb',fontproperties=font(30))
# Pie plot
ax2.set_xticks([])
ax2.set_yticks([])
pielabel = ['T>A','T>C','T>G','C>A','C>G','C>T']
explode = [0.32,0.29,0.26,0.23,0.2,0]
pie1 = ax2.pie(sumList,labels=pielabel, explode=explode,colors=c,shadow=True,startangle=270)
for i in pie1[1]:
# print i
i.set_fontproperties(font(24))
# i.set_backgroundcolor('white')
ax1.text(32,topy*0.8,'%s\nn = %s'%(sigPath.split('/')[-1][:-10],countn),fontproperties=font(32),backgroundcolor='white')
plt.savefig(sigPath+'.sigplot.png')
plt.savefig(sigPath+'.sigplot.pdf')
if __name__ == '__main__':
main()
|
readline/btb
|
cancer/integrate/coMut/mafSignature2plot.py
|
Python
|
gpl-2.0
| 3,469 | 0.036322 |
# Copyright (C) 2012-2016 Julie Marchant <onpon4@riseup.net>
#
# This file is part of the Pygame SGE.
#
# The Pygame SGE is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# The Pygame SGE is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with the Pygame SGE. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides classes related to rendering graphics.
"""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import math
import os
import warnings
import pygame
import six
import sge
from sge import r
from sge.r import (_check_color_input, _check_color, _scale, _get_blend_flags,
_screen_blend, f_split_text, s_get_image, s_set_size,
s_refresh, s_set_transparency, s_from_text, tg_blit)
COLORS = {'white': '#ffffff', 'silver': '#c0c0c0', 'gray': '#808080',
'black': '#000000', 'red': '#ff0000', 'maroon': '#800000',
'yellow': '#ffff00', 'olive': '#808000', 'lime': '#00ff00',
'green': '#008000', 'aqua': '#00ffff', 'teal': '#008080',
'blue': '#0000ff', 'navy': '#000080', 'fuchsia': '#ff00ff',
'purple': '#800080'}
COLOR_NAMES = {}
for pair in COLORS.items():
COLOR_NAMES[pair[1]] = pair[0]
__all__ = ["Color", "Sprite", "TileGrid", "Font", "BackgroundLayer",
"Background"]
class Color(object):
"""
This class stores color information.
Objects of this class can be converted to iterables indicating the
object's :attr:`red`, :attr:`green`, :attr:`blue`, and :attr:`alpha`
values, respectively; to integers which can be interpreted as a
hexadecimal representation of the color, excluding alpha
transparency; and to strings which indicate the English name of the
color (in all lowercase) if possible, and :attr:`hex_string`
otherwise.
.. attribute:: red
The red component of the color as an integer, where ``0``
indicates no red intensity and ``255`` indicates full red
intensity.
.. attribute:: green
The green component of the color as an integer, where ``0``
indicates no green intensity and ``255`` indicates full green
intensity.
.. attribute:: blue
The blue component of the color as an integer, where ``0``
indicates no blue intensity and ``255`` indicates full blue
intensity.
.. attribute:: alpha
The alpha transparency of the color as an integer, where ``0``
indicates full transparency and ``255`` indicates full opacity.
.. attribute:: hex_string
An HTML hex string representation of the color. (Read-only)
"""
def __init__(self, value):
"""
Arguments:
- ``value`` -- The value indicating the color represented by
this object. Should be one of the following:
- One of the 16 HTML color names (case-insensitive).
- An HTML-style hex string containing 3, 4, 6, or 8 digits
which indicate the red, green, blue, and alpha components of
the color, respectively, as pairs of hexadecimal digits. If
the string contains 3 or 4 digits, each digit is duplicated;
for example, ``"#F80"`` is equivalent to ``"#FF8800"``.
- An integer which, when written as a hexadecimal number,
specifies the components of the color in the same way as an
HTML-style hex string containing 6 digits.
- A list or tuple indicating the red, green, and blue
components, and optionally the alpha component, in that
order.
"""
self.alpha = 255
if isinstance(value, six.string_types):
value = COLORS.get(value, value)[1:]
if len(value) == 3:
r, g, b = [int(value[i] * 2, 16) for i in six.moves.range(3)]
self.red, self.green, self.blue = r, g, b
elif len(value) == 4:
r, g, b, a = [int(value[i] * 2, 16) for i in range(4)]
self.red, self.green, self.blue, self.alpha = r, g, b, a
elif len(value) == 6:
r, g, b = [int(value[i:(i + 2)], 16)
for i in six.moves.range(0, 6, 2)]
self.red, self.green, self.blue = r, g, b
elif len(value) == 8:
r, g, b, a = [int(value[i:(i + 2)], 16) for i in range(0, 8, 2)]
self.red, self.green, self.blue, self.alpha = r, g, b, a
else:
raise ValueError("Invalid color string.")
elif isinstance(value, six.integer_types):
b, g, r = [(value & 256 ** (i + 1) - 1) // 256 ** i
for i in six.moves.range(3)]
self.red, self.green, self.blue = r, g, b
elif isinstance(value, (list, tuple)):
if len(value) >= 3:
self.red, self.green, self.blue = value[:3]
if len(value) >= 4:
self.alpha = value[3]
else:
raise ValueError("Invalid color tuple.")
else:
raise ValueError("Invalid color value.")
@property
def red(self):
return self._r
@red.setter
def red(self, value):
self._r = _check_color_input(value)
@property
def green(self):
return self._g
@green.setter
def green(self, value):
self._g = _check_color_input(value)
@property
def blue(self):
return self._b
@blue.setter
def blue(self, value):
self._b = _check_color_input(value)
@property
def alpha(self):
return self._a
@alpha.setter
def alpha(self, value):
self._a = _check_color_input(value)
@property
def hex_string(self):
if self.alpha == 255:
r, g, b = [hex(c)[2:].zfill(2) for c in self[:3]]
return "#{}{}{}".format(r, g, b)
else:
r, g, b, a = [hex(c)[2:].zfill(2) for c in self]
return "#{}{}{}{}".format(r, g, b, a)
def __iter__(self):
return iter([self.red, self.green, self.blue, self.alpha])
def __int__(self):
return self.red * 256 ** 2 | self.green * 256 | self.blue
def __repr__(self):
return 'sge.gfx.Color("{}")'.format(str(self))
def __str__(self):
return COLOR_NAMES.get(self.hex_string, self.hex_string)
def __eq__(self, other):
return str(self) == str(other)
def __getitem__(self, index):
return tuple(self)[index]
def __setitem__(self, index, value):
c = list(self)
c[index] = value
self.red, self.green, self.blue, self.alpha = c
class Sprite(object):
"""
This class stores images and information about how the SGE is to use
those images.
What image formats are supported depends on the implementation of
the SGE, but image formats that are generally a good choice are PNG
and JPEG. See the implementation-specific information for a full
list of supported formats.
.. attribute:: width
The width of the sprite.
.. note::
Changing this attribute will cause the sprite to be scaled
horizontally. This is a destructive transformation: it can
result in loss of pixel information, especially if it is done
repeatedly. Because of this, it is advised that you do not
adjust this value for routine scaling. Use the
:attr:`image_xscale` attribute of a :class:`sge.dsp.Object`
object instead.
.. attribute:: height
The height of the sprite.
.. note::
Changing this attribute will cause the sprite to be scaled
vertically. This is a destructive transformation: it can
result in loss of pixel information, especially if it is done
repeatedly. Because of this, it is advised that you do not
adjust this value for routine scaling. Use the
:attr:`image_yscale` attribute of a :class:`sge.dsp.Object`
object instead.
.. attribute:: transparent
Whether or not the image should be partially transparent, based
on the image's alpha channel. If this is :const:`False`, all
pixels in the image will be treated as fully opaque regardless
of what the image file says their opacity should be.
This can also be set to a :class:`sge.gfx.Color` object, which
will cause the indicated color to be used as a colorkey.
.. attribute:: origin_x
The suggested horizontal location of the origin relative to the
left edge of the images.
.. attribute:: origin_y
The suggested vertical location of the origin relative to the top
edge of the images.
.. attribute:: fps
The suggested rate in frames per second to animate the image at.
Can be negative, in which case animation will be reversed.
.. attribute:: speed
The suggested rate to animate the image at as a factor of
:attr:`sge.game.fps`. Can be negative, in which case animation
will be reversed.
.. attribute:: bbox_x
The horizontal location relative to the sprite of the suggested
bounding box to use with it. If set to :const:`None`, it will
become equal to ``-origin_x`` (which is always the left edge of
the image).
.. attribute:: bbox_y
The vertical location relative to the sprite of the suggested
bounding box to use with it. If set to :const:`None`, it will
become equal to ``-origin_y`` (which is always the top edge of
the image).
.. attribute:: bbox_width
The width of the suggested bounding box. If set to
:const:`None`, it will become equal to ``width - bbox_x``
(which is always everything on the image to the right of
:attr:`bbox_x`).
.. attribute:: bbox_height
The height of the suggested bounding box. If set to
:const:`None`, it will become equal to ``height - bbox_y``
(which is always everything on the image below :attr:`bbox_y`).
.. attribute:: name
The name of the sprite given when it was created. (Read-only)
.. attribute:: frames
The number of animation frames in the sprite. (Read-only)
.. attribute:: rd
Reserved dictionary for internal use by the SGE. (Read-only)
"""
@property
def width(self):
return self.__w
@width.setter
def width(self, value):
if self.__w != value:
self.__w = int(round(value))
s_set_size(self)
s_refresh(self)
@property
def height(self):
return self.__h
@height.setter
def height(self, value):
if self.__h != value:
self.__h = int(round(value))
s_set_size(self)
s_refresh(self)
@property
def transparent(self):
return self.__transparent
@transparent.setter
def transparent(self, value):
if self.__transparent != value:
self.__transparent = value
s_refresh(self)
@property
def speed(self):
return self.fps / sge.game.fps
@speed.setter
def speed(self, value):
self.fps = value * sge.game.fps
@property
def bbox_x(self):
return self.__bbox_x
@bbox_x.setter
def bbox_x(self, value):
if value is not None:
self.__bbox_x = value
else:
self.__bbox_x = -self.origin_x
@property
def bbox_y(self):
return self.__bbox_y
@bbox_y.setter
def bbox_y(self, value):
if value is not None:
self.__bbox_y = value
else:
self.__bbox_y = -self.origin_y
@property
def bbox_width(self):
return self.__bbox_width
@bbox_width.setter
def bbox_width(self, value):
if value is not None:
self.__bbox_width = value
else:
self.__bbox_width = self.width - self.origin_x - self.bbox_x
@property
def bbox_height(self):
return self.__bbox_height
@bbox_height.setter
def bbox_height(self, value):
if value is not None:
self.__bbox_height = value
else:
self.__bbox_height = self.height - self.origin_y - self.bbox_y
@property
def frames(self):
return len(self.rd["baseimages"])
def __init__(self, name=None, directory="", width=None, height=None,
transparent=True, origin_x=0, origin_y=0, fps=60, bbox_x=None,
bbox_y=None, bbox_width=None, bbox_height=None):
"""
Arguments:
- ``name`` -- The base name of the image files, used to find all
individual image files that make up the sprite's animation`.
One of the following rules will be used to find the images:
- The base name plus a valid image extension. If this rule is
used, the image will be loaded as a single-frame sprite.
- The base name and an integer separated by either a hyphen
(``-``) or an underscore (``_``) and followed by a valid
image extension. If this rule is used, all images with
names like this are loaded and treated as an animation, with
the lower-numbered images being earlier frames.
- The base name and an integer separated by either ``-strip``
or ``_strip`` and followed by a valid image extension. If
this rule is used, the image will be treated as an animation
read as a horizontal reel from left to right, split into the
number of frames indicated by the integer.
- If the base name is :const:`None`, the sprite will be a
fully transparent rectangle at the specified size (with both
``width`` and ``height`` defaulting to 32 if they are set to
:const:`None`). The SGE decides what to assign to the
sprite's :attr:`name` attribute in this case, but it will
always be a string.
If none of the above rules can be used, :exc:`OSError` is
raised.
- ``directory`` -- The directory to search for image files in.
All other arguments set the respective initial attributes of the
sprite. See the documentation for :class:`Sprite` for more
information.
"""
self.rd = {}
self.name = name
self.rd["baseimages"] = []
self.rd["drawcycle"] = 0
fname_single = []
fname_frames = []
fname_strip = []
errlist = []
if name is not None:
def check_alpha(surface):
# Check whether the surface has a colorkey. If it does,
# return the surface converted to use alpha
# transparency. Otherwise, return the surface.
if surface.get_colorkey() is not None:
return surface.convert_alpha()
return surface
if not directory:
directory = os.curdir
for fname in os.listdir(directory):
full_fname = os.path.join(directory, fname)
if (fname.startswith(name) and
os.path.isfile(full_fname)):
root, ext = os.path.splitext(fname)
if root == name:
split = [name, '']
elif root.rsplit('-', 1)[0] == name:
split = root.rsplit('-', 1)
elif root.rsplit('_', 1)[0] == name:
split = root.rsplit('_', 1)
else:
continue
if root == name:
fname_single.append(full_fname)
elif split[1].isdigit():
n = int(split[1])
while len(fname_frames) - 1 < n:
fname_frames.append(None)
fname_frames[n] = full_fname
elif (split[1].startswith('strip') and
split[1][5:].isdigit()):
fname_strip.append(full_fname)
if any(fname_single):
# Load the single image
for fname in fname_single:
try:
img = pygame.image.load(fname)
except pygame.error as e:
errlist.append(e)
else:
self.rd["baseimages"].append(check_alpha(img))
if not self.rd["baseimages"] and any(fname_frames):
# Load the multiple images
for fname in fname_frames:
if fname:
try:
img = pygame.image.load(fname)
except pygame.error as e:
errlist.append(e)
else:
self.rd["baseimages"].append(check_alpha(img))
if not self.rd["baseimages"] and any(fname_strip):
# Load the strip (sprite sheet)
for fname in fname_strip:
root, ext = os.path.splitext(os.path.basename(fname))
assert '-' in root or '_' in root
assert (root.rsplit('-', 1)[0] == name or
root.rsplit('_', 1)[0] == name)
if root.rsplit('-', 1)[0] == name:
split = root.rsplit('-', 1)
else:
split = root.rsplit('_', 1)
try:
sheet = pygame.image.load(fname)
except pygame.error as e:
errlist.append(e)
else:
sheet = check_alpha(sheet)
flags = sheet.get_flags()
assert split[1][5:].isdigit()
n = int(split[1][5:])
img_w = max(1, sheet.get_width()) // n
img_h = max(1, sheet.get_height())
for x in six.moves.range(0, img_w * n, img_w):
img = pygame.Surface((img_w, img_h), flags)
img.blit(sheet, (int(-x), 0))
self.rd["baseimages"].append(img)
if not self.rd["baseimages"]:
print("Pygame errors during search:")
if errlist:
for e in errlist:
print(e)
else:
print("None")
msg = 'Supported file(s) for sprite name "{}" not found in {}'.format(name, directory)
raise OSError(msg)
else:
# Name is None; default to a blank rectangle.
if width is None:
width = 32
if height is None:
height = 32
width = int(round(width))
height = int(round(height))
self.__w = width
self.__h = height
# Choose name
self.name = "sge-pygame-dynamicsprite"
img = pygame.Surface((width, height), pygame.SRCALPHA)
img.fill(pygame.Color(0, 0, 0, 0))
self.rd["baseimages"].append(img)
if width is None:
width = 1
for image in self.rd["baseimages"]:
width = max(width, image.get_width())
if height is None:
height = 1
for image in self.rd["baseimages"]:
height = max(height, image.get_height())
self.__w = int(round(width))
self.__h = int(round(height))
s_set_size(self)
self.origin_x = origin_x
self.origin_y = origin_y
self.__transparent = transparent
self.fps = fps
self.bbox_x = bbox_x
self.bbox_y = bbox_y
self.bbox_width = bbox_width
self.bbox_height = bbox_height
self.rd["locked"] = False
s_refresh(self)
def append_frame(self):
"""Append a new blank frame to the end of the sprite."""
img = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
img.fill(pygame.Color(0, 0, 0, 0))
self.rd["baseimages"].append(img)
s_refresh(self)
def insert_frame(self, frame):
"""
Insert a new blank frame into the sprite.
Arguments:
- ``frame`` -- The frame of the sprite to insert the new frame
in front of, where ``0`` is the first frame.
"""
img = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
img.fill(pygame.Color(0, 0, 0, 0))
self.rd["baseimages"].insert(frame, img)
s_refresh(self)
def extend(self, sprite):
"""
Extend this sprite with the frames of another sprite.
If the size of the frames added is different from the size of
this sprite, they are scaled to this sprite's size.
Arguments:
- ``sprite`` -- The sprite to add the frames of to this sprite.
"""
self.rd["baseimages"].extend(sprite.rd["baseimages"])
s_set_size(self)
s_refresh(self)
def delete_frame(self, frame):
"""
Delete a frame from the sprite.
Arguments:
- ``frame`` -- The frame of the sprite to delete, where ``0`` is
the first frame.
"""
del self.rd["baseimages"][frame]
def get_pixel(self, x, y, frame=0):
"""
Return a :class:`sge.gfx.Color` object indicating the color of a
particular pixel on the sprite.
Arguments:
- ``x`` -- The horizontal location relative to the sprite of the
pixel to check.
- ``y`` -- The vertical location relative to the sprite of the
pixel to check.
- ``frame`` -- The frame of the sprite to check, where ``0`` is
the first frame.
"""
x = int(round(x))
y = int(round(y))
frame %= self.frames
pg_color = self.rd["baseimages"][frame].get_at((x, y))
return Color(tuple(pg_color))
def get_pixels(self, frame=0):
"""
Return a two-dimensional list of :class`sge.gfx.Color` objects
indicating the colors of a particular frame's pixels.
A returned list given the name ``pixels`` is indexed as
``pixels[x][y]``, where ``x`` is the horizontal location of the
pixel and ``y`` is the vertical location of the pixel.
Arguments:
- ``frame`` -- The frame of the sprite to check, where ``0`` is
the first frame.
"""
frame %= self.frames
surf = self.rd["baseimages"][frame]
surf.lock()
w, h = surf.get_size()
pixels = [[Color(tuple(surf.get_at(x, y))) for y in six.moves.range(h)]
for x in six.moves.range(w)]
surf.unlock()
return pixels
def draw_dot(self, x, y, color, frame=None, blend_mode=None):
"""
Draw a single-pixel dot on the sprite.
Arguments:
- ``x`` -- The horizontal location relative to the sprite to
draw the dot.
- ``y`` -- The vertical location relative to the sprite to draw
the dot.
- ``color`` -- A :class:`sge.gfx.Color` object representing the
color of the dot.
- ``frame`` -- The frame of the sprite to draw on, where ``0``
is the first frame; set to :const:`None` to draw on all
frames.
- ``blend_mode`` -- The blend mode to use. Possible blend modes
are:
- :data:`sge.BLEND_NORMAL`
- :data:`sge.BLEND_RGBA_ADD`
- :data:`sge.BLEND_RGBA_SUBTRACT`
- :data:`sge.BLEND_RGBA_MULTIPLY`
- :data:`sge.BLEND_RGBA_SCREEN`
- :data:`sge.BLEND_RGBA_MINIMUM`
- :data:`sge.BLEND_RGBA_MAXIMUM`
- :data:`sge.BLEND_RGB_ADD`
- :data:`sge.BLEND_RGB_SUBTRACT`
- :data:`sge.BLEND_RGB_MULTIPLY`
- :data:`sge.BLEND_RGB_SCREEN`
- :data:`sge.BLEND_RGB_MINIMUM`
- :data:`sge.BLEND_RGB_MAXIMUM`
:const:`None` is treated as :data:`sge.BLEND_NORMAL`.
"""
_check_color(color)
x = int(round(x))
y = int(round(y))
pg_color = pygame.Color(*color)
if frame is None:
rng = six.moves.range(self.frames)
else:
rng = [frame % self.frames]
pygame_flags = _get_blend_flags(blend_mode)
if color.alpha == 255 and not pygame_flags:
for i in rng:
self.rd["baseimages"][i].set_at((x, y), pg_color)
else:
stamp = pygame.Surface((1, 1), pygame.SRCALPHA)
stamp.fill(pg_color)
for i in rng:
dsurf = self.rd["baseimages"][i]
if blend_mode == sge.BLEND_RGB_SCREEN:
_screen_blend(dsurf, stamp, x, y, False)
elif blend_mode == sge.BLEND_RGBA_SCREEN:
_screen_blend(dsurf, stamp, x, y, True)
else:
dsurf.blit(stamp, (x, y), None, pygame_flags)
s_refresh(self)
def draw_line(self, x1, y1, x2, y2, color, thickness=1, anti_alias=False,
frame=None, blend_mode=None):
"""
Draw a line segment on the sprite.
Arguments:
- ``x1`` -- The horizontal location relative to the sprite of
the first end point of the line segment.
- ``y1`` -- The vertical location relative to the sprite of the
first end point of the line segment.
- ``x2`` -- The horizontal location relative to the sprite of
the second end point of the line segment.
- ``y2`` -- The vertical location relative to the sprite of the
second end point of the line segment.
- ``color`` -- A :class:`sge.gfx.Color` object representing the
color of the line segment.
- ``thickness`` -- The thickness of the line segment.
- ``anti_alias`` -- Whether or not anti-aliasing should be used.
- ``frame`` -- The frame of the sprite to draw on, where ``0``
is the first frame; set to :const:`None` to draw on all
frames.
- ``blend_mode`` -- The blend mode to use. Possible blend modes
are:
- :data:`sge.BLEND_NORMAL`
- :data:`sge.BLEND_RGBA_ADD`
- :data:`sge.BLEND_RGBA_SUBTRACT`
- :data:`sge.BLEND_RGBA_MULTIPLY`
- :data:`sge.BLEND_RGBA_SCREEN`
- :data:`sge.BLEND_RGBA_MINIMUM`
- :data:`sge.BLEND_RGBA_MAXIMUM`
- :data:`sge.BLEND_RGB_ADD`
- :data:`sge.BLEND_RGB_SUBTRACT`
- :data:`sge.BLEND_RGB_MULTIPLY`
- :data:`sge.BLEND_RGB_SCREEN`
- :data:`sge.BLEND_RGB_MINIMUM`
- :data:`sge.BLEND_RGB_MAXIMUM`
:const:`None` is treated as :data:`sge.BLEND_NORMAL`.
"""
_check_color(color)
x1 = int(round(x1))
y1 = int(round(y1))
x2 = int(round(x2))
y2 = int(round(y2))
thickness = int(round(thickness))
pg_color = pygame.Color(*color)
thickness = abs(thickness)
if frame is None:
rng = six.moves.range(self.frames)
else:
rng = [frame % self.frames]
pygame_flags = _get_blend_flags(blend_mode)
stamp = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
stamp.fill(pygame.Color(0, 0, 0, 0))
if anti_alias and thickness == 1:
pygame.draw.aaline(stamp, pg_color, (x1, y1), (x2, y2))
else:
pygame.draw.line(stamp, pg_color, (x1, y1), (x2, y2),
thickness)
for i in rng:
dsurf = self.rd["baseimages"][i]
if blend_mode == sge.BLEND_RGB_SCREEN:
_screen_blend(dsurf, stamp, 0, 0, False)
elif blend_mode == sge.BLEND_RGBA_SCREEN:
_screen_blend(dsurf, stamp, 0, 0, True)
else:
dsurf.blit(stamp, (0, 0), None, pygame_flags)
s_refresh(self)
def draw_rectangle(self, x, y, width, height, fill=None, outline=None,
outline_thickness=1, frame=None, blend_mode=None):
"""
Draw a rectangle on the sprite.
Arguments:
- ``x`` -- The horizontal location relative to the sprite to
draw the rectangle.
- ``y`` -- The vertical location relative to the sprite to draw
the rectangle.
- ``width`` -- The width of the rectangle.
- ``height`` -- The height of the rectangle.
- ``fill`` -- A :class:`sge.gfx.Color` object representing the
color of the fill of the rectangle.
- ``outline`` -- A :class:`sge.gfx.Color` object representing
the color of the outline of the rectangle.
- ``outline_thickness`` -- The thickness of the outline of the
rectangle.
- ``frame`` -- The frame of the sprite to draw on, where ``0``
is the first frame; set to :const:`None` to draw on all
frames.
- ``blend_mode`` -- The blend mode to use. Possible blend modes
are:
- :data:`sge.BLEND_NORMAL`
- :data:`sge.BLEND_RGBA_ADD`
- :data:`sge.BLEND_RGBA_SUBTRACT`
- :data:`sge.BLEND_RGBA_MULTIPLY`
- :data:`sge.BLEND_RGBA_SCREEN`
- :data:`sge.BLEND_RGBA_MINIMUM`
- :data:`sge.BLEND_RGBA_MAXIMUM`
- :data:`sge.BLEND_RGB_ADD`
- :data:`sge.BLEND_RGB_SUBTRACT`
- :data:`sge.BLEND_RGB_MULTIPLY`
- :data:`sge.BLEND_RGB_SCREEN`
- :data:`sge.BLEND_RGB_MINIMUM`
- :data:`sge.BLEND_RGB_MAXIMUM`
:const:`None` is treated as :data:`sge.BLEND_NORMAL`.
"""
_check_color(fill)
_check_color(outline)
x = int(round(x))
y = int(round(y))
width = int(round(width))
height = int(round(height))
outline_thickness = abs(outline_thickness)
if outline_thickness == 0:
outline = None
if fill is None and outline is None:
# There's no point in trying in this case.
return
rect = pygame.Rect(x, y, width, height)
if fill is not None:
pg_fill = pygame.Color(*fill)
if outline is not None:
pg_outl = pygame.Color(*outline)
if frame is None:
rng = six.moves.range(self.frames)
else:
rng = [frame % self.frames]
pygame_flags = _get_blend_flags(blend_mode)
stamp = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
stamp.fill(pygame.Color(0, 0, 0, 0))
if fill is not None:
stamp.fill(pg_fill, rect)
if outline is not None:
pygame.draw.rect(stamp, pg_outl, rect, outline_thickness)
for i in rng:
dsurf = self.rd["baseimages"][i]
if blend_mode == sge.BLEND_RGB_SCREEN:
_screen_blend(dsurf, stamp, 0, 0, False)
elif blend_mode == sge.BLEND_RGBA_SCREEN:
_screen_blend(dsurf, stamp, 0, 0, True)
else:
dsurf.blit(stamp, (0, 0), None, pygame_flags)
s_refresh(self)
def draw_ellipse(self, x, y, width, height, fill=None, outline=None,
outline_thickness=1, anti_alias=False, frame=None,
blend_mode=None):
"""
Draw an ellipse on the sprite.
Arguments:
- ``x`` -- The horizontal location relative to the sprite to
position the imaginary rectangle containing the ellipse.
- ``y`` -- The vertical location relative to the sprite to
position the imaginary rectangle containing the ellipse.
- ``width`` -- The width of the ellipse.
- ``height`` -- The height of the ellipse.
- ``fill`` -- A :class:`sge.gfx.Color` object representing the
color of the fill of the ellipse.
- ``outline`` -- A :class:`sge.gfx.Color` object representing
the color of the outline of the ellipse.
- ``outline_thickness`` -- The thickness of the outline of the
ellipse.
- ``anti_alias`` -- Whether or not anti-aliasing should be used.
- ``frame`` -- The frame of the sprite to draw on, where ``0``
is the first frame; set to :const:`None` to draw on all
frames.
- ``blend_mode`` -- The blend mode to use. Possible blend modes
are:
- :data:`sge.BLEND_NORMAL`
- :data:`sge.BLEND_RGBA_ADD`
- :data:`sge.BLEND_RGBA_SUBTRACT`
- :data:`sge.BLEND_RGBA_MULTIPLY`
- :data:`sge.BLEND_RGBA_SCREEN`
- :data:`sge.BLEND_RGBA_MINIMUM`
- :data:`sge.BLEND_RGBA_MAXIMUM`
- :data:`sge.BLEND_RGB_ADD`
- :data:`sge.BLEND_RGB_SUBTRACT`
- :data:`sge.BLEND_RGB_MULTIPLY`
- :data:`sge.BLEND_RGB_SCREEN`
- :data:`sge.BLEND_RGB_MINIMUM`
- :data:`sge.BLEND_RGB_MAXIMUM`
:const:`None` is treated as :data:`sge.BLEND_NORMAL`.
"""
_check_color(fill)
_check_color(outline)
x = int(round(x))
y = int(round(y))
width = int(round(width))
height = int(round(height))
outline_thickness = abs(outline_thickness)
if outline_thickness == 0:
outline = None
if fill is None and outline is None:
# There's no point in trying in this case.
return
rect = pygame.Rect(x, y, width, height)
if fill is not None:
pg_fill = pygame.Color(*fill)
if outline is not None:
pg_outl = pygame.Color(*outline)
if frame is None:
rng = six.moves.range(self.frames)
else:
rng = [frame % self.frames]
pygame_flags = _get_blend_flags(blend_mode)
stamp = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
stamp.fill(pygame.Color(0, 0, 0, 0))
if fill is not None:
pygame.draw.ellipse(stamp, pg_fill, rect)
if outline is not None:
pygame.draw.ellipse(stamp, pg_outl, rect, outline_thickness)
for i in rng:
dsurf = self.rd["baseimages"][i]
if blend_mode == sge.BLEND_RGB_SCREEN:
_screen_blend(dsurf, stamp, 0, 0, False)
elif blend_mode == sge.BLEND_RGBA_SCREEN:
_screen_blend(dsurf, stamp, 0, 0, True)
else:
dsurf.blit(stamp, (0, 0), None, pygame_flags)
s_refresh(self)
def draw_circle(self, x, y, radius, fill=None, outline=None,
outline_thickness=1, anti_alias=False, frame=None,
blend_mode=None):
"""
Draw a circle on the sprite.
Arguments:
- ``x`` -- The horizontal location relative to the sprite to
position the center of the circle.
- ``y`` -- The vertical location relative to the sprite to
position the center of the circle.
- ``radius`` -- The radius of the circle.
- ``fill`` -- A :class:`sge.gfx.Color` object representing the
color of the fill of the circle.
- ``outline`` -- A :class:`sge.gfx.Color` object representing
the color of the outline of the circle.
- ``outline_thickness`` -- The thickness of the outline of the
circle.
- ``anti_alias`` -- Whether or not anti-aliasing should be used.
- ``frame`` -- The frame of the sprite to draw on, where ``0``
is the first frame; set to :const:`None` to draw on all
frames.
- ``blend_mode`` -- The blend mode to use. Possible blend modes
are:
- :data:`sge.BLEND_NORMAL`
- :data:`sge.BLEND_RGBA_ADD`
- :data:`sge.BLEND_RGBA_SUBTRACT`
- :data:`sge.BLEND_RGBA_MULTIPLY`
- :data:`sge.BLEND_RGBA_SCREEN`
- :data:`sge.BLEND_RGBA_MINIMUM`
- :data:`sge.BLEND_RGBA_MAXIMUM`
- :data:`sge.BLEND_RGB_ADD`
- :data:`sge.BLEND_RGB_SUBTRACT`
- :data:`sge.BLEND_RGB_MULTIPLY`
- :data:`sge.BLEND_RGB_SCREEN`
- :data:`sge.BLEND_RGB_MINIMUM`
- :data:`sge.BLEND_RGB_MAXIMUM`
:const:`None` is treated as :data:`sge.BLEND_NORMAL`.
"""
_check_color(fill)
_check_color(outline)
x = int(round(x))
y = int(round(y))
radius = int(round(radius))
outline_thickness = abs(outline_thickness)
if outline_thickness == 0:
outline = None
if fill is None and outline is None:
# There's no point in trying in this case.
return
if fill is not None:
pg_fill = pygame.Color(*fill)
if outline is not None:
pg_outl = pygame.Color(*outline)
if frame is None:
rng = six.moves.range(self.frames)
else:
rng = [frame % self.frames]
pygame_flags = _get_blend_flags(blend_mode)
stamp = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
stamp.fill(pygame.Color(0, 0, 0, 0))
if fill is not None:
pygame.draw.circle(stamp, pg_fill, (x, y), radius)
if outline is not None:
pygame.draw.circle(stamp, pg_outl, (x, y), radius,
outline_thickness)
for i in rng:
dsurf = self.rd["baseimages"][i]
if blend_mode == sge.BLEND_RGB_SCREEN:
_screen_blend(dsurf, stamp, 0, 0, False)
elif blend_mode == sge.BLEND_RGBA_SCREEN:
_screen_blend(dsurf, stamp, 0, 0, True)
else:
dsurf.blit(stamp, (0, 0), None, pygame_flags)
s_refresh(self)
def draw_polygon(self, points, fill=None, outline=None,
outline_thickness=1, anti_alias=False, frame=None,
blend_mode=None):
"""
Draw a polygon on the sprite.
Arguments:
- ``points`` -- A list of points relative to the sprite to
position each of the polygon's angles. Each point should be a
tuple in the form ``(x, y)``, where x is the horizontal
location and y is the vertical location.
- ``fill`` -- A :class:`sge.gfx.Color` object representing the
color of the fill of the polygon.
- ``outline`` -- A :class:`sge.gfx.Color` object representing
the color of the outline of the polygon.
- ``outline_thickness`` -- The thickness of the outline of the
polygon.
- ``anti_alias`` -- Whether or not anti-aliasing should be used.
- ``frame`` -- The frame of the sprite to draw on, where ``0``
is the first frame; set to :const:`None` to draw on all
frames.
- ``blend_mode`` -- The blend mode to use. Possible blend modes
are:
- :data:`sge.BLEND_NORMAL`
- :data:`sge.BLEND_RGBA_ADD`
- :data:`sge.BLEND_RGBA_SUBTRACT`
- :data:`sge.BLEND_RGBA_MULTIPLY`
- :data:`sge.BLEND_RGBA_SCREEN`
- :data:`sge.BLEND_RGBA_MINIMUM`
- :data:`sge.BLEND_RGBA_MAXIMUM`
- :data:`sge.BLEND_RGB_ADD`
- :data:`sge.BLEND_RGB_SUBTRACT`
- :data:`sge.BLEND_RGB_MULTIPLY`
- :data:`sge.BLEND_RGB_SCREEN`
- :data:`sge.BLEND_RGB_MINIMUM`
- :data:`sge.BLEND_RGB_MAXIMUM`
:const:`None` is treated as :data:`sge.BLEND_NORMAL`.
"""
_check_color(fill)
_check_color(outline)
points = [(int(round(x)), int(round(y))) for (x, y) in points]
outline_thickness = abs(outline_thickness)
if outline_thickness == 0:
outline = None
if fill is None and outline is None:
# There's no point in trying in this case.
return
if fill is not None:
pg_fill = pygame.Color(*fill)
if outline is not None:
pg_outl = pygame.Color(*outline)
if frame is None:
rng = six.moves.range(self.frames)
else:
rng = [frame % self.frames]
pygame_flags = _get_blend_flags(blend_mode)
stamp = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
stamp.fill(pygame.Color(0, 0, 0, 0))
if fill is not None:
pygame.draw.polygon(stamp, pg_fill, points, 0)
if outline is not None:
if anti_alias and outline_thickness == 1:
pygame.draw.aalines(stamp, pg_outl, True, points)
else:
pygame.draw.polygon(stamp, pg_outl, points,
outline_thickness)
for i in rng:
dsurf = self.rd["baseimages"][i]
if blend_mode == sge.BLEND_RGB_SCREEN:
_screen_blend(dsurf, stamp, 0, 0, False)
elif blend_mode == sge.BLEND_RGBA_SCREEN:
_screen_blend(dsurf, stamp, 0, 0, True)
else:
dsurf.blit(stamp, (0, 0), None, pygame_flags)
s_refresh(self)
def draw_sprite(self, sprite, image, x, y, frame=None, blend_mode=None):
"""
Draw another sprite on the sprite.
Arguments:
- ``sprite`` -- The :class:`sge.gfx.Sprite` or
:class:`sge.gfx.TileGrid` object to draw with.
- ``image`` -- The frame of ``sprite`` to draw with, where ``0``
is the first frame.
- ``x`` -- The horizontal location relative to ``self`` to
position the origin of ``sprite``.
- ``y`` -- The vertical location relative to ``self`` to
position the origin of ``sprite``.
- ``frame`` -- The frame of the sprite to draw on, where ``0``
is the first frame; set to :const:`None` to draw on all
frames.
- ``blend_mode`` -- The blend mode to use. Possible blend modes
are:
- :data:`sge.BLEND_NORMAL`
- :data:`sge.BLEND_RGBA_ADD`
- :data:`sge.BLEND_RGBA_SUBTRACT`
- :data:`sge.BLEND_RGBA_MULTIPLY`
- :data:`sge.BLEND_RGBA_SCREEN`
- :data:`sge.BLEND_RGBA_MINIMUM`
- :data:`sge.BLEND_RGBA_MAXIMUM`
- :data:`sge.BLEND_RGB_ADD`
- :data:`sge.BLEND_RGB_SUBTRACT`
- :data:`sge.BLEND_RGB_MULTIPLY`
- :data:`sge.BLEND_RGB_SCREEN`
- :data:`sge.BLEND_RGB_MINIMUM`
- :data:`sge.BLEND_RGB_MAXIMUM`
:const:`None` is treated as :data:`sge.BLEND_NORMAL`.
"""
x = int(round(x - sprite.origin_x))
y = int(round(y - sprite.origin_y))
image %= sprite.frames
pygame_flags = _get_blend_flags(blend_mode)
if frame is None:
rng = six.moves.range(self.frames)
else:
rng = [frame % self.frames]
for i in rng:
dsurf = self.rd["baseimages"][i]
if isinstance(sprite, sge.gfx.Sprite):
ssurf = s_set_transparency(sprite,
sprite.rd["baseimages"][image])
if blend_mode == sge.BLEND_RGB_SCREEN:
_screen_blend(dsurf, ssurf, x, y, False)
elif blend_mode == sge.BLEND_RGBA_SCREEN:
_screen_blend(dsurf, ssurf, x, y, True)
else:
dsurf.blit(ssurf, (x, y), None, pygame_flags)
elif isinstance(sprite, sge.gfx.TileGrid):
tg_blit(sprite, dsurf, x, y)
s_refresh(self)
def draw_text(self, font, text, x, y, width=None, height=None,
color=Color("white"), halign="left", valign="top",
anti_alias=True, frame=None, blend_mode=None):
"""
Draw text on the sprite.
Arguments:
- ``font`` -- The font to use to draw the text.
- ``text`` -- The text (as a string) to draw.
- ``x`` -- The horizontal location relative to the sprite to
draw the text.
- ``y`` -- The vertical location relative to the sprite to draw
the text.
- ``width`` -- The width of the imaginary rectangle the text is
drawn in; set to :const:`None` to make the rectangle as wide
as needed to contain the text without additional line breaks.
If set to something other than :const:`None`, a line which
does not fit will be automatically split into multiple lines
that do fit.
- ``height`` -- The height of the imaginary rectangle the text
is drawn in; set to :const:`None` to make the rectangle as
tall as needed to contain the text.
- ``color`` -- A :class:`sge.gfx.Color` object representing the
color of the text.
- ``halign`` -- The horizontal alignment of the text and the
horizontal location of the origin of the imaginary rectangle
the text is drawn in. Can be set to one of the following:
- ``"left"`` -- Align the text to the left of the imaginary
rectangle the text is drawn in. Set the origin of the
imaginary rectangle to its left edge.
- ``"center"`` -- Align the text to the center of the
imaginary rectangle the text is drawn in. Set the origin of
the imaginary rectangle to its center.
- ``"right"`` -- Align the text to the right of the imaginary
rectangle the text is drawn in. Set the origin of the
imaginary rectangle to its right edge.
- ``valign`` -- The vertical alignment of the text and the
vertical location of the origin of the imaginary rectangle the
text is drawn in. Can be set to one of the following:
- ``"top"`` -- Align the text to the top of the imaginary
rectangle the text is drawn in. Set the origin of the
imaginary rectangle to its top edge. If the imaginary
rectangle is not tall enough to contain all of the text, cut
text off from the bottom.
- ``"middle"`` -- Align the the text to the middle of the
imaginary rectangle the text is drawn in. Set the origin of
the imaginary rectangle to its middle. If the imaginary
rectangle is not tall enough to contain all of the text, cut
text off equally from the top and bottom.
- ``"bottom"`` -- Align the text to the bottom of the
imaginary rectangle the text is drawn in. Set the origin of
the imaginary rectangle to its top edge. If the imaginary
rectangle is not tall enough to contain all of the text, cut
text off from the top.
- ``anti_alias`` -- Whether or not anti-aliasing should be used.
- ``frame`` -- The frame of the sprite to draw on, where ``0``
is the first frame; set to :const:`None` to draw on all
frames.
- ``blend_mode`` -- The blend mode to use. Possible blend modes
are:
- :data:`sge.BLEND_NORMAL`
- :data:`sge.BLEND_RGBA_ADD`
- :data:`sge.BLEND_RGBA_SUBTRACT`
- :data:`sge.BLEND_RGBA_MULTIPLY`
- :data:`sge.BLEND_RGBA_SCREEN`
- :data:`sge.BLEND_RGBA_MINIMUM`
- :data:`sge.BLEND_RGBA_MAXIMUM`
- :data:`sge.BLEND_RGB_ADD`
- :data:`sge.BLEND_RGB_SUBTRACT`
- :data:`sge.BLEND_RGB_MULTIPLY`
- :data:`sge.BLEND_RGB_SCREEN`
- :data:`sge.BLEND_RGB_MINIMUM`
- :data:`sge.BLEND_RGB_MAXIMUM`
:const:`None` is treated as :data:`sge.BLEND_NORMAL`.
"""
_check_color(color)
x = int(round(x))
y = int(round(y))
lines = f_split_text(font, text, width)
width = int(font.get_width(text, width, height))
height = int(font.get_height(text, width, height))
fake_height = int(font.get_height(text, width))
text_surf = pygame.Surface((width, fake_height), pygame.SRCALPHA)
box_surf = pygame.Surface((width, height), pygame.SRCALPHA)
text_rect = text_surf.get_rect()
box_rect = box_surf.get_rect()
pygame_flags = _get_blend_flags(blend_mode)
for i in six.moves.range(len(lines)):
rendered_text = font.rd["font"].render(lines[i], anti_alias,
pygame.Color(*color))
if color.alpha < 255:
rendered_text = rendered_text.convert_alpha()
rendered_text.fill((0, 0, 0, 255 - color.alpha), None,
pygame.BLEND_RGBA_SUB)
rect = rendered_text.get_rect()
rect.top = i * font.rd["font"].get_linesize()
if halign.lower() == "left":
rect.left = text_rect.left
elif halign.lower() == "right":
rect.right = text_rect.right
elif halign.lower() == "center":
rect.centerx = text_rect.centerx
text_surf.blit(rendered_text, rect)
if valign.lower() == "top":
text_rect.top = box_rect.top
elif valign.lower() == "bottom":
text_rect.bottom = box_rect.bottom
elif valign.lower() == "middle":
text_rect.centery = box_rect.centery
box_surf.blit(text_surf, text_rect)
if halign.lower() == "left":
box_rect.left = x
elif halign.lower() == "right":
box_rect.right = x
elif halign.lower() == "center":
box_rect.centerx = x
else:
box_rect.left = x
if valign.lower() == "top":
box_rect.top = y
elif valign.lower() == "bottom":
box_rect.bottom = y
elif valign.lower() == "middle":
box_rect.centery = y
else:
box_rect.top = y
if frame is None:
rng = six.moves.range(self.frames)
else:
rng = [frame % self.frames]
for i in rng:
dsurf = self.rd["baseimages"][i]
if blend_mode == sge.BLEND_RGB_SCREEN:
_screen_blend(dsurf, box_surf, box_rect.left, box_rect.top,
False)
elif blend_mode == sge.BLEND_RGBA_SCREEN:
_screen_blend(dsurf, box_surf, box_rect.left, box_rect.top,
True)
else:
dsurf.blit(box_surf, box_rect, None, pygame_flags)
s_refresh(self)
def draw_erase(self, x, y, width, height, frame=None):
"""
Erase part of the sprite.
Arguments:
- ``x`` -- The horizontal location relative to the sprite of the
area to erase.
- ``y`` -- The vertical location relative to the sprite of the
area to erase.
- ``width`` -- The width of the area to erase.
- ``height`` -- The height of the area to erase.
- ``frame`` -- The frame of the sprite to erase from, where
``0`` is the first frame; set to :const:`None` to erase from
all frames.
"""
if frame is None:
rng = six.moves.range(self.frames)
else:
rng = [frame % self.frames]
for i in rng:
if self.rd["baseimages"][i].get_flags() & pygame.SRCALPHA:
color = pygame.Color(0, 0, 0, 0)
else:
color = self.rd["baseimages"][i].get_colorkey()
rect = pygame.Rect(x, y, width, height)
self.rd["baseimages"][i].fill(color, rect)
s_refresh(self)
def draw_clear(self, frame=None):
"""
Erase everything from the sprite.
Arguments:
- ``frame`` -- The frame of the sprite to clear, where ``0`` is
the first frame; set to :const:`None` to clear all frames.
"""
self.draw_erase(0, 0, self.width, self.height, frame)
def draw_lock(self):
"""
Lock the sprite for continuous drawing.
Use this method to "lock" the sprite for being drawn on several
times in a row. What exactly this does depends on the
implementation and it may even do nothing at all, but calling
this method before doing several draw actions on the sprite in a
row gives the SGE a chance to make the drawing more efficient.
After you are done with continuous drawing, call
:meth:`draw_unlock` to let the SGE know that you are done
drawing.
.. warning::
Do not cause a sprite to be used while it's locked. For
example, don't leave it locked for the duration of a frame,
and don't draw it or project it on anything. The effect of
using a locked sprite could be as minor as graphical errors
and as severe as crashing the program, depending on the SGE
implementation. Always call :meth:`draw_unlock` immediately
after you're done drawing for a while.
"""
if not self.rd["locked"]:
self.rd["locked"] = True
def draw_unlock(self):
"""
Unlock the sprite.
Use this method to "unlock" the sprite after it has been
"locked" for continuous drawing by :meth:`draw_lock`.
"""
if self.rd["locked"]:
self.rd["locked"] = False
s_refresh(self)
def mirror(self, frame=None):
"""
Mirror the sprite horizontally.
Arguments:
- ``frame`` -- The frame of the sprite to mirror, where ``0`` is
the first frame; set to :const:`None` to mirror all frames.
"""
if frame is None:
rng = six.moves.range(self.frames)
else:
rng = [frame % self.frames]
for i in rng:
img = self.rd["baseimages"][i]
self.rd["baseimages"][i] = pygame.transform.flip(img, True, False)
s_refresh(self)
def flip(self, frame=None):
"""
Flip the sprite vertically.
Arguments:
- ``frame`` -- The frame of the sprite to flip, where ``0`` is
the first frame; set to :const:`None` to flip all frames.
"""
if frame is None:
rng = six.moves.range(self.frames)
else:
rng = [frame % self.frames]
for i in rng:
img = self.rd["baseimages"][i]
self.rd["baseimages"][i] = pygame.transform.flip(img, False, True)
s_refresh(self)
def resize_canvas(self, width, height):
"""
Resize the sprite by adding empty space instead of scaling.
After resizing the canvas:
1. The horizontal location of the origin is multiplied by the
new width divided by the old width.
2. The vertical location of the origin is multiplied by the new
height divided by the old height.
3. All frames are repositioned within the sprite such that their
position relative to the origin is the same as before.
Arguments:
- ``width`` -- The width to set the sprite to.
- ``height`` -- The height to set the sprite to.
"""
xscale = width / self.width
yscale = height / self.height
xdiff = self.origin_x * xscale - self.origin_x
ydiff = self.origin_y * yscale - self.origin_y
for i in six.moves.range(self.frames):
new_surf = pygame.Surface((width, height), pygame.SRCALPHA)
new_surf.fill(pygame.Color(0, 0, 0, 0))
new_surf.blit(self.rd["baseimages"][i], (int(xdiff), int(ydiff)))
self.rd["baseimages"][i] = new_surf
self.__w = width
self.__h = height
self.origin_x *= xscale
self.origin_y *= yscale
s_refresh(self)
def scale(self, xscale=1, yscale=1, frame=None):
"""
Scale the sprite to a different size.
Unlike changing :attr:`width` and :attr:`height`, this function
does not result in the actual size of the sprite changing.
Instead, any scaled frames are repositioned so that the pixel
which was at the origin before scaling remains at the origin.
Arguments:
- ``xscale`` -- The horizontal scale factor.
- ``yscale`` -- The vertical scale factor.
- ``frame`` -- The frame of the sprite to rotate, where ``0`` is
the first frame; set to :const:`None` to rotate all frames.
.. note::
This is a destructive transformation: it can result in loss
of pixel information, especially if it is done repeatedly.
Because of this, it is advised that you do not adjust this
value for routine scaling. Use the :attr:`image_xscale` and
:attr:`image_yscale` attributes of a :class:`sge.dsp.Object`
object instead.
.. note::
Because this function does not alter the actual size of the
sprite, scaling up may result in some parts of the image
being cropped off.
"""
xscale = abs(xscale)
yscale = abs(yscale)
scale_w = max(1, int(self.width * xscale))
scale_h = max(1, int(self.height * yscale))
xdiff = self.origin_x - self.origin_x * xscale
ydiff = self.origin_y - self.origin_y * yscale
if frame is None:
rng = six.moves.range(self.frames)
else:
rng = [frame % self.frames]
for i in rng:
new_surf = pygame.Surface((self.width, self.height),
pygame.SRCALPHA)
new_surf.fill(pygame.Color(0, 0, 0, 0))
surf = _scale(self.rd["baseimages"][i], scale_w, scale_h)
new_surf.blit(surf, (int(xdiff), int(ydiff)))
self.rd["baseimages"][i] = new_surf
s_refresh(self)
def rotate(self, x, adaptive_resize=True, frame=None):
"""
Rotate the sprite about the center.
Arguments:
- ``x`` -- The rotation amount in degrees, with rotation in a
positive direction being clockwise.
- ``adaptive_resize`` -- Whether or not the sprite should be
resized to accomodate rotation. If this is :const:`True`,
rotation amounts other than multiples of 180 will result in
the size of the sprite being adapted to fit the whole rotated
image. The origin and any frames which have not been rotated
will also be moved so that their location relative to the
rotated image(s) is the same.
- ``frame`` -- The frame of the sprite to rotate, where ``0`` is
the first frame; set to :const:`None` to rotate all frames.
.. note::
This is a destructive transformation: it can result in loss
of pixel information, especially if it is done repeatedly.
Because of this, it is advised that you do not adjust this
value for routine rotation. Use the :attr:`image_rotation`
attribute of a :class:`sge.dsp.Object` object instead.
"""
new_w = self.width
new_h = self.height
if frame is None:
rng = six.moves.range(self.frames)
else:
rng = [frame % self.frames]
for i in rng:
img = pygame.transform.rotate(self.rd["baseimages"][i], -x)
new_w = img.get_width()
new_h = img.get_height()
if adaptive_resize:
self.rd["baseimages"][i] = img
else:
x = -(new_w - self.__w) / 2
y = -(new_h - self.__h) / 2
self.rd["baseimages"][i].fill(pygame.Color(0, 0, 0, 0))
self.rd["baseimages"][i].blit(img, (int(x), int(y)))
if adaptive_resize:
xdiff = (new_w - self.__w) / 2
ydiff = (new_h - self.__h) / 2
self.origin_x += xdiff
self.origin_y += ydiff
self.__w = new_w
self.__h = new_h
if frame is not None:
# Need to go back and correct the positions of frames
# that weren't rotated.
for i in six.moves.range(self.frames):
if frame % self.frames != i:
surf = pygame.Surface((new_w, new_h), pygame.SRCALPHA)
surf.fill(pygame.Color(0, 0, 0, 0))
surf.blit(self.rd["baseimages"][i],
(int(xdiff), int(ydiff)))
self.rd["baseimages"][i] = surf
s_refresh(self)
def swap_color(self, old_color, new_color, frame=None):
"""
Change all pixels of one color to another color.
Arguments:
- ``old_color`` -- A :class:`sge.gfx.Color` object indicating
the color of pixels to change.
- ``new_color`` -- A :class:`sge.gfx.Color` object indicating
the color to change the pixels to.
- ``frame`` -- The frame of the sprite to modify, where ``0`` is
the first frame; set to :const:`None` to modify all frames.
.. note::
While this method can be used on any image, it is likely to
be most efficient when used on images based on palettes
(such as 8-bit images). The SGE cannot implicitly convert
high bit depth images to low bit depths, so if you plan on
using this method frequently, you should ensure that you
save your images in a low bit depth.
"""
_check_color(old_color)
_check_color(new_color)
if old_color is None or new_color is None:
return
if frame is None:
rng = six.moves.range(self.frames)
else:
rng = [frame % self.frames]
pg_new_color = pygame.Color(*new_color)
for i in rng:
img = self.rd["baseimages"][i]
try:
palette = img.get_palette()
except pygame.error:
img.lock()
for y in six.moves.range(img.get_height()):
for x in six.moves.range(img.get_width()):
if old_color == Color(tuple(img.get_at((x, y)))):
img.set_at((x, y), pg_new_color)
img.unlock()
else:
for j in six.moves.range(len(palette)):
if old_color == Color(tuple(palette[j])):
palette[j] = pg_new_color
img.set_palette(palette)
def copy(self):
"""Return a copy of the sprite."""
new_copy = Sprite(width=self.width, height=self.height,
transparent=self.transparent, origin_x=self.origin_x,
origin_y=self.origin_y, fps=self.fps,
bbox_x=self.bbox_x, bbox_y=self.bbox_y,
bbox_width=self.bbox_width,
bbox_height=self.bbox_height)
for i in range(1, self.frames):
new_copy.append_frame()
for i in range(self.frames):
new_copy.draw_sprite(self, i, self.origin_x, self.origin_y, i)
return new_copy
def save(self, fname):
"""
Save the sprite to an image file.
Arguments:
- ``fname`` -- The path of the file to save the sprite to. If
it is not a path that can be saved to, :exc:`OSError` is
raised.
If the sprite has multiple frames, the image file saved will be
a horizontal reel of each of the frames from left to right with
no space in between the frames.
"""
# Assuming self.width and self.height are the size of all
# surfaces in _baseimages (this should be the case).
w = self.width * self.frames
h = self.height
reel = pygame.Surface((w, h), pygame.SRCALPHA)
reel.fill(pygame.Color(0, 0, 0, 0))
for i in six.moves.range(self.frames):
reel.blit(self.rd["baseimages"][i], (int(self.width * i), 0))
try:
pygame.image.save(reel, fname)
except pygame.error:
m = 'Couldn\'t save to "{}"'.format(
os.path.normpath(os.path.realpath(fname)))
raise OSError(m)
@classmethod
def from_tween(cls, sprite, frames, fps=None, xscale=None, yscale=None,
rotation=None, blend=None, bbox_x=None, bbox_y=None,
bbox_width=None, bbox_height=None, blend_mode=None):
"""
Create a sprite based on tweening an existing sprite.
"Tweening" refers to creating an animation from gradual
transformations to an image. For example, this can be used to
generate an animation of an object growing to a particular size.
The animation generated is called a "tween".
Arguments:
- ``sprite`` -- The sprite to base the tween on. If the sprite
includes multiple frames, all frames will be used in sequence
until the end of the tween.
The tween's origin is derived from this sprite's origin,
adjusted appropriately to accomodate any size changes made.
Whether or not the tween is transparent is also determined by
whether or not this sprite is transparent.
- ``frames`` -- The number of frames the to make the tween take
up.
- ``fps`` -- The suggested rate of animation for the tween in
frames per second. If set to :const:`None`, the suggested
animation rate of the base sprite is used.
- ``xscale`` -- The horizontal scale factor at the end of the
tween. If set to :const:`None`, horizontal scaling will not
be included in the tweening process.
- ``yscale`` -- The vertical scale factor at the end of the
tween. If set to :const:`None`, vertical scaling will not be
included in the tweening process.
- ``rotation`` -- The total clockwise rotation amount in degrees
at the end of the tween. Can be negative to indicate
counter-clockwise rotation instead. If set to :const:`None`,
rotation will not be included in the tweening process.
- ``blend`` -- A :class:`sge.gfx.Color` object representing the
color to blend with the sprite at the end of the tween. If
set to :const:`None`, color blending will not be included in
the tweening process.
- ``blend_mode`` -- The blend mode to use with ``blend``.
Possible blend modes are:
- :data:`sge.BLEND_NORMAL`
- :data:`sge.BLEND_RGBA_ADD`
- :data:`sge.BLEND_RGBA_SUBTRACT`
- :data:`sge.BLEND_RGBA_MULTIPLY`
- :data:`sge.BLEND_RGBA_SCREEN`
- :data:`sge.BLEND_RGBA_MINIMUM`
- :data:`sge.BLEND_RGBA_MAXIMUM`
- :data:`sge.BLEND_RGB_ADD`
- :data:`sge.BLEND_RGB_SUBTRACT`
- :data:`sge.BLEND_RGB_MULTIPLY`
- :data:`sge.BLEND_RGB_SCREEN`
- :data:`sge.BLEND_RGB_MINIMUM`
- :data:`sge.BLEND_RGB_MAXIMUM`
:const:`None` is treated as :data:`sge.BLEND_RGBA_MULTIPLY`.
All other arguments set the respective initial attributes of the
tween. See the documentation for :class:`sge.gfx.Sprite` for
more information.
"""
if fps is None:
fps = sprite.fps
if blend_mode is None:
blend_mode = sge.BLEND_RGBA_MULTIPLY
new_w = sprite.width
new_h = sprite.height
new_origin_x = sprite.origin_x
new_origin_y = sprite.origin_y
if xscale is not None and xscale > 1:
new_w *= xscale
new_origin_x *= xscale
if yscale is not None and yscale > 1:
new_h *= yscale
new_origin_y *= yscale
if rotation is not None:
h = math.hypot(new_w, new_h)
new_origin_x += (h - new_w) / 2
new_origin_y += (h - new_h) / 2
new_w = h
new_h = h
tween_spr = cls(width=new_w, height=new_h,
transparent=sprite.transparent, origin_x=new_origin_x,
origin_y=new_origin_y, fps=fps, bbox_x=bbox_x,
bbox_y=bbox_y, bbox_width=bbox_width,
bbox_height=bbox_height)
while tween_spr.frames < frames:
tween_spr.append_frame()
for i in six.moves.range(frames):
tween_spr.draw_sprite(sprite, i, new_origin_x, new_origin_y,
frame=i)
progress = i / (frames - 1)
if xscale is not None or yscale is not None:
if xscale is None or xscale == 1:
xs = 1
else:
xs = 1 + (xscale - 1) * progress
if yscale is None or yscale == 1:
ys = 1
else:
ys = 1 + (yscale - 1) * progress
tween_spr.scale(xs, ys, frame=i)
if rotation is not None:
tween_spr.rotate(rotation * progress, adaptive_resize=False,
frame=i)
if blend is not None:
blender = Sprite(width=tween_spr.width, height=tween_spr.height)
if blend_mode in {sge.BLEND_RGBA_MULTIPLY,
sge.BLEND_RGBA_MINIMUM,
sge.BLEND_RGB_MULTIPLY,
sge.BLEND_RGB_MINIMUM}:
r = int(255 - (255 - blend.red) * progress)
g = int(255 - (255 - blend.green) * progress)
b = int(255 - (255 - blend.blue) * progress)
a = int(255 - (255 - blend.alpha) * progress)
elif blend_mode in {sge.BLEND_RGBA_ADD,
sge.BLEND_RGBA_SUBTRACT,
sge.BLEND_RGBA_SCREEN,
sge.BLEND_RGBA_MAXIMUM,
sge.BLEND_RGB_ADD,
sge.BLEND_RGB_SUBTRACT,
sge.BLEND_RGB_SCREEN,
sge.BLEND_RGB_MAXIMUM}:
r = int(blend.red * progress)
g = int(blend.green * progress)
b = int(blend.blue * progress)
a = int(blend.alpha * progress)
else:
r = blend.red
g = blend.green
b = blend.blue
a = int(blend.alpha * progress)
color = Color((r, g, b, a))
blender.draw_rectangle(0, 0, blender.width, blender.height,
fill=color)
tween_spr.draw_sprite(blender, 0, 0, 0, frame=i,
blend_mode=blend_mode)
return tween_spr
@classmethod
def from_text(cls, font, text, width=None, height=None,
color=Color("white"), halign="left", valign="top",
anti_alias=True):
"""
Create a sprite, draw the given text on it, and return the
sprite. See the documentation for
:meth:`sge.gfx.Sprite.draw_text` for more information.
The sprite's origin is set based on ``halign`` and ``valign``.
"""
return s_from_text(cls, font, text, width, height, color, halign,
valign, anti_alias).copy()
@classmethod
def from_tileset(cls, fname, x=0, y=0, columns=1, rows=1, xsep=0, ysep=0,
width=1, height=1, origin_x=0, origin_y=0,
transparent=True, fps=0, bbox_x=None, bbox_y=None,
bbox_width=None, bbox_height=None):
"""
Return a sprite based on the tiles in a tileset.
Arguments:
- ``fname`` -- The path to the image file containing the
tileset.
- ``x`` -- The horizontal location relative to the image of the
top-leftmost tile in the tileset.
- ``y`` -- The vertical location relative to the image of the
top-leftmost tile in the tileset.
- ``columns`` -- The number of columns in the tileset.
- ``rows`` -- The number of rows in the tileset.
- ``xsep`` -- The spacing between columns in the tileset.
- ``ysep`` -- The spacing between rows in the tileset.
- ``width`` -- The width of the tiles.
- ``height`` -- The height of the tiles.
For all other arguments, see the documentation for
:meth:`Sprite.__init__`.
Each tile in the tileset becomes a subimage of the returned
sprite, ordered first from left to right and then from top to
bottom.
"""
self = cls(width=width, height=height, origin_x=origin_x,
origin_y=origin_y, transparent=transparent, fps=fps,
bbox_x=bbox_x, bbox_y=bbox_y, bbox_width=bbox_width,
bbox_height=bbox_height)
try:
tileset = pygame.image.load(fname)
except pygame.error as e:
raise OSError(e)
for i in six.moves.range(1, rows * columns):
self.append_frame()
for i in six.moves.range(rows):
for j in six.moves.range(columns):
frame = i * columns + j
x_ = x + (width + xsep) * j
y_ = y + (height + ysep) * i
self.rd["baseimages"][frame].blit(
s_set_transparency(self, tileset), (int(-x_), int(-y_)))
s_refresh(self)
return self
@classmethod
def from_screenshot(cls, x=0, y=0, width=None, height=None):
"""
Return the current display on the screen as a sprite.
Arguments:
- ``x`` -- The horizontal location of the rectangular area to
take a screenshot of.
- ``y`` -- The vertical location of the rectangular area to take
a screenshot of.
- ``width`` -- The width of the area to take a screenshot of;
set to None for all of the area to the right of ``x`` to be
included.
- ``height`` -- The height of the area to take a screenshot of;
set to :const:`None` for all of the area below ``y`` to be
included.
If you only wish to save a screenshot (of the entire screen) to
a file, the easiest way to do that is::
sge.gfx.Sprite.from_screenshot().save("foo.png")
"""
if width is None:
width = sge.game.width - x
if height is None:
height = sge.game.height - y
if (r.game_x == 0 and r.game_y == 0 and r.game_xscale == 1 and
r.game_yscale == 1):
display_surface = r.game_window
else:
display_surface = r.game_display_surface
sprite = cls(width=width, height=height)
sprite.rd["baseimages"][0].blit(display_surface, (int(-x), int(-y)))
s_refresh(sprite)
return sprite
def __copy__(self):
return self.copy()
def __deepcopy__(self, memo):
return self.copy()
class TileGrid(object):
"""
This class represents a grid of individual sprites. This is useful
for tiled bckgrounds; it is faster than making each tile as its own
object and likely uses less RAM than drawing the tiles onto a single
large sprite.
This class is mostly compatible with :class:`sge.gfx.Sprite`, and
where its use is permitted, it is used the same way. However, an
object of this class:
- Cannot be drawn to. Drawing methods exist for compatibility only,
and have no effect.
- Cannot be scaled, mirrored, flipped, rotated, or transformed in
any way. Attempting to do so will have no effect.
- Cannot be colorized in any way, or have its transparency modified.
Attempting to do so will have no effect.
- Cannot be animated in any way. Only the first frame of each
individual sprite is considered.
- Cannot be used as a basis for precise collision detection.
.. attribute:: tiles
A list of :class:`sge.gfx.Sprite` objects to use as tiles. How
exactly they are displayed is dependent on the values of
:attr:`render_method` and :attr:`section_length`. Use
:const:`None` where no tile should be displayed.
.. attribute:: render_method
A string indicating how the tiles should be rendered. Can be one
of the following:
- ``"orthogonal"`` -- Start in the top-left corner of the grid.
Render each tile in a section to the right of the previous tile
by :attr:`tile_width` pixels. Render each section downward
from the previous section by :attr:`tile_height` pixels.
- ``"isometric"`` -- Start in the top-left corner of the grid.
Render each tile in a section to the right of the previous tile
by :attr:`tile_width` pixels. Render each section downward
from the previous section by ``tile_height / 2`` pixels.
Assuming the first section has an index of ``0``, render each
odd-numbered section to the right of the even-numbered sections
by ``tile_width / 2`` pixels.
If this is set to an invalid value or :const:`None`, it becomes
``"orthogonal"``.
.. note::
If two tiles overlap, the most recently rendered tile will
be in front (closer to the viewer).
.. attribute:: section_length
The number of tiles in one section of tiles. What constitutes a
section is defined by the value of :attr:`render_method`.
.. attribute:: tile_width
The width of each tile. What exactly this means is defined by
the value of :attr:`render_method`.
.. note::
For reasons of efficiency, it is assumed that all sprites in
:attr:`tiles` have a width exactly corresponding to the width
specified here. Attempting to use sprites which have
different widths will not cause an error, but the visual
result of this, particularly any portion of a sprite outside
of its designated area, is undefined.
.. attribute:: tile_width
The height of each tile. What exactly this means is defined by
the value of :attr:`render_method`.
.. note::
For reasons of efficiency, it is assumed that all sprites in
:attr:`tiles` have a height exactly corresponding to the
height specified here. Attempting to use sprites which have
different widths will not cause an error, but the visual
result of this, particularly any portion of a sprite outside
of its designated area, is undefined.
.. attribute:: width
The total width of the tile grid in pixels. Attempting to change
this value has no effect and is only supported for compatibility
with :class:`sge.gfx.Sprite`.
.. attribute:: height
The total height of the tile grid in pixels. Attempting to
change this value has no effect and is only supported for
compatibility with :class:`sge.gfx.Sprite`.
.. attribute:: origin_x
The suggested horizontal location of the origin relative to the
left edge of the grid.
.. attribute:: origin_y
The suggested vertical location of the origin relative to the top
edge of the grid.
.. attribute:: bbox_x
The horizontal location relative to the grid of the suggested
bounding box to use with it. If set to :const:`None`, it will
become equal to ``-origin_x`` (which is always the left edge of
the grid).
.. attribute:: bbox_y
The vertical location relative to the grid of the suggested
bounding box to use with it. If set to :const:`None`, it will
become equal to ``-origin_y`` (which is always the top edge of
the grid).
.. attribute:: bbox_width
The width of the suggested bounding box. If set to
:const:`None`, it will become equal to ``width - bbox_x``
(which is always everything on the grid to the right of
:attr:`bbox_x`).
.. attribute:: bbox_height
The height of the suggested bounding box. If set to
:const:`None`, it will become equal to ``height - bbox_y``
(which is always everything on the grid below :attr:`bbox_y`).
.. attribute:: transparent
Defined as :const:`True`. Provided for compatibility with
:class:`sge.gfx.Sprite`.
.. attribute:: fps
Defined as ``0``. Provided for compatibility with
:class:`sge.gfx.Sprite`.
.. attribute:: speed
Defined as ``0``. Provided for compatibility with
:class:`sge.gfx.Sprite`.
.. attribute:: name
Defined as :const:`None`. Provided for compatibility with
:class:`sge.gfx.Sprite`. (Read-only)
.. attribute:: frames
Defined as ``1``. Provided for compatibility with
:class:`sge.gfx.Sprite`. (Read-only)
.. attribute:: rd
Reserved dictionary for internal use by the SGE. (Read-only)
"""
@property
def width(self):
if self.render_method == "isometric":
w = self.tile_width
return self.section_length * w + (w / 2)
else:
return self.section_length * self.tile_width
@width.setter
def width(self, value):
pass
@property
def height(self):
rows = len(self.tiles) / self.section_length
if self.render_method == "isometric":
h = self.tile_height / 2
return self.section_length * h + h
else:
return rows * self.tile_height
@height.setter
def height(self, value):
pass
@property
def bbox_x(self):
return self.__bbox_x
@bbox_x.setter
def bbox_x(self, value):
if value is not None:
self.__bbox_x = value
else:
self.__bbox_x = -self.origin_x
@property
def bbox_y(self):
return self.__bbox_y
@bbox_y.setter
def bbox_y(self, value):
if value is not None:
self.__bbox_y = value
else:
self.__bbox_y = -self.origin_y
@property
def bbox_width(self):
return self.__bbox_width
@bbox_width.setter
def bbox_width(self, value):
if value is not None:
self.__bbox_width = value
else:
self.__bbox_width = self.width - self.bbox_y
@property
def bbox_height(self):
return self.__bbox_height
@bbox_height.setter
def bbox_height(self, value):
if value is not None:
self.__bbox_height = value
else:
self.__bbox_height = self.height - self.bbox_y
def __init__(self, tiles, render_method=None, section_length=1,
tile_width=16, tile_height=16, origin_x=0, origin_y=0,
bbox_x=None, bbox_y=None, bbox_width=None, bbox_height=None):
"""
Arguments set the respective initial attributes of the grid.
See the documentation for :class:`xsge.gfx.TileGrid` for more
information.
"""
self.rd = {}
self.tiles = tiles
self.render_method = render_method
self.section_length = section_length
self.tile_width = tile_width
self.tile_height = tile_height
self.origin_x = origin_x
self.origin_y = origin_y
self.bbox_x = bbox_x
self.bbox_y = bbox_y
self.bbox_width = bbox_width
self.bbox_height = bbox_height
self.transparent = True
self.fps = 0
self.speed = 0
self.name = None
self.frames = 1
def copy(self):
"""Return a shallow copy of the grid."""
return self.__class__(
self.tiles, render_method=self.render_method,
section_length=self.section_length, tile_width=self.tile_width,
tile_height=self.tile_height, origin_x=self.origin_x,
origin_y=self.origin_y, fps=self.fps, bbox_x=self.bbox_x,
bbox_y=self.bbox_y, bbox_width=self.bbox_width,
bbox_height=self.bbox_height)
def render(self):
"""
Return a sprite with the grid rendered to it as a single image.
For simplicity, the width of the resulting sprite is exactly
:attr:`width`, and the height of the sprite is exactly
:attr:`height`, even if this results in parts of some of the
sprites being cut off from the resulting image.
.. warning::
If the grid is large, the returned sprite may use a large
amount of RAM. Keep this in mind if RAM availability is
limited.
"""
rendered_sprite = Sprite(width=self.width, height=self.height)
tg_blit(self, rendered_sprite, (0, 0))
s_refresh(rendered_sprite)
return rendered_sprite
def save(self, fname):
"""
Render the grid and then save it to an image file.
Calling ``self.save(fname)`` is equivalent to::
self.render().save(fname)
See the documentation for :meth:`render` and
:meth:`sge.gfx.Sprite.save` for more information.
"""
self.render().save(fname)
def append_frame(self, *args, **kwargs):
"""
Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`.
"""
def insert_frame(self, *args, **kwargs):
"""
Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`.
"""
def delete_frame(self, *args, **kwargs):
"""
Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`.
"""
def draw_dot(self, *args, **kwargs):
"""
Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`.
"""
def draw_line(self, *args, **kwargs):
"""
Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`.
"""
def draw_rectangle(self, *args, **kwargs):
"""
Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`.
"""
def draw_ellipse(self, *args, **kwargs):
"""
Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`.
"""
def draw_circle(self, *args, **kwargs):
"""
Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`.
"""
def draw_polygon(self, *args, **kwargs):
"""
Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`.
"""
def draw_sprite(self, *args, **kwargs):
"""
Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`.
"""
def draw_text(self, *args, **kwargs):
"""
Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`.
"""
def draw_erase(self, *args, **kwargs):
"""
Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`.
"""
def draw_clear(self, *args, **kwargs):
"""
Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`.
"""
def draw_lock(self, *args, **kwargs):
"""
Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`.
"""
def draw_unlock(self, *args, **kwargs):
"""
Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`.
"""
def mirror(self, *args, **kwargs):
"""
Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`.
"""
def flip(self, *args, **kwargs):
"""
Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`.
"""
def rotate(self, *args, **kwargs):
"""
Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`.
"""
def __copy__(self):
return self.copy()
def __deepcopy__(self, memo):
tiles_copy = []
for tile in self.tiles:
tiles_copy.append(tile.copy())
return self.__class__(
tiles_copy, render_method=self.render_method,
section_length=self.section_length, tile_width=self.tile_width,
tile_height=self.tile_height, origin_x=self.origin_x,
origin_y=self.origin_y, fps=self.fps, bbox_x=self.bbox_x,
bbox_y=self.bbox_y, bbox_width=self.bbox_width,
bbox_height=self.bbox_height)
class Font(object):
"""
This class stores a font for use by text drawing methods.
Note that bold and italic rendering could be ugly. It is better to
choose a bold or italic font rather than enabling bold or italic
rendering, if possible.
.. attribute:: size
The height of the font in pixels.
.. attribute:: underline
Whether or not underlined rendering is enabled.
.. attribute:: bold
Whether or not bold rendering is enabled.
.. note::
Using this option can be ugly. It is better to choose a bold
font rather than enabling bold rendering, if possible.
.. attribute:: italic
Whether or not italic rendering is enabled.
.. note::
Using this option can be ugly. It is better to choose an
italic font rather than enabling italic rendering, if
possible.
.. attribute:: name
The name of the font as specified when it was created.
(Read-only)
.. attribute:: rd
Reserved dictionary for internal use by the SGE. (Read-only)
"""
@property
def size(self):
return self.__size
@size.setter
def size(self, value):
if self.rd.get("font") is not None:
# Preserve underline, bold, and italic settings.
underline = self.underline
bold = self.bold
italic = self.italic
else:
underline = False
bold = False
italic = False
self.__size = value
self.rd["font"] = None
if isinstance(self.name, six.string_types):
names = [self.name]
else:
try:
names = list(self.name)
except TypeError:
# Most likely a non-iterable value, such as None, so we
# assume the default font is to be used.
names = []
for name in names:
if os.path.isfile(name):
self.rd["font"] = pygame.font.Font(name, self.__size)
break
elif pygame.font.match_font(name):
self.rd["font"] = pygame.font.SysFont(
','.join(names), self.__size)
break
else:
default_names = [
"courier", "courier new", "courier prime", "freemono",
"liberation mono", "dejavu sans mono", "droid sans mono",
"nimbus mono l", "cousine", "texgyrecursor"]
self.rd["font"] = pygame.font.SysFont(
','.join(default_names), self.__size)
# Restore underline, bold, and italic settings.
self.underline = underline
self.bold = bold
self.italic = italic
@property
def underline(self):
return self.rd["font"].get_underline()
@underline.setter
def underline(self, value):
self.rd["font"].set_underline(bool(value))
@property
def bold(self):
return self.rd["font"].get_bold()
@bold.setter
def bold(self, value):
self.rd["font"].set_bold(bool(value))
@property
def italic(self):
return self.rd["font"].get_italic()
@italic.setter
def italic(self, value):
self.rd["font"].set_italic(bool(value))
def __init__(self, name=None, size=12, underline=False, bold=False,
italic=False):
"""
Arguments:
- ``name`` -- The name of the font. Can be one of the
following:
- A string indicating the path to the font file.
- A string indicating the case-insensitive name of a system
font, e.g. ``"Liberation Serif"``.
- A list or tuple of strings indicating either a font file or
a system font to choose from in order of preference.
If none of the above methods return a valid font, the SGE will
choose the font.
All other arguments set the respective initial attributes of the
font. See the documentation for :class:`sge.gfx.Font` for more
information.
.. note::
It is generally not a good practice to rely on system fonts.
There are no standard fonts; a font which you have on your
system is probably not on everyone's system. Rather than
relying on system fonts, choose a font which is under a libre
license (such as the GNU General Public License or the SIL
Open Font License) and distribute it with your game; this
will ensure that everyone sees text rendered the same way you
do.
"""
self.rd = {}
self.name = name
self.size = size
self.underline = underline
self.bold = bold
self.italic = italic
def get_width(self, text, width=None, height=None):
"""
Return the width of a certain string of text when rendered.
See the documentation for :meth:`sge.gfx.Sprite.draw_text` for
more information.
"""
lines = f_split_text(self, text, width)
text_width = 0
for line in lines:
text_width = max(text_width, self.rd["font"].size(line)[0])
if width is not None:
text_width = min(text_width, width)
return text_width
def get_height(self, text, width=None, height=None):
"""
Return the height of a certain string of text when rendered.
See the documentation for :meth:`sge.gfx.Sprite.draw_text` for
more information.
"""
lines = f_split_text(self, text, width)
if lines:
text_height = self.rd["font"].get_linesize() * (len(lines) - 1)
text_height += self.rd["font"].size(lines[-1])[1]
else:
text_height = 0
if height is not None:
text_height = min(text_height, height)
return text_height
@classmethod
def from_sprite(cls, sprite, chars, hsep=0, vsep=0, size=12,
underline=False, bold=False, italic=False):
"""
Return a font derived from a sprite.
Arguments:
- ``sprite`` -- The :class:`sge.gfx.Sprite` object to derive the
font from.
- ``chars`` -- A dictionary mapping each supported text
character to the corresponding frame of the sprite. For
example, ``{'A': 0, 'B': 1, 'C': 2}`` would assign the letter
"A' to the first frame, the letter "B" to the second frame,
and the letter "C" to the third frame.
Alternatively, this can be given as a list of characters to
assign to the frames corresponding to the characters' indexes
within the list. For example, ``['A', 'B', 'C']`` would
assign the letter "A" to the first frame, the letter "B" to
the second frame, and the letter "C" to the third frame.
Any character not explicitly mapped to a frame will be
rendered as its differently-cased counterpart if possible
(e.g. "A" as "a"). Otherwise, it will be rendered using the
frame mapped to :const:`None`. If :const:`None` has not been
explicitly mapped to a frame, it is implied to be a blank
space.
- ``hsep`` -- The amount of horizontal space to place between
characters when text is rendered.
- ``vsep`` -- The amount of vertical space to place between
lines when text is rendered.
All other arguments set the respective initial attributes of the
font. See the documentation for :class:`sge.gfx.Font` for more
information.
The font's :attr:`name` attribute will be set to the name of the
sprite the font is derived from.
The font's :attr:`size` attribute will indicate the height of
the characters in pixels. The width of the characters will be
adjusted proportionally.
"""
if not isinstance(sprite, Sprite):
e = "{} is not a valid Sprite object.".format(repr(sprite))
raise TypeError(e)
return _SpriteFont(sprite, chars, hsep, vsep, size, underline, bold,
italic)
class _PygameSpriteFont(pygame.font.Font):
# Special font class that returns good values for a sprite font.
@property
def vsize(self):
return self.height
@vsize.setter
def vsize(self, value):
if self.height != 0:
scale_factor = value / self.height
if scale_factor != 1:
self.width *= scale_factor
self.height *= scale_factor
else:
# Protection against division by zero.
self.width = value
self.height = value
def __init__(self, sprite, chars, hsep, vsep, size):
self.sprite = sprite
self.hsep = hsep
self.vsep = vsep
if isinstance(chars, dict):
self.chars = chars
else:
self.chars = {}
for i in six.moves.range(len(chars)):
self.chars[chars[i]] = i
self.width = self.sprite.width
self.height = self.sprite.height
self.vsize = size
self.underline = False
self.bold = False
self.italic = False
def render(self, text, antialias, color, background=None):
w, h = self.size(text)
xscale = (self.width / self.sprite.width if self.sprite.width > 0
else 1)
yscale = (self.height / self.sprite.height if self.sprite.height > 0
else 1)
surf = pygame.Surface((w, h), pygame.SRCALPHA)
surf.fill(pygame.Color(0, 0, 0, 0))
if not isinstance(color, pygame.Color):
color = pygame.Color(color)
sge_color = Color((color.r, color.g, color.b, color.a))
for i in six.moves.range(len(text)):
if text[i] in self.chars:
cimg = s_get_image(self.sprite, self.chars[text[i]],
xscale=xscale, yscale=yscale,
blend=sge_color)
surf.blit(cimg, (int(i * (self.width + self.hsep)), 0))
elif text[i].swapcase() in self.chars:
cimg = s_get_image(self.sprite, self.chars[text[i].swapcase()],
xscale=xscale, yscale=yscale,
blend=sge_color)
surf.blit(cimg, (int(i * (self.width + self.hsep)), 0))
elif None in self.chars:
cimg = s_get_image(self.sprite, self.chars[None],
xscale=xscale, yscale=yscale,
blend=sge_color)
surf.blit(cimg, (int(i * (self.width + self.hsep)), 0))
if background is None:
return surf
else:
rsurf = pygame.Surface((w, h), pygame.SRCALPHA)
rsurf.fill(background)
rsurf.blit(surf, (0, 0))
return rsurf
def size(self, text):
# XXX: I don't understand why, but adding an extra pixel to both
# the width and the height is necessary. Without this extra
# pixel of width and height, the rightmost column and bottom row
# of pixels end up not being displayed.
return (int(self.width * len(text) + self.hsep * (len(text) - 1)) + 1,
int(self.height) + 1)
def set_underline(self, bool_):
self.underline = bool_
def get_underline(self):
return self.underline
def set_bold(self, bool_):
self.bold = bool_
def get_bold(self):
return self.bold
def set_italic(self, bool_):
self.italic = bool_
def get_italic(self):
return self.italic
def metrics(self, text):
m = (0, self.width, 0, self.height, self.width)
return [m for char in text]
def get_linesize(self):
return self.height + self.vsep
def get_height(self):
return self.height
def get_ascent(self):
return self.height
def get_descent(self):
return 0
class _SpriteFont(Font):
# Special sprite font class for Font.from_sprite.
@property
def size(self):
return self.rd["font"].vsize
@size.setter
def size(self, value):
self.rd["font"].vsize = value
def __init__(self, sprite, chars, hsep=0, vsep=0, size=12, underline=False,
bold=False, italic=False):
self.rd = {}
self.name = sprite.name
self.rd["font"] = _PygameSpriteFont(sprite, chars, hsep, vsep, size)
self.underline = underline
self.bold = bold
self.italic = italic
class BackgroundLayer(object):
"""
This class stores a sprite and certain information for a layer of a
background. In particular, it stores the location of the layer,
whether the layer tiles horizontally, vertically, or both, and the
rate at which it scrolls.
.. attribute:: sprite
The sprite used for this layer. It will be animated normally if
it contains multiple frames.
.. attribute:: x
The horizontal location of the layer relative to the background.
.. attribute:: y
The vertical location of the layer relative to the background.
.. attribute:: z
The Z-axis position of the layer in the room.
.. attribute:: xscroll_rate
The horizontal rate that the layer scrolls as a factor of the
additive inverse of the horizontal movement of the view.
.. attribute:: yscroll_rate
The vertical rate that the layer scrolls as a factor of the
additive inverse of the vertical movement of the view.
.. attribute:: repeat_left
Whether or not the layer should be repeated (tiled) to the left.
.. attribute:: repeat_right
Whether or not the layer should be repeated (tiled) to the right.
.. attribute:: repeat_up
Whether or not the layer should be repeated (tiled) upwards.
.. attribute:: repeat_down
Whether or not the layer should be repeated (tiled) downwards.
.. attribute:: rd
Reserved dictionary for internal use by the SGE. (Read-only)
"""
def __init__(self, sprite, x, y, z=0, xscroll_rate=1, yscroll_rate=1,
repeat_left=False, repeat_right=False, repeat_up=False,
repeat_down=False):
"""
Arguments set the respective initial attributes of the layer.
See the documentation for :class:`sge.gfx.BackgroundLayer` for
more information.
"""
self.rd = {}
self.sprite = sprite
self.x = x
self.y = y
self.z = z
self.xscroll_rate = xscroll_rate
self.yscroll_rate = yscroll_rate
self.repeat_left = repeat_left
self.repeat_right = repeat_right
self.repeat_up = repeat_up
self.repeat_down = repeat_down
self.rd["fps"] = 0
self.rd["image_index"] = 0
self.rd["count"] = 0
self.rd["frame_time"] = None
class Background(object):
"""
This class stores the layers that make up the background (which
contain the information about what images to use and where) as well
as the color to use where no image is shown.
.. attribute:: layers
A list containing all :class:`sge.gfx.BackgroundLayer` objects
used in this background. (Read-only)
.. attribute:: color
A :class:`sge.gfx.Color` object representing the color used in
parts of the background where no layer is shown.
.. attribute:: rd
Reserved dictionary for internal use by the SGE. (Read-only)
"""
@property
def color(self):
return self.__color
@color.setter
def color(self, value):
_check_color(value)
self.__color = value
def __init__(self, layers, color):
"""
Arguments set the respective initial attributes of the
background. See the documentation for
:class:`sge.gfx.Background` for more information.
"""
self.rd = {}
self.color = color
sorted_layers = []
for layer in layers:
i = 0
while i < len(sorted_layers) and layer.z >= sorted_layers[i].z:
i += 1
sorted_layers.insert(i, layer)
self.layers = sorted_layers
|
iirlas/OpenJam-2017
|
sge/gfx.py
|
Python
|
gpl-3.0
| 106,231 | 0.000028 |
"""
Created by Emille Ishida in May, 2015.
Class to implement calculations on data matrix.
"""
import os
import sys
import matplotlib.pylab as plt
import numpy as np
from multiprocessing import Pool
from snclass.treat_lc import LC
from snclass.util import read_user_input, read_snana_lc, translate_snid
from snclass.functions import core_cross_val, screen
##############################################
class DataMatrix(object):
"""
Data matrix class.
Methods:
- build: Build data matrix according to user input file specifications.
- reduce_dimension: Perform dimensionality reduction.
- cross_val: Perform cross-validation.
Attributes:
- user_choices: dict, user input choices
- snid: vector, list of objects identifiers
- datam: array, data matrix for training
- redshift: vector, redshift for training data
- sntype: vector, classification of training data
- low_dim_matrix: array, data matrix in KernelPC space
- transf_test: function, project argument into KernelPC space
- final: vector, optimize parameter values
"""
def __init__(self, input_file=None):
"""
Read user input file.
input: input_file -> str
name of user input file
"""
self.datam = None
self.snid = []
self.redshift = None
self.sntype = None
self.low_dim_matrix = None
self.transf_test = None
self.final = None
self.test_projection = []
if input_file is not None:
self.user_choices = read_user_input(input_file)
def check_file(self, filename, epoch=True, ref_filter=None):
"""
Construct one line of the data matrix.
input: filename, str
file of raw data for 1 supernova
epoch, bool - optional
If true, check if SN satisfies epoch cuts
Default is True
ref_filter, str - optional
Reference filter for peak MJD calculation
Default is None
"""
screen('Fitting ' + filename, self.user_choices)
# translate identifier
self.user_choices['path_to_lc'] = [translate_snid(filename, self.user_choices['photon_flag'][0])[0]]
# read light curve raw data
raw = read_snana_lc(self.user_choices)
# initiate light curve object
lc_obj = LC(raw, self.user_choices)
# load GP fit
lc_obj.load_fit_GP(self.user_choices['samples_dir'][0] + filename)
# normalize
lc_obj.normalize(ref_filter=ref_filter)
# shift to peak mjd
lc_obj.mjd_shift()
if epoch:
# check epoch requirements
lc_obj.check_epoch()
else:
lc_obj.epoch_cuts = True
if lc_obj.epoch_cuts:
# build data matrix lines
lc_obj.build_steps()
# store
obj_line = []
for fil in self.user_choices['filters']:
for item in lc_obj.flux_for_matrix[fil]:
obj_line.append(item)
rflag = self.user_choices['redshift_flag'][0]
redshift = raw[rflag][0]
obj_class = raw[self.user_choices['type_flag'][0]][0]
self.snid.append(raw['SNID:'][0])
return obj_line, redshift, obj_class
else:
screen('... Failed to pass epoch cuts!', self.user_choices)
screen('\n', self.user_choices)
return None
def store_training(self, file_out):
"""
Store complete training matrix.
input: file_out, str
output file name
"""
# write to file
if file_out is not None:
op1 = open(file_out, 'w')
op1.write('SNID type z LC...\n')
for i in xrange(len(self.datam)):
op1.write(str(self.snid[i]) + ' ' + str(self.sntype[i]) +
' ' + str(self.redshift[i]) + ' ')
for j in xrange(len(self.datam[i])):
op1.write(str(self.datam[i][j]) + ' ')
op1.write('\n')
op1.close()
def build(self, file_out=None, check_epoch=True, ref_filter=None):
"""
Build data matrix according to user input file specifications.
input: file_out -> str, optional
file to store data matrix (str). Default is None
check_epoch -> bool, optional
If True check if SN satisfies epoch cuts
Default is True
ref_filter -> str, optional
Reference filter for MJD calculation
Default is None
"""
# list all files in sample directory
file_list = os.listdir(self.user_choices['samples_dir'][0])
datam = []
redshift = []
sntype = []
for obj in file_list:
if 'mean' in obj:
sn_char = self.check_file(obj, epoch=check_epoch,
ref_filter=ref_filter)
if sn_char is not None:
datam.append(sn_char[0])
redshift.append(sn_char[1])
sntype.append(sn_char[2])
self.datam = np.array(datam)
self.redshift = np.array(redshift)
self.sntype = np.array(sntype)
# store results
self.store_training(file_out)
def reduce_dimension(self):
"""Perform dimensionality reduction with user defined function."""
# define dimensionality reduction function
func = self.user_choices['dim_reduction_func']
# reduce dimensionality
self.low_dim_matrix = func(self.datam, self.user_choices)
# define transformation function
self.transf_test = func(self.datam, self.user_choices, transform=True)
def cross_val(self):
"""Optimize the hyperparameters for RBF kernel and ncomp."""
# correct type parameters if necessary
types_func = self.user_choices['transform_types_func']
if types_func is not None:
self.sntype = types_func(self.sntype, self.user_choices['Ia_flag'][0])
# initialize parameters
data = self.datam
types = self.sntype
choices = self.user_choices
nparticles = self.user_choices['n_cross_val_particles']
parameters = []
for i in xrange(nparticles):
pars = {}
pars['data'] = data
pars['types'] = types
pars['user_choices'] = choices
parameters.append(pars)
if int(self.user_choices['n_proc'][0]) > 0:
cv_func = self.user_choices['cross_validation_func']
pool = Pool(processes=int(self.user_choices['n_proc'][0]))
my_pool = pool.map_async(cv_func, parameters)
try:
results = my_pool.get(0xFFFF)
except KeyboardInterrupt:
print 'Interruputed by the user!'
sys.exit()
pool.close()
pool.join()
results = np.array(results)
else:
number = self.user_choices['n_cross_val_particles']
results = np.array([core_cross_val(pars)
for pars in parameters])
flist = list(results[:,len(results[0])-1])
max_success = max(flist)
indx_max = flist.index(max_success)
self.final = {}
for i in xrange(len(self.user_choices['cross_val_par'])):
par_list = self.user_choices['cross_val_par']
self.final[par_list[i]] = results[indx_max][i]
def final_configuration(self):
"""Determine final configuraton based on cross-validation results."""
#update optimized hyper-parameters
for par in self.user_choices['cross_val_par']:
indx = self.user_choices['cross_val_par'].index(par)
self.user_choices[par] = self.final[par]
#update low dimensional matrix
self.reduce_dimension()
def plot(self, pcs, file_out, show=False, test=None):
"""
Plot 2-dimensional scatter of data matrix in kPCA space.
input: pcs, vector of int
kernel PCs to be used as horizontal and vertical axis
file_out, str
file name to store final plot
show, bool, optional
if True show plot in screen
Default is False
test, dict, optional
keywords: data, type
if not None plot the projection of 1 photometric object
Default is None
"""
#define vectors to plot
xdata = self.low_dim_matrix[:,pcs[0]]
ydata = self.low_dim_matrix[:,pcs[1]]
if '0' in self.sntype:
snIa = self.sntype == '0'
nonIa = self.sntype != '0'
else:
snIa = self.sntype == 'Ia'
snIbc = self.sntype == 'Ibc'
snII = self.sntype == 'II'
plt.figure(figsize=(10,10))
if '0' in self.sntype:
plt.scatter(xdata[nonIa], ydata[nonIa], color='purple', marker='s',
label='spec non-Ia')
plt.scatter(xdata[snIa], ydata[snIa], color='blue', marker='o',
label='spec Ia')
else:
plt.scatter(xdata[snII], ydata[snII], color='purple', marker='s',
label='spec II')
plt.scatter(xdata[snIbc], ydata[snIbc], color='green', marker='^',
s=30, label='spec Ibc')
plt.scatter(xdata[snIa], ydata[snIa], color='blue', marker='o',
label='spec Ia')
if test is not None:
if len(test.samples_for_matrix) > 0:
plt.title('prob_Ia = ' + str(round(test['prob_Ia'], 2)))
if test.raw['SIM_NON1a:'][0] == '0':
sntype = 'Ia'
else:
sntype = 'nonIa'
plt.scatter([test.test_proj[0][pcs[0]]], [test.test_proj[0][pcs[1]]],
marker='*', color='red', s=75,
label='photo ' + sntype)
plt.xlabel('kPC' + str(pcs[0] + 1), fontsize=14)
plt.ylabel('kPC' + str(pcs[1] + 1), fontsize=14)
plt.legend(fontsize=12)
if show:
plt.show()
if file_out is not None:
plt.savefig(file_out)
plt.close()
def main():
"""Print documentation."""
print __doc__
if __name__ == '__main__':
main()
|
emilleishida/snclass
|
snclass/matrix.py
|
Python
|
gpl-3.0
| 10,669 | 0.001312 |
"""
The mean of three integers A, B and C is (A + B + C)/3. The median of three integers is the one that would be in the
middle if they are sorted in non-decreasing order. Given two integers A and B, return the minimum possible integer C
such that the mean and the median of A, B and C are equal.
Input
Each test case is given in a single line that contains two integers A and B (1 ≤ A ≤ B ≤ 109). The last test case is
followed by a line containing two zeros.
Output
For each test case output one line containing the minimum possible integer C such that the mean and the median of A, B
and C are equal.
"""
A = int
B = int
C = int
while B != 0 and C != 0:
B, C = map(int, input().split())
if 1 <= B <= C <= 10 ** 9:
A = 2 * B - C
print(A)
|
deyvedvm/cederj
|
urionlinejudge/python/1379.py
|
Python
|
gpl-3.0
| 781 | 0.006452 |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v10.enums",
marshal="google.ads.googleads.v10",
manifest={"AssetSetAssetStatusEnum",},
)
class AssetSetAssetStatusEnum(proto.Message):
r"""Container for enum describing possible statuses of an asset
set asset.
"""
class AssetSetAssetStatus(proto.Enum):
r"""The possible statuses of an asset set asset."""
UNSPECIFIED = 0
UNKNOWN = 1
ENABLED = 2
REMOVED = 3
__all__ = tuple(sorted(__protobuf__.manifest))
|
googleads/google-ads-python
|
google/ads/googleads/v10/enums/types/asset_set_asset_status.py
|
Python
|
apache-2.0
| 1,168 | 0.000856 |
# Copyright (c) 2021, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import numpy as np
import pytest
from coremltools.converters.mil.mil import Builder as mb
from coremltools.converters.mil.testing_utils import (
assert_model_is_valid,
get_op_types_in_program,
apply_pass_and_basic_check,
)
np.random.seed(6174)
class TestLayerNormOrInstanceNormFusionPass:
@pytest.mark.parametrize("axes_size", [1, 2, 3])
def test_layer_norm(self, axes_size):
"""
Detect layer norm pattern, found in the TF bert model.
y = x * [gamma * rsqrt(variance + eps)] + (beta - mean * [gamma * rsqrt(variance + eps)])
where mean and variance are computed along axes [-1] or [-1,-2] and so on
and gamma and beta are constants with rank equal to the length of the axes parameter.
"""
shape = (3, 5, 6)
rank = len(shape)
axes = list(range(rank - axes_size, rank))
@mb.program(input_specs=[mb.TensorSpec(shape=shape)])
def prog(x):
x1 = mb.reduce_mean(x=x, axes=axes, keep_dims=True)
x2 = mb.sub(x=x, y=x1)
x2 = mb.square(x=x2)
x2 = mb.reduce_mean(x=x2, axes=axes, keep_dims=True)
x2 = mb.add(x=x2, y=1e-5)
x2 = mb.rsqrt(x=x2)
x3 = mb.mul(x=np.random.rand(*shape[-len(axes) :]), y=x2)
x4 = mb.mul(x=x3, y=x1)
x5 = mb.mul(x=x, y=x3)
x4 = mb.sub(x=np.random.rand(*shape[-len(axes) :]), y=x4)
y = mb.add(x=x4, y=x5)
return y
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "common::fuse_layernorm_or_instancenorm"
)
assert get_op_types_in_program(prev_prog) == [
"reduce_mean",
"sub",
"square",
"reduce_mean",
"add",
"rsqrt",
"mul",
"mul",
"mul",
"sub",
"add",
]
assert get_op_types_in_program(prog) == ["layer_norm"]
assert_model_is_valid(
prog, {"x": shape}, expected_output_shapes={block.outputs[0].name: shape}
)
def test_instance_norm_pattern_1(self):
"""
Detect instance norm pattern
y = x * [gamma * rsqrt(variance + eps)] + (beta - mean * [gamma * rsqrt(variance + eps)])
where input is rank 4, (N,C,H,W), axis=[2, 3], along which reduction happens,
and gamma and beta are of shape (1,C,1,1)
"""
shape = (3, 5, 6, 7)
@mb.program(input_specs=[mb.TensorSpec(shape=shape)])
def prog(x):
x1 = mb.reduce_mean(x=x, axes=[2, 3], keep_dims=True)
x2 = mb.sub(x=x, y=x1)
x2 = mb.square(x=x2)
x2 = mb.reduce_mean(x=x2, axes=[2, 3], keep_dims=True)
x2 = mb.add(x=x2, y=1e-5)
x2 = mb.rsqrt(x=x2)
x3 = mb.mul(x=np.random.rand(1, shape[1], 1, 1), y=x2)
x4 = mb.mul(x=x3, y=x1)
x5 = mb.mul(x=x, y=x3)
x4 = mb.sub(x=np.random.rand(1, shape[1], 1, 1), y=x4)
y = mb.add(x=x4, y=x5)
return y
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "common::fuse_layernorm_or_instancenorm"
)
assert get_op_types_in_program(prev_prog) == [
"reduce_mean",
"sub",
"square",
"reduce_mean",
"add",
"rsqrt",
"mul",
"mul",
"mul",
"sub",
"add",
]
assert get_op_types_in_program(prog) == ["instance_norm"]
assert_model_is_valid(
prog, {"x": shape}, expected_output_shapes={block.outputs[0].name: shape}
)
def test_instance_norm_pattern_1_rank_1_gamma_beta(self):
"""
Detect instance norm pattern
y = x * [gamma * rsqrt(variance + eps)] + (beta - mean * [gamma * rsqrt(variance + eps)])
where input is rank 4, (N,C,H,W), axis=[2, 3], along which reduction happens,
and gamma and beta are of shape (C,)
"""
shape = (3, 5, 6, 7)
@mb.program(input_specs=[mb.TensorSpec(shape=shape)])
def prog(x):
x1 = mb.reduce_mean(x=x, axes=[1, 2], keep_dims=True)
x2 = mb.sub(x=x, y=x1)
x2 = mb.square(x=x2)
x2 = mb.reduce_mean(x=x2, axes=[1, 2], keep_dims=True)
x2 = mb.add(x=x2, y=1e-5)
x2 = mb.rsqrt(x=x2)
x3 = mb.mul(x=np.random.rand(shape[3]), y=x2)
x4 = mb.mul(x=x3, y=x1)
x5 = mb.mul(x=x, y=x3)
x4 = mb.sub(x=np.random.rand(shape[3]), y=x4)
y = mb.add(x=x4, y=x5)
return y
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "common::fuse_layernorm_or_instancenorm"
)
assert get_op_types_in_program(prev_prog) == [
"reduce_mean",
"sub",
"square",
"reduce_mean",
"add",
"rsqrt",
"mul",
"mul",
"mul",
"sub",
"add",
]
assert get_op_types_in_program(prog) == ["transpose", "instance_norm", "transpose"]
assert_model_is_valid(
prog, {"x": shape}, expected_output_shapes={block.outputs[0].name: shape}
)
def test_instance_norm_pattern_1_with_channel_last_data_format(self):
"""
Detect instance norm pattern with channel last data format
x = transpose(x) # channel first to channel last, NCHW -> NHWC
x = x * [gamma * rsqrt(variance + eps)] + (beta - mean * [gamma * rsqrt(variance + eps)])
x = transpose(x) # channel last to channel first, NHWC -> NCHW
The input is rank 4 (N, C, H, W) and the input for fused "instance_norm" op is
rank 4 (N, H, W, C), and axis=[1, 2] or [-3, -2], along which reduction happens.
This is common in TensorFlow model when data format is channel last.
PyMIL inserts transposes around "conv" layer to make "conv" channel first.
"fuse_layernorm_or_instancenorm" pass is expected to fuse this pattern as well.
"""
shape = (1, 3, 5, 5)
@mb.program(input_specs=[mb.TensorSpec(shape=shape)])
def prog(x):
x = mb.transpose(x=x, perm=[0, 2, 3, 1])
x1 = mb.reduce_mean(x=x, axes=[1, 2], keep_dims=True)
x2 = mb.sub(x=x, y=x1)
x2 = mb.square(x=x2)
x2 = mb.reduce_mean(x=x2, axes=[1, 2], keep_dims=True)
x2 = mb.add(x=x2, y=1e-5)
x2 = mb.rsqrt(x=x2)
x3 = mb.mul(x=np.random.rand(1, 1, 1, shape[1]), y=x2)
x4 = mb.mul(x=x3, y=x1)
x5 = mb.mul(x=x, y=x3)
x4 = mb.sub(x=np.random.rand(1, 1, 1, shape[1]), y=x4)
x6 = mb.add(x=x4, y=x5)
y = mb.transpose(x=x6, perm=[0, 3, 1, 2])
return y
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "common::fuse_layernorm_or_instancenorm"
)
assert get_op_types_in_program(prev_prog) == [
"transpose",
"reduce_mean",
"sub",
"square",
"reduce_mean",
"add",
"rsqrt",
"mul",
"mul",
"mul",
"sub",
"add",
"transpose",
]
assert get_op_types_in_program(prog) == [
"transpose",
"transpose",
"instance_norm",
"transpose",
"transpose",
]
assert_model_is_valid(
prog, {"x": shape}, expected_output_shapes={block.outputs[0].name: shape},
)
# reduce transpose pass should remove extra ones
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "common::reduce_transposes"
)
assert get_op_types_in_program(prog) == ["instance_norm"]
assert_model_is_valid(
prog, {"x": shape}, expected_output_shapes={block.outputs[0].name: shape},
)
def test_instance_norm_pattern_2(self):
"""
Detect instance norm pattern 2 and fusion.
|----> sub0 ----| const (0.5)
| ^ | |
| | V V
x ---> mean0 square --> mean1 --> add_eps ---> pow const_gamma const_beta
| | | | |
| V V V V
|----> sub1 --------------------------------> real_div --> mul_gamma --> add_beta --> ...
"""
shape = (3, 5, 6, 7)
@mb.program(input_specs=[mb.TensorSpec(shape=shape)])
def prog(x):
mean0 = mb.reduce_mean(x=x, axes=[2, 3], keep_dims=True)
sub0 = mb.sub(x=x, y=mean0)
sub1 = mb.sub(x=x, y=mean0)
square = mb.square(x=sub0)
mean1 = mb.reduce_mean(x=square, axes=[2, 3], keep_dims=True)
add_eps = mb.add(x=mean1, y=1e-5) # epsilon
pow = mb.pow(x=add_eps, y=0.5)
div = mb.real_div(x=sub1, y=pow)
mul_gamma = mb.mul(x=np.random.rand(1, shape[1], 1, 1), y=div) #
add_beta = mb.add(x=np.random.rand(1, shape[1], 1, 1), y=mul_gamma)
return add_beta
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "common::fuse_layernorm_or_instancenorm"
)
assert get_op_types_in_program(prev_prog) == [
"reduce_mean",
"sub",
"sub",
"square",
"reduce_mean",
"add",
"pow",
"real_div",
"mul",
"add",
]
assert get_op_types_in_program(prog) == ["instance_norm"]
assert_model_is_valid(
prog, {"x": shape}, expected_output_shapes={block.outputs[0].name: shape}
)
def test_instance_norm_pattern_3(self):
"""
Detect and fuse instance norm pattern 3 (pattern in TensorFlow-Addons).
|-------------------------------------------------|
| |
| V
x --> mean square --> mean1 --> add_eps --> rsqrt --> mul2 --> mul_sub
| | ^ | |
| V | | |
| --> sub -----| | |
| V V
|--------------------------------------------> mul1 -------------> add --> ...
"""
shape = (3, 5, 6, 7)
@mb.program(input_specs=[mb.TensorSpec(shape=shape)])
def prog(x):
mean0 = mb.reduce_mean(x=x, axes=[2, 3], keep_dims=True)
sub = mb.sub(x=x, y=mean0)
square = mb.square(x=sub)
mean1 = mb.reduce_mean(x=square, axes=[2, 3], keep_dims=True)
add_eps = mb.add(x=mean1, y=1e-5) # epsilon
rsqrt = mb.rsqrt(x=add_eps)
mul1 = mb.mul(x=rsqrt, y=x)
mul2 = mb.mul(x=mean0, y=rsqrt)
mul_sub = mb.mul(x=mul2, y=-1)
add = mb.add(x=mul1, y=mul_sub)
return add
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "common::fuse_layernorm_or_instancenorm"
)
assert get_op_types_in_program(prev_prog) == [
"reduce_mean",
"sub",
"square",
"reduce_mean",
"add",
"rsqrt",
"mul",
"mul",
"mul",
"add",
]
assert get_op_types_in_program(prog) == ["instance_norm"]
assert_model_is_valid(
prog, {"x": shape}, expected_output_shapes={block.outputs[0].name: shape}
)
def test_instance_norm_pattern_4(self):
"""
Detect and fuse instance norm pattern 4.
|-----------|
| V
|------> mul_square1 -----> sum1 -----> mul_mean1
| |
| V
x --> sum --> mul_mean ==> mul_square --> sub_variance --> add_eps --> rsqrt
| | |
| | V
| | mul_gamma
| | |
| | |----------------|
| | | V
| |--------------------------------------------+-------------> mul2
| V |
|----------------------------------------------------------> mul1 |
| V
| sub_beta --> add --> [...]
| ^
|---------------------------|
"""
shape = (3, 5, 6, 7)
@mb.program(input_specs=[mb.TensorSpec(shape=shape)])
def prog(x):
mul_square1 = mb.mul(x=x, y=x)
sum = mb.reduce_sum(x=x, axes=[2, 3], keep_dims=True)
mul_mean = mb.mul(x=sum, y=3.3333334e-05) # dummy value here
mul_square = mb.mul(x=mul_mean, y=mul_mean)
sum1 = mb.reduce_sum(x=mul_square1, axes=[2, 3], keep_dims=True)
mul_mean1 = mb.mul(x=sum1, y=8.333333e-06) # dummy value here
sub_variance = mb.sub(x=mul_mean1, y=mul_square)
add_eps = mb.add(x=sub_variance, y=1e-5) # epsilon
rsqrt = mb.rsqrt(x=add_eps)
mul_gamma = mb.mul(x=rsqrt, y=np.random.rand(1, shape[1], 1, 1))
mul1 = mb.mul(x=mul_gamma, y=x)
mul2 = mb.mul(x=mul_mean, y=mul_gamma)
sub_beta = mb.sub(x=np.random.rand(1, shape[1], 1, 1), y=mul2)
add = mb.add(x=mul1, y=sub_beta)
return add
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "common::fuse_layernorm_or_instancenorm"
)
assert get_op_types_in_program(prev_prog) == [
"mul",
"reduce_sum",
"mul",
"mul",
"reduce_sum",
"mul",
"sub",
"add",
"rsqrt",
"mul",
"mul",
"mul",
"sub",
"add",
]
assert get_op_types_in_program(prog) == ["instance_norm"]
assert_model_is_valid(
prog, {"x": shape}, expected_output_shapes={block.outputs[0].name: shape}
)
|
apple/coremltools
|
coremltools/converters/mil/mil/passes/test_layernorm_instancenorm_fusion.py
|
Python
|
bsd-3-clause
| 15,619 | 0.002753 |
#! /usr/bin/env python3
#############################################################
# Title: Python Debug Class #
# Description: Wrapper around Debugging and Logging for any #
# python class #
# Version: #
# * Version 1.00 03/28/2016 RC #
# * Version 1.10 12/16/2016 RC #
# * Version 1.11 07/06/2018 RC #
# #
# Author: Richard Cintorino (c) Richard Cintorino 2016 #
#############################################################
from datetime import datetime
class pyDebugger:
#Debug Function
def Log(self, sString, endd="\n",PrintName=True, DebugLevel="ALL", PrintTime=True):
sCN = ""
if DebugLevel in self.__DebugLevel or "ALL" in self.__DebugLevel:
if PrintTime == True:
sCN += datetime.now().strftime("%Y.%m.%d %H:%M:%S") + " "
if PrintName == True:
if self.__PrintDebugLevel == True:
sCN += "[" + DebugLevel + "] "
sCN += self.ClassName + ":"
if self.__Debug == True:
print(sCN + sString,end=endd)
if self.__LogToFile == True:
try:
with open("/var/log/" + self.ClassName + ".log", "a+") as logFile:
logFile.write(str(datetime.now()) + " " + sCN + sString+endd)
logFile.close()
except Exception as e:
print(self.ClassName + "_Logging Error: " + str(e))
def SetDebugLevel(self,DebugLevel):
if "," in DebugLevel:
self.__DebugLevel = DebugLevel.split(",")
else:
self.__DebugLevel = DebugLevel
def __init__(self,otherSelf, Debug, LogToFile, DebugLevel="ALL,NONE", PrintDebugLevel=True):
self.SetDebugLevel(DebugLevel)
self.__PrintDebugLevel = PrintDebugLevel
self.__Debug = Debug
self.__LogToFile = LogToFile
self.ClassName = otherSelf.__class__.__name__
self.Log("Starting Debugger, Debug="+ str(Debug) + " LogToFile=" + str(LogToFile))
|
Got-iT-Services-Inc/pyDebugger
|
Debug.py
|
Python
|
gpl-3.0
| 2,272 | 0.007482 |
# -*- coding: utf-8 -*-
"""The top-level package for ``django-mysqlpool``."""
# These imports make 2 act like 3, making it easier on us to switch to PyPy or
# some other VM if we need to for performance reasons.
from __future__ import (absolute_import, print_function, unicode_literals,
division)
# Make ``Foo()`` work the same in Python 2 as it does in Python 3.
__metaclass__ = type
import os
from django.conf import settings
from django.db.backends.mysql import base
from django.core.exceptions import ImproperlyConfigured
try:
import sqlalchemy.pool as pool
except ImportError as e:
raise ImproperlyConfigured("Error loading SQLAlchemy module: %s" % e)
# Global variable to hold the actual connection pool.
MYSQLPOOL = None
# Default pool type (QueuePool, SingletonThreadPool, AssertionPool, NullPool,
# StaticPool).
DEFAULT_BACKEND = 'QueuePool'
# Needs to be less than MySQL connection timeout (server setting). The default
# is 120, so default to 119.
DEFAULT_POOL_TIMEOUT = 119
def isiterable(value):
"""Determine whether ``value`` is iterable."""
try:
iter(value)
return True
except TypeError:
return False
class OldDatabaseProxy():
"""Saves a reference to the old connect function.
Proxies calls to its own connect() method to the old function.
"""
def __init__(self, old_connect):
"""Store ``old_connect`` to be used whenever we connect."""
self.old_connect = old_connect
def connect(self, **kwargs):
"""Delegate to the old ``connect``."""
# Bounce the call to the old function.
return self.old_connect(**kwargs)
class HashableDict(dict):
"""A dictionary that is hashable.
This is not generally useful, but created specifically to hold the ``conv``
parameter that needs to be passed to MySQLdb.
"""
def __hash__(self):
"""Calculate the hash of this ``dict``.
The hash is determined by converting to a sorted tuple of key-value
pairs and hashing that.
"""
items = [(n, tuple(v)) for n, v in self.items() if isiterable(v)]
return hash(tuple(items))
# Define this here so Django can import it.
DatabaseWrapper = base.DatabaseWrapper
# Wrap the old connect() function so our pool can call it.
OldDatabase = OldDatabaseProxy(base.Database.connect)
def get_pool():
"""Create one and only one pool using the configured settings."""
global MYSQLPOOL
if MYSQLPOOL is None:
backend_name = getattr(settings, 'MYSQLPOOL_BACKEND', DEFAULT_BACKEND)
backend = getattr(pool, backend_name)
kwargs = getattr(settings, 'MYSQLPOOL_ARGUMENTS', {})
kwargs.setdefault('poolclass', backend)
kwargs.setdefault('recycle', DEFAULT_POOL_TIMEOUT)
MYSQLPOOL = pool.manage(OldDatabase, **kwargs)
setattr(MYSQLPOOL, '_pid', os.getpid())
if getattr(MYSQLPOOL, '_pid', None) != os.getpid():
pool.clear_managers()
return MYSQLPOOL
def connect(**kwargs):
"""Obtain a database connection from the connection pool."""
# SQLAlchemy serializes the parameters to keep unique connection
# parameter groups in their own pool. We need to store certain
# values in a manner that is compatible with their serialization.
conv = kwargs.pop('conv', None)
ssl = kwargs.pop('ssl', None)
if conv:
kwargs['conv'] = HashableDict(conv)
if ssl:
kwargs['ssl'] = HashableDict(ssl)
# Open the connection via the pool.
return get_pool().connect(**kwargs)
# Monkey-patch the regular mysql backend to use our hacked-up connect()
# function.
base.Database.connect = connect
|
smartfile/django-mysqlpool
|
django_mysqlpool/backends/mysqlpool/base.py
|
Python
|
mit
| 3,693 | 0 |
from datetime import datetime
from ... search import get_results, phone_hits, both_hits
from ... run_cli import Arguments
from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(16)
def unique_features(feature, data):
features = set()
for v in data.values():
try:
if isinstance(v[feature], str):
features.add(v[feature])
elif isinstance(v[feature], list):
for i in v:
features.add(v[feature])
except:
pass
return features
def parsetime(timestring):
return datetime.strptime(timestring, '%Y-%m-%dT%H:%M:%S').ctime()
def specific_term(args):
accumulator = lambda x: get_term(x, args)
query = args.query[0]
results = get_results(query, int(args.size[0]), True)
phone = unique_features("phone", results)
posttime = unique_features("posttime", results)
output = {
'phrase' : query,
'total' : len(phone),
'initial_date': parsetime(min(posttime)),
'final_date' : parsetime(max(posttime)),
}
output['results'] = dict(pool.map(accumulator, phone))
return output
def get_term(pid, args):
phone_res = phone_hits(pid, int(args.size[0]))
both_res = both_hits(args.query[0], pid)
date_phone = set()
for v in phone_res.values():
try:
date_phone.add(v["posttime"])
except:
pass
term = {
'results':{
'phone' : phone_res['total'],
'both' : both_res['total'],
},
'date': {
'initial': parsetime(min(date_phone)),
'final' : parsetime(max(date_phone)),
}
}
return pid, term
def run(node):
args = Arguments(node.get('text', 'bouncy'), node.get('size', 100))
return specific_term(args)
|
qadium-memex/linkalytics
|
linkalytics/factor_validator/coincidence/coincidence.py
|
Python
|
apache-2.0
| 1,870 | 0.01123 |
"""Implementations of authorization abstract base class managers."""
# pylint: disable=invalid-name
# Method names comply with OSID specification.
# pylint: disable=no-init
# Abstract classes do not define __init__.
# pylint: disable=too-few-public-methods
# Some interfaces are specified as 'markers' and include no methods.
# pylint: disable=too-many-public-methods
# Number of methods are defined in specification
# pylint: disable=too-many-ancestors
# Inheritance defined in specification
# pylint: disable=too-many-arguments
# Argument signature defined in specification.
# pylint: disable=duplicate-code
# All apparent duplicates have been inspected. They aren't.
import abc
class AuthorizationProfile:
"""The ``AuthorizationProfile`` describes the interoperability among authorization services."""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def supports_visible_federation(self):
"""Tests if federation is visible.
:return: ``true`` if visible federation is supported ``,`` ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_authorization(self):
"""Tests for the availability of an authorization service which is the basic service for checking authorizations.
:return: ``true`` if authorization is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_authorization_lookup(self):
"""Tests if an authorization lookup service is supported.
An authorization lookup service defines methods to access
authorizations.
:return: true if authorization lookup is supported, false otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_authorization_query(self):
"""Tests if an authorization query service is supported.
:return: ``true`` if authorization query is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_authorization_search(self):
"""Tests if an authorization search service is supported.
:return: ``true`` if authorization search is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_authorization_admin(self):
"""Tests if an authorization administrative service is supported.
:return: ``true`` if authorization admin is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_authorization_notification(self):
"""Tests if authorization notification is supported.
Messages may be sent when authorizations are created, modified,
or deleted.
:return: ``true`` if authorization notification is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_authorization_vault(self):
"""Tests if an authorization to vault lookup session is available.
:return: ``true`` if authorization vault lookup session is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_authorization_vault_assignment(self):
"""Tests if an authorization to vault assignment session is available.
:return: ``true`` if authorization vault assignment is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_authorization_smart_vault(self):
"""Tests if an authorization smart vaulting session is available.
:return: ``true`` if authorization smart vaulting is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_function_lookup(self):
"""Tests if a function lookup service is supported.
A function lookup service defines methods to access
authorization functions.
:return: ``true`` if function lookup is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_function_query(self):
"""Tests if a function query service is supported.
:return: ``true`` if function query is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_function_search(self):
"""Tests if a function search service is supported.
:return: ``true`` if function search is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_function_admin(self):
"""Tests if a function administrative service is supported.
:return: ``true`` if function admin is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_function_notification(self):
"""Tests if function notification is supported.
Messages may be sent when functions are created, modified, or
deleted.
:return: ``true`` if function notification is supported ``,`` ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_function_vault(self):
"""Tests if a function to vault lookup session is available.
:return: ``true`` if function vault lookup session is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_function_vault_assignment(self):
"""Tests if a function to vault assignment session is available.
:return: ``true`` if function vault assignment is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_function_smart_vault(self):
"""Tests if a function smart vaulting session is available.
:return: ``true`` if function smart vaulting is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_qualifier_lookup(self):
"""Tests if a qualifier lookup service is supported.
A function lookup service defines methods to access
authorization qualifiers.
:return: ``true`` if qualifier lookup is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_qualifier_query(self):
"""Tests if a qualifier query service is supported.
:return: ``true`` if qualifier query is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_qualifier_search(self):
"""Tests if a qualifier search service is supported.
:return: ``true`` if qualifier search is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_qualifier_admin(self):
"""Tests if a qualifier administrative service is supported.
:return: ``true`` if qualifier admin is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_qualifier_notification(self):
"""Tests if qualifier notification is supported.
Messages may be sent when qualifiers are created, modified, or
deleted.
:return: ``true`` if qualifier notification is supported ``,`` ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_qualifier_hierarchy(self):
"""Tests if a qualifier hierarchy traversal is supported.
:return: ``true`` if a qualifier hierarchy traversal is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_qualifier_hierarchy_design(self):
"""Tests if qualifier hierarchy design is supported.
:return: ``true`` if a qualifier hierarchy design is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_qualifier_vault(self):
"""Tests if a qualifier to vault lookup session is available.
:return: ``true`` if qualifier vault lookup session is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_qualifier_vault_assignment(self):
"""Tests if a qualifier to vault assignment session is available.
:return: ``true`` if qualifier vault assignment is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_qualifier_smart_vault(self):
"""Tests if a qualifier smart vaulting session is available.
:return: ``true`` if qualifier smart vault session is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_vault_lookup(self):
"""Tests if a vault lookup service is supported.
A vault lookup service defines methods to access authorization
vaults.
:return: ``true`` if function lookup is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_vault_query(self):
"""Tests if a vault query service is supported.
:return: ``true`` if vault query is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_vault_search(self):
"""Tests if a vault search service is supported.
:return: ``true`` if vault search is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_vault_admin(self):
"""Tests if a vault administrative service is supported.
:return: ``true`` if vault admin is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_vault_notification(self):
"""Tests if vault notification is supported.
Messages may be sent when vaults are created, modified, or
deleted.
:return: ``true`` if vault notification is supported ``,`` ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_vault_hierarchy(self):
"""Tests if a vault hierarchy traversal is supported.
:return: ``true`` if a vault hierarchy traversal is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_vault_hierarchy_design(self):
"""Tests if vault hierarchy design is supported.
:return: ``true`` if a function hierarchy design is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_authorization_batch(self):
"""Tests if an authorization batch service is supported.
:return: ``true`` if an authorization batch service design is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_authorization_rules(self):
"""Tests if an authorization rules service is supported.
:return: ``true`` if an authorization rules service design is supported, ``false`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def get_authorization_record_types(self):
"""Gets the supported ``Authorization`` record types.
:return: a list containing the supported authorization record types
:rtype: ``osid.type.TypeList``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.TypeList
authorization_record_types = property(fget=get_authorization_record_types)
@abc.abstractmethod
def supports_authorization_record_type(self, authorization_record_type):
"""Tests if the given authorization record type is supported.
:param authorization_record_type: a ``Type`` indicating an authorization record type
:type authorization_record_type: ``osid.type.Type``
:return: ``true`` if the given record Type is supported, ``false`` otherwise
:rtype: ``boolean``
:raise: ``NullArgument`` -- ``authorization_record_type`` is ``null``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def get_authorization_search_record_types(self):
"""Gets the supported ``Authorization`` search record types.
:return: a list containing the supported authorization search record types
:rtype: ``osid.type.TypeList``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.TypeList
authorization_search_record_types = property(fget=get_authorization_search_record_types)
@abc.abstractmethod
def supports_authorization_search_record_type(self, authorization_search_record_type):
"""Tests if the given authorization search record type is supported.
:param authorization_search_record_type: a ``Type`` indicating an authorization search record type
:type authorization_search_record_type: ``osid.type.Type``
:return: ``true`` if the given search record Type is supported, ``false`` otherwise
:rtype: ``boolean``
:raise: ``NullArgument`` -- ``authorization_search_record_type`` is ``null``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def get_function_record_types(self):
"""Gets the supported ``Function`` record types.
:return: a list containing the supported ``Function`` record types
:rtype: ``osid.type.TypeList``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.TypeList
function_record_types = property(fget=get_function_record_types)
@abc.abstractmethod
def supports_function_record_type(self, function_record_type):
"""Tests if the given ``Function`` record type is supported.
:param function_record_type: a ``Type`` indicating a ``Function`` record type
:type function_record_type: ``osid.type.Type``
:return: ``true`` if the given Type is supported, ``false`` otherwise
:rtype: ``boolean``
:raise: ``NullArgument`` -- ``function_record_type`` is ``null``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def get_function_search_record_types(self):
"""Gets the supported ``Function`` search record types.
:return: a list containing the supported ``Function`` search record types
:rtype: ``osid.type.TypeList``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.TypeList
function_search_record_types = property(fget=get_function_search_record_types)
@abc.abstractmethod
def supports_function_search_record_type(self, function_search_record_type):
"""Tests if the given ``Function`` search record type is supported.
:param function_search_record_type: a ``Type`` indicating a ``Function`` search record type
:type function_search_record_type: ``osid.type.Type``
:return: ``true`` if the given Type is supported, ``false`` otherwise
:rtype: ``boolean``
:raise: ``NullArgument`` -- ``function_search_record_type`` is ``null``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def get_qualifier_record_types(self):
"""Gets the supported ``Qualifier`` record types.
:return: a list containing the supported ``Qualifier`` record types
:rtype: ``osid.type.TypeList``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.TypeList
qualifier_record_types = property(fget=get_qualifier_record_types)
@abc.abstractmethod
def supports_qualifier_record_type(self, qualifier_record_type):
"""Tests if the given ``Qualifier`` record type is supported.
:param qualifier_record_type: a ``Type`` indicating a ``Qualifier`` record type
:type qualifier_record_type: ``osid.type.Type``
:return: ``true`` if the given Type is supported, ``false`` otherwise
:rtype: ``boolean``
:raise: ``NullArgument`` -- ``qualifier_record_type`` is ``null``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def get_qualifier_search_record_types(self):
"""Gets the supported ``Qualifier`` search record types.
:return: a list containing the supported ``Qualifier`` search record types
:rtype: ``osid.type.TypeList``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.TypeList
qualifier_search_record_types = property(fget=get_qualifier_search_record_types)
@abc.abstractmethod
def supports_qualifier_search_record_type(self, qualifier_search_record_type):
"""Tests if the given ``Qualifier`` search record type is supported.
:param qualifier_search_record_type: a ``Type`` indicating a ``Qualifier`` search record type
:type qualifier_search_record_type: ``osid.type.Type``
:return: ``true`` if the given Type is supported, ``false`` otherwise
:rtype: ``boolean``
:raise: ``NullArgument`` -- ``qualifier_search_record_type`` is ``null``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def get_vault_record_types(self):
"""Gets the supported ``Vault`` record types.
:return: a list containing the supported ``Vault`` record types
:rtype: ``osid.type.TypeList``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.TypeList
vault_record_types = property(fget=get_vault_record_types)
@abc.abstractmethod
def supports_vault_record_type(self, vault_record_type):
"""Tests if the given ``Vault`` record type is supported.
:param vault_record_type: a ``Type`` indicating a ``Vault`` type
:type vault_record_type: ``osid.type.Type``
:return: ``true`` if the given vault record ``Type`` is supported, ``false`` otherwise
:rtype: ``boolean``
:raise: ``NullArgument`` -- ``vault_record_type`` is ``null``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def get_vault_search_record_types(self):
"""Gets the supported vault search record types.
:return: a list containing the supported ``Vault`` search record types
:rtype: ``osid.type.TypeList``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.TypeList
vault_search_record_types = property(fget=get_vault_search_record_types)
@abc.abstractmethod
def supports_vault_search_record_type(self, vault_search_record_type):
"""Tests if the given vault search record type is supported.
:param vault_search_record_type: a ``Type`` indicating a ``Vault`` search record type
:type vault_search_record_type: ``osid.type.Type``
:return: ``true`` if the given search record ``Type`` is supported, ``false`` otherwise
:rtype: ``boolean``
:raise: ``NullArgument`` -- ``vault_search_record_type`` is ``null``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def get_authorization_condition_record_types(self):
"""Gets the supported ``AuthorizationCondition`` record types.
:return: a list containing the supported ``AuthorizationCondition`` record types
:rtype: ``osid.type.TypeList``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.TypeList
authorization_condition_record_types = property(fget=get_authorization_condition_record_types)
@abc.abstractmethod
def supports_authorization_condition_record_type(self, authorization_condition_record_type):
"""Tests if the given ``AuthorizationCondition`` record type is supported.
:param authorization_condition_record_type: a ``Type`` indicating an ``AuthorizationCondition`` record type
:type authorization_condition_record_type: ``osid.type.Type``
:return: ``true`` if the given authorization condition record ``Type`` is supported, ``false`` otherwise
:rtype: ``boolean``
:raise: ``NullArgument`` -- ``authorization_condition_record_type`` is ``null``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
class AuthorizationManager:
"""The authorization manager provides access to authorization sessions and provides interoperability tests for various aspects of this service.
The sessions included in this manager are:
* ``AuthorizationSession:`` a session to performs authorization
checks
* ``AuthorizationLookupSession:`` a session to look up
``Authorizations``
* ``AuthorizationQuerySession:`` a session to query
``Authorizations``
* ``AuthorizationSearchSession:`` a session to search
``Authorizations``
* ``AuthorizationAdminSession:`` a session to create, modify and
delete ``Authorizations``
* ``AuthorizationNotificationSession: a`` session to receive
messages pertaining to ``Authorization`` changes
* ``AuthorizationVaultSession:`` a session to look up
authorization to vault mappings
* ``AuthorizationVaultAssignmentSession:`` a session to manage
authorization to vault mappings
* ``AuthorizationSmartVaultSession:`` a session to manage smart
authorization vaults
* ``FunctionLookupSession:`` a session to look up ``Functions``
* ``FunctionQuerySession:`` a session to query ``Functions``
* ``FunctionSearchSession:`` a session to search ``Functions``
* ``FunctionAdminSession:`` a session to create, modify and delete
``Functions``
* ``FunctionNotificationSession: a`` session to receive messages
pertaining to ``Function`` changes
* ``FunctionVaultSession:`` a session for looking up function and
vault mappings
* ``FunctionVaultAssignmentSession:`` a session for managing
function and vault mappings
* ``FunctionSmartVaultSession:`` a session to manage dynamic
function vaults
* ``QualifierLookupSession:`` a session to look up ``Qualifiers``
* ``QualifierQuerySession:`` a session to query ``Qualifiers``
* ``QualifierSearchSession:`` a session to search ``Qualifiers``
* ``QualifierAdminSession:`` a session to create, modify and
delete ``Qualifiers``
* ``QualifierNotificationSession: a`` session to receive messages
pertaining to ``Qualifier`` changes
* ``QualifierHierarchySession:`` a session for traversing
qualifier hierarchies
* ``QualifierHierarchyDesignSession:`` a session for managing
qualifier hierarchies
* ``QualifierVaultSession:`` a session for looking up qualifier
and vault mappings
* ``QualifierVaultAssignmentSession:`` a session for managing
qualifier and vault mappings
* ``QualifierSmartVaultSession:`` a session to manage dynamic
qualifier vaults
* ``VaultLookupSession:`` a session to lookup vaults
* ``VaultQuerySession:`` a session to query Vaults
* ``VaultSearchSession`` : a session to search vaults
* ``VaultAdminSession`` : a session to create, modify and delete
vaults
* ``VaultNotificationSession`` : a session to receive messages
pertaining to ``Vault`` changes
* ``VaultHierarchySession`` : a session to traverse the ``Vault``
hierarchy
* ``VaultHierarchyDesignSession`` : a session to manage the
``Vault`` hierarchy
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def get_authorization_session(self):
"""Gets an ``AuthorizationSession`` which is responsible for performing authorization checks.
:return: an authorization session for this service
:rtype: ``osid.authorization.AuthorizationSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization()`` is ``true``.*
"""
return # osid.authorization.AuthorizationSession
authorization_session = property(fget=get_authorization_session)
@abc.abstractmethod
def get_authorization_session_for_vault(self, vault_id):
"""Gets an ``AuthorizationSession`` which is responsible for performing authorization checks for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: ``an _authorization_session``
:rtype: ``osid.authorization.AuthorizationSession``
:raise: ``NotFound`` -- ``vault_id``
:raise: ``NullArgument`` -- ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_authorization()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.AuthorizationSession
@abc.abstractmethod
def get_authorization_lookup_session(self):
"""Gets the ``OsidSession`` associated with the authorization lookup service.
:return: an ``AuthorizationLookupSession``
:rtype: ``osid.authorization.AuthorizationLookupSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_lookup()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_lookup()`` is ``true``.*
"""
return # osid.authorization.AuthorizationLookupSession
authorization_lookup_session = property(fget=get_authorization_lookup_session)
@abc.abstractmethod
def get_authorization_lookup_session_for_vault(self, vault_id):
"""Gets the ``OsidSession`` associated with the authorization lookup service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: ``an _authorization_lookup_session``
:rtype: ``osid.authorization.AuthorizationLookupSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_authorization_lookup()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_lookup()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.AuthorizationLookupSession
@abc.abstractmethod
def get_authorization_query_session(self):
"""Gets the ``OsidSession`` associated with the authorization query service.
:return: an ``AuthorizationQuerySession``
:rtype: ``osid.authorization.AuthorizationQuerySession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_query()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_query()`` is ``true``.*
"""
return # osid.authorization.AuthorizationQuerySession
authorization_query_session = property(fget=get_authorization_query_session)
@abc.abstractmethod
def get_authorization_query_session_for_vault(self, vault_id):
"""Gets the ``OsidSession`` associated with the authorization query service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: ``an _authorization_query_session``
:rtype: ``osid.authorization.AuthorizationQuerySession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_authorization_query()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_query()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.AuthorizationQuerySession
@abc.abstractmethod
def get_authorization_search_session(self):
"""Gets the ``OsidSession`` associated with the authorization search service.
:return: an ``AuthorizationSearchSession``
:rtype: ``osid.authorization.AuthorizationSearchSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_search()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_search()`` is ``true``.*
"""
return # osid.authorization.AuthorizationSearchSession
authorization_search_session = property(fget=get_authorization_search_session)
@abc.abstractmethod
def get_authorization_search_session_for_vault(self, vault_id):
"""Gets the ``OsidSession`` associated with the authorization search service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: ``an _authorization_search_session``
:rtype: ``osid.authorization.AuthorizationSearchSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_authorization_search()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_search()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.AuthorizationSearchSession
@abc.abstractmethod
def get_authorization_admin_session(self):
"""Gets the ``OsidSession`` associated with the authorization administration service.
:return: an ``AuthorizationAdminSession``
:rtype: ``osid.authorization.AuthorizationAdminSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_admin()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_admin()`` is ``true``.*
"""
return # osid.authorization.AuthorizationAdminSession
authorization_admin_session = property(fget=get_authorization_admin_session)
@abc.abstractmethod
def get_authorization_admin_session_for_vault(self, vault_id):
"""Gets the ``OsidSession`` associated with the authorization admin service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: ``an _authorization_admin_session``
:rtype: ``osid.authorization.AuthorizationAdminSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_authorization_admin()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_admin()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.AuthorizationAdminSession
@abc.abstractmethod
def get_authorization_notification_session(self, authorization_receiver):
"""Gets the notification session for notifications pertaining to authorization changes.
:param authorization_receiver: the authorization receiver
:type authorization_receiver: ``osid.authorization.AuthorizationReceiver``
:return: an ``AuthorizationNotificationSession``
:rtype: ``osid.authorization.AuthorizationNotificationSession``
:raise: ``NullArgument`` -- ``authorization_receiver`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_notification()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_notification()`` is ``true``.*
"""
return # osid.authorization.AuthorizationNotificationSession
@abc.abstractmethod
def get_authorization_notification_session_for_vault(self, authorization_receiver, vault_id):
"""Gets the ``OsidSession`` associated with the authorization notification service for the given vault.
:param authorization_receiver: the authorization receiver
:type authorization_receiver: ``osid.authorization.AuthorizationReceiver``
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: ``an _authorization_notification_session``
:rtype: ``osid.authorization.AuthorizationNotificationSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``authorization_receiver`` or ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_authorization_notification()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_notification()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.AuthorizationNotificationSession
@abc.abstractmethod
def get_authorization_vault_session(self):
"""Gets the session for retrieving authorization to vault mappings.
:return: an ``AuthorizationVaultSession``
:rtype: ``osid.authorization.AuthorizationVaultSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_vault()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_vault()`` is ``true``.*
"""
return # osid.authorization.AuthorizationVaultSession
authorization_vault_session = property(fget=get_authorization_vault_session)
@abc.abstractmethod
def get_authorization_vault_assignment_session(self):
"""Gets the session for assigning authorizations to vault mappings.
:return: a ``AuthorizationVaultAssignmentSession``
:rtype: ``osid.authorization.AuthorizationVaultAssignmentSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_vault_assignment()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_vault_assignment()`` is ``true``.*
"""
return # osid.authorization.AuthorizationVaultAssignmentSession
authorization_vault_assignment_session = property(fget=get_authorization_vault_assignment_session)
@abc.abstractmethod
def get_authorization_smart_vault_session(self, vault_id):
"""Gets the session for managing dynamic authorization vaults.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: a ``AuthorizationSmartVaultSession``
:rtype: ``osid.authorization.AuthorizationSmartVaultSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_smart_vault()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_smart_vault()`` is ``true``.*
"""
return # osid.authorization.AuthorizationSmartVaultSession
@abc.abstractmethod
def get_function_lookup_session(self):
"""Gets the ``OsidSession`` associated with the function lookup service.
:return: a ``FunctionLookupSession``
:rtype: ``osid.authorization.FunctionLookupSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_function_lookup()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_lookup()`` is ``true``.*
"""
return # osid.authorization.FunctionLookupSession
function_lookup_session = property(fget=get_function_lookup_session)
@abc.abstractmethod
def get_function_lookup_session_for_vault(self, vault_id):
"""Gets the ``OsidSession`` associated with the function lookup service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: ``a FunctionLookupSession``
:rtype: ``osid.authorization.FunctionLookupSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_function_lookup()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_lookup()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.FunctionLookupSession
@abc.abstractmethod
def get_function_query_session(self):
"""Gets the ``OsidSession`` associated with the function query service.
:return: a ``FunctionQuerySession``
:rtype: ``osid.authorization.FunctionQuerySession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_function_query()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_query()`` is ``true``.*
"""
return # osid.authorization.FunctionQuerySession
function_query_session = property(fget=get_function_query_session)
@abc.abstractmethod
def get_function_query_session_for_vault(self, vault_id):
"""Gets the ``OsidSession`` associated with the function query service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: a ``FunctionQuerySession``
:rtype: ``osid.authorization.FunctionQuerySession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_function_query()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_query()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.FunctionQuerySession
@abc.abstractmethod
def get_function_search_session(self):
"""Gets the ``OsidSession`` associated with the function search service.
:return: a ``FunctionSearchSession``
:rtype: ``osid.authorization.FunctionSearchSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_function_search()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_search()`` is ``true``.*
"""
return # osid.authorization.FunctionSearchSession
function_search_session = property(fget=get_function_search_session)
@abc.abstractmethod
def get_function_search_session_for_vault(self, vault_id):
"""Gets the ``OsidSession`` associated with the function search service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: a ``FunctionSearchSession``
:rtype: ``osid.authorization.FunctionSearchSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_function_search()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_search()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.FunctionSearchSession
@abc.abstractmethod
def get_function_admin_session(self):
"""Gets the ``OsidSession`` associated with the function administration service.
:return: a ``FunctionAdminSession``
:rtype: ``osid.authorization.FunctionAdminSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_function_admin()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_admin()`` is ``true``.*
"""
return # osid.authorization.FunctionAdminSession
function_admin_session = property(fget=get_function_admin_session)
@abc.abstractmethod
def get_function_admin_session_for_vault(self, vault_id):
"""Gets the ``OsidSession`` associated with the function admin service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: ``a FunctionAdminSession``
:rtype: ``osid.authorization.FunctionAdminSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_function_admin()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_admin()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.FunctionAdminSession
@abc.abstractmethod
def get_function_notification_session(self, function_receiver):
"""Gets the notification session for notifications pertaining to function changes.
:param function_receiver: the function receiver
:type function_receiver: ``osid.authorization.FunctionReceiver``
:return: a ``FunctionNotificationSession``
:rtype: ``osid.authorization.FunctionNotificationSession``
:raise: ``NullArgument`` -- ``function_receiver`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_function_notification()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_notification()`` is ``true``.*
"""
return # osid.authorization.FunctionNotificationSession
@abc.abstractmethod
def get_function_notification_session_for_vault(self, function_receiver, vault_id):
"""Gets the ``OsidSession`` associated with the function notification service for the given vault.
:param function_receiver: the function receiver
:type function_receiver: ``osid.authorization.FunctionReceiver``
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: ``a FunctionNotificationSession``
:rtype: ``osid.authorization.FunctionNotificationSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``function_receiver`` or ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_function_notification()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_notification()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.FunctionNotificationSession
@abc.abstractmethod
def get_function_vault_session(self):
"""Gets the session for retrieving function to vault mappings.
:return: a ``FunctionVaultSession``
:rtype: ``osid.authorization.FunctionVaultSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_function_vault()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_vault()`` is ``true``.*
"""
return # osid.authorization.FunctionVaultSession
function_vault_session = property(fget=get_function_vault_session)
@abc.abstractmethod
def get_function_vault_assignment_session(self):
"""Gets the session for assigning function to vault mappings.
:return: a ``FunctionVaultAssignmentSession``
:rtype: ``osid.authorization.FunctionVaultAssignmentSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_function_vault_assignment()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_vault_assignment()`` is ``true``.*
"""
return # osid.authorization.FunctionVaultAssignmentSession
function_vault_assignment_session = property(fget=get_function_vault_assignment_session)
@abc.abstractmethod
def get_function_smart_vault_session(self, vault_id):
"""Gets the session associated with the function smart vault for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: a ``FunctionSmartVaultSession``
:rtype: ``osid.authorization.FunctionSmartVaultSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_function_smart_vault()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_smart_vault()`` is ``true``.*
"""
return # osid.authorization.FunctionSmartVaultSession
@abc.abstractmethod
def get_qualifier_lookup_session(self):
"""Gets the ``OsidSession`` associated with the qualifier lookup service.
:return: a ``QualifierLookupSession``
:rtype: ``osid.authorization.QualifierLookupSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_lookup()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_lookup()`` is ``true``.*
"""
return # osid.authorization.QualifierLookupSession
qualifier_lookup_session = property(fget=get_qualifier_lookup_session)
@abc.abstractmethod
def get_qualifier_lookup_session_for_vault(self, vault_id):
"""Gets the ``OsidSession`` associated with the qualifier lookup service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: a ``QualifierLookupSession``
:rtype: ``osid.authorization.QualifierLookupSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_qualifier_lookup()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_lookup()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.QualifierLookupSession
@abc.abstractmethod
def get_qualifier_query_session(self):
"""Gets the ``OsidSession`` associated with the qualifier query service.
:return: a ``QualifierQuerySession``
:rtype: ``osid.authorization.QualifierQuerySession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_query()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_query()`` is ``true``.*
"""
return # osid.authorization.QualifierQuerySession
qualifier_query_session = property(fget=get_qualifier_query_session)
@abc.abstractmethod
def get_qualifier_query_session_for_vault(self, vault_id):
"""Gets the ``OsidSession`` associated with the qualifier query service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: a ``QualifierQuerySession``
:rtype: ``osid.authorization.QualifierQuerySession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_qualifier_query()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_query()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.QualifierQuerySession
@abc.abstractmethod
def get_qualifier_search_session(self):
"""Gets the ``OsidSession`` associated with the qualifier search service.
:return: a ``QualifierSearchSession``
:rtype: ``osid.authorization.QualifierSearchSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_search()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_search()`` is ``true``.*
"""
return # osid.authorization.QualifierSearchSession
qualifier_search_session = property(fget=get_qualifier_search_session)
@abc.abstractmethod
def get_qualifier_search_session_for_vault(self, vault_id):
"""Gets the ``OsidSession`` associated with the qualifier search service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: a ``QualifierSearchSession``
:rtype: ``osid.authorization.QualifierSearchSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_qualifier_search()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_search()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.QualifierSearchSession
@abc.abstractmethod
def get_qualifier_admin_session(self):
"""Gets the ``OsidSession`` associated with the qualifier administration service.
:return: a ``QualifierAdminSession``
:rtype: ``osid.authorization.QualifierAdminSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_admin()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_admin()`` is ``true``.*
"""
return # osid.authorization.QualifierAdminSession
qualifier_admin_session = property(fget=get_qualifier_admin_session)
@abc.abstractmethod
def get_qualifier_admin_session_for_vault(self, vault_id):
"""Gets the ``OsidSession`` associated with the qualifier admin service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: a ``QualifierAdminSession``
:rtype: ``osid.authorization.QualifierAdminSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_qualifier_admin()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_admin()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.QualifierAdminSession
@abc.abstractmethod
def get_qualifier_notification_session(self, qualifier_receiver):
"""Gets the notification session for notifications pertaining to qualifier changes.
:param qualifier_receiver: the qualifier receiver
:type qualifier_receiver: ``osid.authorization.QualifierReceiver``
:return: a ``QualifierNotificationSession``
:rtype: ``osid.authorization.QualifierNotificationSession``
:raise: ``NullArgument`` -- ``qualifier_receiver`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_notification()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_notification()`` is ``true``.*
"""
return # osid.authorization.QualifierNotificationSession
@abc.abstractmethod
def get_qualifier_notification_session_for_vault(self, qualifier_receiver, vault_id):
"""Gets the ``OsidSession`` associated with the qualifier notification service for the given vault.
:param qualifier_receiver: the qualifier receiver
:type qualifier_receiver: ``osid.authorization.QualifierReceiver``
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: a ``QualifierNotificationSession``
:rtype: ``osid.authorization.QualifierNotificationSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``qualifier_receiver`` or ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_qualifier_notification()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_notification()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.QualifierNotificationSession
@abc.abstractmethod
def get_qualifier_hierarchy_session(self, qualifier_hierarchy_id):
"""Gets the ``OsidSession`` associated with the qualifier hierarchy traversal service.
The authorization service uses distinct hierarchies that can be
managed through a Hierarchy OSID.
:param qualifier_hierarchy_id: the ``Id`` of a qualifier hierarchy
:type qualifier_hierarchy_id: ``osid.id.Id``
:return: a ``QualifierHierarchySession``
:rtype: ``osid.authorization.QualifierHierarchySession``
:raise: ``NotFound`` -- ``qualifier_hierarchy_id`` not found
:raise: ``NullArgument`` -- ``qualifier_hierarchy_id`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_hierarchy()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_hierarchy()`` is ``true``.*
"""
return # osid.authorization.QualifierHierarchySession
@abc.abstractmethod
def get_qualifier_hierarchy_design_session(self, qualifier_hierarchy_id):
"""Gets the ``OsidSession`` associated with the qualifier hierarchy design service.
:param qualifier_hierarchy_id: the ``Id`` of a qualifier hierarchy
:type qualifier_hierarchy_id: ``osid.id.Id``
:return: a ``QualifierHierarchyDesignSession``
:rtype: ``osid.authorization.QualifierHierarchyDesignSession``
:raise: ``NotFound`` -- ``qualifier_hierarchy_id`` not found
:raise: ``NullArgument`` -- ``qualifier_hierarchy_id`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_hierarchy_design()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_hierarchy_design()`` is ``true``.*
"""
return # osid.authorization.QualifierHierarchyDesignSession
@abc.abstractmethod
def get_qualifier_vault_session(self):
"""Gets the session for retrieving qualifier to vault mappings.
:return: a ``QualifierVaultSession``
:rtype: ``osid.authorization.QualifierVaultSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_vault()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_vault()`` is ``true``.*
"""
return # osid.authorization.QualifierVaultSession
qualifier_vault_session = property(fget=get_qualifier_vault_session)
@abc.abstractmethod
def get_qualifier_vault_assignment_session(self):
"""Gets the session for assigning qualifier to vault mappings.
:return: a ``QualifierVaultAssignmentSession``
:rtype: ``osid.authorization.QualifierVaultSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_vault_assignment()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_vault_assignment()`` is ``true``.*
"""
return # osid.authorization.QualifierVaultSession
qualifier_vault_assignment_session = property(fget=get_qualifier_vault_assignment_session)
@abc.abstractmethod
def get_qualifier_smart_vault_session(self, vault_id):
"""Gets the session associated with the qualifier smart vault for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:return: a ``QualifierSmartVaultSession``
:rtype: ``osid.authorization.QualifierSmartVaultSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_smart_vault()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_smart_vault()`` is ``true``.*
"""
return # osid.authorization.QualifierSmartVaultSession
@abc.abstractmethod
def get_vault_lookup_session(self):
"""Gets the OsidSession associated with the vault lookup service.
:return: a ``VaultLookupSession``
:rtype: ``osid.authorization.VaultLookupSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_vault_lookup() is false``
*compliance: optional -- This method must be implemented if
``supports_vault_lookup()`` is true.*
"""
return # osid.authorization.VaultLookupSession
vault_lookup_session = property(fget=get_vault_lookup_session)
@abc.abstractmethod
def get_vault_query_session(self):
"""Gets the OsidSession associated with the vault query service.
:return: a ``VaultQuerySession``
:rtype: ``osid.authorization.VaultQuerySession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_vault_query() is false``
*compliance: optional -- This method must be implemented if
``supports_vault_query()`` is true.*
"""
return # osid.authorization.VaultQuerySession
vault_query_session = property(fget=get_vault_query_session)
@abc.abstractmethod
def get_vault_search_session(self):
"""Gets the OsidSession associated with the vault search service.
:return: a ``VaultSearchSession``
:rtype: ``osid.authorization.VaultSearchSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_vault_search() is false``
*compliance: optional -- This method must be implemented if
``supports_vault_search()`` is true.*
"""
return # osid.authorization.VaultSearchSession
vault_search_session = property(fget=get_vault_search_session)
@abc.abstractmethod
def get_vault_admin_session(self):
"""Gets the OsidSession associated with the vault administration service.
:return: a ``VaultAdminSession``
:rtype: ``osid.authorization.VaultAdminSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_vault_admin() is false``
*compliance: optional -- This method must be implemented if
``supports_vault_admin()`` is true.*
"""
return # osid.authorization.VaultAdminSession
vault_admin_session = property(fget=get_vault_admin_session)
@abc.abstractmethod
def get_vault_notification_session(self, vaultreceiver):
"""Gets the notification session for notifications pertaining to vault service changes.
:param vaultreceiver: the vault receiver
:type vaultreceiver: ``osid.authorization.VaultReceiver``
:return: a ``VaultNotificationSession``
:rtype: ``osid.authorization.VaultNotificationSession``
:raise: ``NullArgument`` -- ``vault_receiver`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_vault_notification() is false``
*compliance: optional -- This method must be implemented if
``supports_vault_notification()`` is true.*
"""
return # osid.authorization.VaultNotificationSession
@abc.abstractmethod
def get_vault_hierarchy_session(self):
"""Gets the session traversing vault hierarchies.
:return: a ``VaultHierarchySession``
:rtype: ``osid.authorization.VaultHierarchySession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_vault_hierarchy() is false``
*compliance: optional -- This method must be implemented if
``supports_vault_hierarchy()`` is true.*
"""
return # osid.authorization.VaultHierarchySession
vault_hierarchy_session = property(fget=get_vault_hierarchy_session)
@abc.abstractmethod
def get_vault_hierarchy_design_session(self):
"""Gets the session designing vault hierarchies.
:return: a ``VaultHierarchyDesignSession``
:rtype: ``osid.authorization.VaultHierarchyDesignSession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_vault_hierarchy_design() is false``
*compliance: optional -- This method must be implemented if
``supports_vault_hierarchy_design()`` is true.*
"""
return # osid.authorization.VaultHierarchyDesignSession
vault_hierarchy_design_session = property(fget=get_vault_hierarchy_design_session)
@abc.abstractmethod
def get_authorization_batch_manager(self):
"""Gets an ``AuthorizationBatchManager``.
:return: an ``AuthorizationBatchManager``
:rtype: ``osid.authorization.batch.AuthorizationBatchManager``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_batch() is false``
*compliance: optional -- This method must be implemented if
``supports_authorization_batch()`` is true.*
"""
return # osid.authorization.batch.AuthorizationBatchManager
authorization_batch_manager = property(fget=get_authorization_batch_manager)
@abc.abstractmethod
def get_authorization_rules_manager(self):
"""Gets an ``AuthorizationRulesManager``.
:return: an ``AuthorizationRulesManager``
:rtype: ``osid.authorization.rules.AuthorizationRulesManager``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_rules() is false``
*compliance: optional -- This method must be implemented if
``supports_authorization_rules()`` is true.*
"""
return # osid.authorization.rules.AuthorizationRulesManager
authorization_rules_manager = property(fget=get_authorization_rules_manager)
class AuthorizationProxyManager:
"""The authorization manager provides access to authorization sessions and provides interoperability tests for various aspects of this service.
Methods in this manager support the passing of a ``Proxy`` object.
The sessions included in this manager are:
* ``AuthorizationSession:`` a session to performs authorization
checks
* ``AuthorizationLookupSession:`` a session to look up
``Authorizations``
* ``AuthorizationSearchSession:`` a session to search
``Authorizations``
* ``AuthorizationAdminSession:`` a session to create, modify and
delete ``Authorizations``
* ``AuthorizationNotificationSession: a`` session to receive
messages pertaining to ``Authorization`` changes
* ``AuthorizationVaultSession:`` a session to look up
authorization to vault mappings
* ``AuthorizationVaultAssignmentSession:`` a session to manage
authorization to vault mappings
* ``AuthorizationSmartVaultSession:`` a session to manage smart
authorization vault
* ``FunctionLookupSession:`` a session to look up ``Functions``
* ``FunctionQuerySession:`` a session to query ``Functions``
* ``FunctionSearchSession:`` a session to search ``Functions``
* ``FunctionAdminSession:`` a session to create, modify and delete
``Functions``
* ``FunctionNotificationSession: a`` session to receive messages
pertaining to ``Function`` changes
* ``FunctionVaultSession:`` a session for looking up function and
vault mappings
* ``FunctionVaultAssignmentSession:`` a session for managing
function and vault mappings
* ``FunctionSmartVaultSession:`` a session to manage dynamic
function vaults
* ``QualifierLookupSession:`` a session to look up ``Qualifiers``
* ``QualifierQuerySession:`` a session to query ``Qualifiers``
* ``QualifierSearchSession:`` a session to search ``Qualifiers``
* ``QualifierAdminSession:`` a session to create, modify and
delete ``Qualifiers``
* ``QualifierNotificationSession: a`` session to receive messages
pertaining to ``Qualifier`` changes
* ``QualifierHierarchySession:`` a session for traversing
qualifier hierarchies
* ``QualifierHierarchyDesignSession:`` a session for managing
qualifier hierarchies
* ``QualifierVaultSession:`` a session for looking up qualifier
and vault mappings
* ``QualifierVaultAssignmentSession:`` a session for managing
qualifier and vault mappings
* ``QualifierSmartVaultSession:`` a session to manage dynamic
qualifier vaults
* ``VaultLookupSession:`` a session to lookup vaults
* ``VaultQuerySession:`` a session to query Vaults
* ``VaultSearchSession`` : a session to search vaults
* ``VaultAdminSession`` : a session to create, modify and delete
vaults
* ``VaultNotificationSession`` : a session to receive messages
pertaining to ``Vault`` changes
* ``VaultHierarchySession`` : a session to traverse the ``Vault``
hierarchy
* ``VaultHierarchyDesignSession`` : a session to manage the
``Vault`` hierarchy
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def get_authorization_session(self, proxy):
"""Gets an ``AuthorizationSession`` which is responsible for performing authorization checks.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an authorization session for this service
:rtype: ``osid.authorization.AuthorizationSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization()`` is ``true``.*
"""
return # osid.authorization.AuthorizationSession
@abc.abstractmethod
def get_authorization_session_for_vault(self, vault_id, proxy):
"""Gets an ``AuthorizationSession`` which is responsible for performing authorization checks for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: ``an _authorization_session``
:rtype: ``osid.authorization.AuthorizationSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_authorization()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.AuthorizationSession
@abc.abstractmethod
def get_authorization_lookup_session(self, proxy):
"""Gets the ``OsidSession`` associated with the authorization lookup service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``AuthorizationLookupSession``
:rtype: ``osid.authorization.AuthorizationLookupSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_lookup()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_lookup()`` is ``true``.*
"""
return # osid.authorization.AuthorizationLookupSession
@abc.abstractmethod
def get_authorization_lookup_session_for_vault(self, vault_id, proxy):
"""Gets the ``OsidSession`` associated with the authorization lookup service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: ``an _authorization_lookup_session``
:rtype: ``osid.authorization.AuthorizationLookupSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_authorization_lookup()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_lookup()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.AuthorizationLookupSession
@abc.abstractmethod
def get_authorization_query_session(self, proxy):
"""Gets the ``OsidSession`` associated with the authorization query service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``AuthorizationQuerySession``
:rtype: ``osid.authorization.AuthorizationQuerySession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_query()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_query()`` is ``true``.*
"""
return # osid.authorization.AuthorizationQuerySession
@abc.abstractmethod
def get_authorization_query_session_for_vault(self, vault_id, proxy):
"""Gets the ``OsidSession`` associated with the authorization query service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: ``an _authorization_query_session``
:rtype: ``osid.authorization.AuthorizationQuerySession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_authorization_query()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_query()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.AuthorizationQuerySession
@abc.abstractmethod
def get_authorization_search_session(self, proxy):
"""Gets the ``OsidSession`` associated with the authorization search service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``AuthorizationSearchSession``
:rtype: ``osid.authorization.AuthorizationSearchSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_search()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_search()`` is ``true``.*
"""
return # osid.authorization.AuthorizationSearchSession
@abc.abstractmethod
def get_authorization_search_session_for_vault(self, vault_id, proxy):
"""Gets the ``OsidSession`` associated with the authorization search service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: ``an _authorization_search_session``
:rtype: ``osid.authorization.AuthorizationSearchSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_authorization_search()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_search()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.AuthorizationSearchSession
@abc.abstractmethod
def get_authorization_admin_session(self, proxy):
"""Gets the ``OsidSession`` associated with the authorization administration service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``AuthorizationAdminSession``
:rtype: ``osid.authorization.AuthorizationAdminSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_admin()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_admin()`` is ``true``.*
"""
return # osid.authorization.AuthorizationAdminSession
@abc.abstractmethod
def get_authorization_admin_session_for_vault(self, vault_id, proxy):
"""Gets the ``OsidSession`` associated with the authorization admin service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: ``an _authorization_admin_session``
:rtype: ``osid.authorization.AuthorizationAdminSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_authorization_admin()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_admin()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.AuthorizationAdminSession
@abc.abstractmethod
def get_authorization_notification_session(self, authorization_receiver, proxy):
"""Gets the notification session for notifications pertaining to authorization changes.
:param authorization_receiver: the authorization receiver
:type authorization_receiver: ``osid.authorization.AuthorizationReceiver``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``AuthorizationNotificationSession``
:rtype: ``osid.authorization.AuthorizationNotificationSession``
:raise: ``NullArgument`` -- ``authorization_receiver`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_notification()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_notification()`` is ``true``.*
"""
return # osid.authorization.AuthorizationNotificationSession
@abc.abstractmethod
def get_authorization_notification_session_for_vault(self, authorization_receiver, vault_id, proxy):
"""Gets the ``OsidSession`` associated with the authorization notification service for the given vault.
:param authorization_receiver: the authorization receiver
:type authorization_receiver: ``osid.authorization.AuthorizationReceiver``
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: ``an _authorization_notification_session``
:rtype: ``osid.authorization.AuthorizationNotificationSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``authorization_receiver`` or ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_authorization_notification()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_notification()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.AuthorizationNotificationSession
@abc.abstractmethod
def get_authorization_vault_session(self, proxy):
"""Gets the session for retrieving authorization to vault mappings.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``AuthorizationVaultSession``
:rtype: ``osid.authorization.AuthorizationVaultSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_vault()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_vault()`` is ``true``.*
"""
return # osid.authorization.AuthorizationVaultSession
@abc.abstractmethod
def get_authorization_vault_assignment_session(self, proxy):
"""Gets the session for assigning authorization to vault mappings.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``AuthorizationVaultAssignmentSession``
:rtype: ``osid.authorization.AuthorizationVaultAssignmentSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_vault_assignment()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_vault_assignment()`` is ``true``.*
"""
return # osid.authorization.AuthorizationVaultAssignmentSession
@abc.abstractmethod
def get_authorization_smart_vault_session(self, vault_id, proxy):
"""Gets the session for managing dynamic authorization vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``AuthorizationSmartVaultSession``
:rtype: ``osid.authorization.AuthorizationSmartVaultSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_smart_vault()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_authorization_smart_vault()`` is ``true``.*
"""
return # osid.authorization.AuthorizationSmartVaultSession
@abc.abstractmethod
def get_function_lookup_session(self, proxy):
"""Gets the ``OsidSession`` associated with the function lookup service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``FunctionLookupSession``
:rtype: ``osid.authorization.FunctionLookupSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_function_lookup()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_lookup()`` is ``true``.*
"""
return # osid.authorization.FunctionLookupSession
@abc.abstractmethod
def get_function_lookup_session_for_vault(self, vault_id, proxy):
"""Gets the ``OsidSession`` associated with the function lookup service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: ``a FunctionLookupSession``
:rtype: ``osid.authorization.FunctionLookupSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_function_lookup()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_lookup()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.FunctionLookupSession
@abc.abstractmethod
def get_function_query_session(self, proxy):
"""Gets the ``OsidSession`` associated with the function query service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``FunctionQuerySession``
:rtype: ``osid.authorization.FunctionQuerySession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_function_query()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_query()`` is ``true``.*
"""
return # osid.authorization.FunctionQuerySession
@abc.abstractmethod
def get_function_query_session_for_vault(self, vault_id, proxy):
"""Gets the ``OsidSession`` associated with the function query service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``FunctionQuerySession``
:rtype: ``osid.authorization.FunctionQuerySession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_function_query()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_query()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.FunctionQuerySession
@abc.abstractmethod
def get_function_search_session(self, proxy):
"""Gets the ``OsidSession`` associated with the function search service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``FunctionSearchSession``
:rtype: ``osid.authorization.FunctionSearchSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_function_search()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_search()`` is ``true``.*
"""
return # osid.authorization.FunctionSearchSession
@abc.abstractmethod
def get_function_search_session_for_vault(self, vault_id, proxy):
"""Gets the ``OsidSession`` associated with the function search service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``FunctionSearchSession``
:rtype: ``osid.authorization.FunctionSearchSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_function_search()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_search()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.FunctionSearchSession
@abc.abstractmethod
def get_function_admin_session(self, proxy):
"""Gets the ``OsidSession`` associated with the function administration service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``FunctionAdminSession``
:rtype: ``osid.authorization.FunctionAdminSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_function_admin()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_admin()`` is ``true``.*
"""
return # osid.authorization.FunctionAdminSession
@abc.abstractmethod
def get_function_admin_session_for_vault(self, vault_id, proxy):
"""Gets the ``OsidSession`` associated with the function admin service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: ``a FunctionAdminSession``
:rtype: ``osid.authorization.FunctionAdminSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_function_admin()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_admin()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.FunctionAdminSession
@abc.abstractmethod
def get_function_notification_session(self, function_receiver, proxy):
"""Gets the notification session for notifications pertaining to function changes.
:param function_receiver: the function receiver
:type function_receiver: ``osid.authorization.FunctionReceiver``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``FunctionNotificationSession``
:rtype: ``osid.authorization.FunctionNotificationSession``
:raise: ``NullArgument`` -- ``function_receiver`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_function_notification()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_notification()`` is ``true``.*
"""
return # osid.authorization.FunctionNotificationSession
@abc.abstractmethod
def get_function_notification_session_for_vault(self, function_receiver, vault_id, proxy):
"""Gets the ``OsidSession`` associated with the function notification service for the given vault.
:param function_receiver: the function receiver
:type function_receiver: ``osid.authorization.FunctionReceiver``
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: ``a FunctionNotificationSession``
:rtype: ``osid.authorization.FunctionNotificationSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``function_receiver`` or ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_function_notification()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_notification()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.FunctionNotificationSession
@abc.abstractmethod
def get_function_vault_session(self, proxy):
"""Gets the session for retrieving function to vault mappings.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``FunctionVaultSession``
:rtype: ``osid.authorization.FunctionVaultSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_function_vault()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_vault()`` is ``true``.*
"""
return # osid.authorization.FunctionVaultSession
@abc.abstractmethod
def get_function_vault_assignment_session(self, proxy):
"""Gets the session for assigning function to vault mappings.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``FunctionVaultAssignmentSession``
:rtype: ``osid.authorization.FunctionVaultAssignmentSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_function_vault_assignment()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_vault_assignment()`` is ``true``.*
"""
return # osid.authorization.FunctionVaultAssignmentSession
@abc.abstractmethod
def get_function_smart_vault_session(self, vault_id, proxy):
"""Gets the session for managing dynamic function vaults for the given vault.
:param vault_id: the ``Id`` of a vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: ``vault_id`` not found
:rtype: ``osid.authorization.FunctionSmartVaultSession``
:raise: ``NotFound`` -- ``vault_id`` or ``proxy`` is ``null``
:raise: ``NullArgument`` -- ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_function_smart_vault()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_function_smart_vault()`` is ``true``.*
"""
return # osid.authorization.FunctionSmartVaultSession
@abc.abstractmethod
def get_qualifier_lookup_session(self, proxy):
"""Gets the ``OsidSession`` associated with the qualifier lookup service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``QualifierLookupSession``
:rtype: ``osid.authorization.QualifierLookupSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_lookup()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_lookup()`` is ``true``.*
"""
return # osid.authorization.QualifierLookupSession
@abc.abstractmethod
def get_qualifier_lookup_session_for_vault(self, vault_id, proxy):
"""Gets the ``OsidSession`` associated with the qualifier lookup service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``QualifierLookupSession``
:rtype: ``osid.authorization.QualifierLookupSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_qualifier_lookup()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_lookup()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.QualifierLookupSession
@abc.abstractmethod
def get_qualifier_query_session(self, proxy):
"""Gets the ``OsidSession`` associated with the qualifier query service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``QualifierQuerySession``
:rtype: ``osid.authorization.QualifierQuerySession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_query()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_search()`` is ``true``.*
"""
return # osid.authorization.QualifierQuerySession
@abc.abstractmethod
def get_qualifier_query_session_for_vault(self, vault_id, proxy):
"""Gets the ``OsidSession`` associated with the qualifier query service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``QualifierQuerySession``
:rtype: ``osid.authorization.QualifierQuerySession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_qualifier_query()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_query()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.QualifierQuerySession
@abc.abstractmethod
def get_qualifier_search_session(self, proxy):
"""Gets the ``OsidSession`` associated with the qualifier search service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``QualifierSearchSession``
:rtype: ``osid.authorization.QualifierSearchSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_search()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_search()`` is ``true``.*
"""
return # osid.authorization.QualifierSearchSession
@abc.abstractmethod
def get_qualifier_search_session_for_vault(self, vault_id, proxy):
"""Gets the ``OsidSession`` associated with the qualifier search service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``QualifierSearchSession``
:rtype: ``osid.authorization.QualifierSearchSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_qualifier_search()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_search()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.QualifierSearchSession
@abc.abstractmethod
def get_qualifier_admin_session(self, proxy):
"""Gets the ``OsidSession`` associated with the qualifier administration service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``QualifierAdminSession``
:rtype: ``osid.authorization.QualifierAdminSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_admin()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_admin()`` is ``true``.*
"""
return # osid.authorization.QualifierAdminSession
@abc.abstractmethod
def get_qualifier_admin_session_for_vault(self, vault_id, proxy):
"""Gets the ``OsidSession`` associated with the qualifier admin service for the given vault.
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``QualifierAdminSession``
:rtype: ``osid.authorization.QualifierAdminSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_qualifier_admin()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_admin()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.QualifierAdminSession
@abc.abstractmethod
def get_qualifier_notification_session(self, qualifier_receiver, proxy):
"""Gets the notification session for notifications pertaining to qualifier changes.
:param qualifier_receiver: the qualifier receiver
:type qualifier_receiver: ``osid.authorization.QualifierReceiver``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``QualifierNotificationSession``
:rtype: ``osid.authorization.QualifierNotificationSession``
:raise: ``NullArgument`` -- ``qualifier_receiver`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_notification()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_notification()`` is ``true``.*
"""
return # osid.authorization.QualifierNotificationSession
@abc.abstractmethod
def get_qualifier_notification_session_for_vault(self, qualifier_receiver, vault_id, proxy):
"""Gets the ``OsidSession`` associated with the qualifier notification service for the given vault.
:param qualifier_receiver: the qualifier receiver
:type qualifier_receiver: ``osid.authorization.QualifierReceiver``
:param vault_id: the ``Id`` of the vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``QualifierNotificationSession``
:rtype: ``osid.authorization.QualifierNotificationSession``
:raise: ``NotFound`` -- ``vault_id`` not found
:raise: ``NullArgument`` -- ``qualifier_receiver`` or ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- ``unable to complete request``
:raise: ``Unimplemented`` -- ``supports_qualifier_notification()`` or ``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_notification()`` and
``supports_visible_federation()`` are ``true``.*
"""
return # osid.authorization.QualifierNotificationSession
@abc.abstractmethod
def get_qualifier_hierarchy_session(self, qualifier_hierarchy_id, proxy):
"""Gets the ``OsidSession`` associated with the qualifier hierarchy traversal service.
The authorization service uses distinct hierarchies that can be
managed through a Hierarchy OSID.
:param qualifier_hierarchy_id: the ``Id`` of a qualifier hierarchy
:type qualifier_hierarchy_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``QualifierHierarchySession``
:rtype: ``osid.authorization.QualifierHierarchySession``
:raise: ``NotFound`` -- ``qualifier_hierarchy_id`` not found
:raise: ``NullArgument`` -- ``qualifier_hierarchy_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_hierarchy()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_hierarchy()`` is ``true``.*
"""
return # osid.authorization.QualifierHierarchySession
@abc.abstractmethod
def get_qualifier_hierarchy_design_session(self, qualifier_hierarchy_id, proxy):
"""Gets the ``OsidSession`` associated with the qualifier hierarchy design service.
:param qualifier_hierarchy_id: the ``Id`` of a qualifier hierarchy
:type qualifier_hierarchy_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``QualifierHierarchyDesignSession``
:rtype: ``osid.authorization.QualifierHierarchyDesignSession``
:raise: ``NotFound`` -- ``qualifier_hierarchy_id`` not found
:raise: ``NullArgument`` -- ``qualifier_hierarchy_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_hierarchy_design()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_hierarchy_design()`` is ``true``.*
"""
return # osid.authorization.QualifierHierarchyDesignSession
@abc.abstractmethod
def get_qualifier_vault_session(self, proxy):
"""Gets the session for retrieving qualifier to vault mappings.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``QualifierVaultSession``
:rtype: ``osid.authorization.QualifierVaultSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_vault()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_vault()`` is ``true``.*
"""
return # osid.authorization.QualifierVaultSession
@abc.abstractmethod
def get_qualifier_vault_assignment_session(self, proxy):
"""Gets the session for assigning qualifier to vault mappings.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``QualifierVaultAssignmentSession``
:rtype: ``osid.authorization.QualifierVaultSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_vault_assignment()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_vault_assignment()`` is ``true``.*
"""
return # osid.authorization.QualifierVaultSession
@abc.abstractmethod
def get_qualifier_smart_vault_session(self, vault_id, proxy):
"""Gets the session for managing dynamic qualifier vaults for the given vault.
:param vault_id: the ``Id`` of a vault
:type vault_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: ``vault_id`` not found
:rtype: ``osid.authorization.QualifierSmartVaultSession``
:raise: ``NotFound`` -- ``vault_id`` or ``proxy`` is ``null``
:raise: ``NullArgument`` -- ``vault_id`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_qualifier_smart_vault()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_qualifier_smart_vault()`` is ``true``.*
"""
return # osid.authorization.QualifierSmartVaultSession
@abc.abstractmethod
def get_vault_lookup_session(self, proxy):
"""Gets the OsidSession associated with the vault lookup service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``VaultLookupSession``
:rtype: ``osid.authorization.VaultLookupSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_vault_lookup() is false``
*compliance: optional -- This method must be implemented if
``supports_vault_lookup()`` is true.*
"""
return # osid.authorization.VaultLookupSession
@abc.abstractmethod
def get_vault_query_session(self, proxy):
"""Gets the OsidSession associated with the vault query service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``VaultQuerySession``
:rtype: ``osid.authorization.VaultQuerySession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_vault_query() is false``
*compliance: optional -- This method must be implemented if
``supports_vault_query()`` is true.*
"""
return # osid.authorization.VaultQuerySession
@abc.abstractmethod
def get_vault_search_session(self, proxy):
"""Gets the OsidSession associated with the vault search service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``VaultSearchSession``
:rtype: ``osid.authorization.VaultSearchSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_vault_search() is false``
*compliance: optional -- This method must be implemented if
``supports_vault_search()`` is true.*
"""
return # osid.authorization.VaultSearchSession
@abc.abstractmethod
def get_vault_admin_session(self, proxy):
"""Gets the OsidSession associated with the vault administration service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``VaultAdminSession``
:rtype: ``osid.authorization.VaultAdminSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_vault_admin() is false``
*compliance: optional -- This method must be implemented if
``supports_vault_admin()`` is true.*
"""
return # osid.authorization.VaultAdminSession
@abc.abstractmethod
def get_vault_notification_session(self, vault_receiver, proxy):
"""Gets the notification session for notifications pertaining to vault service changes.
:param vault_receiver: the vault receiver
:type vault_receiver: ``osid.authorization.VaultReceiver``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``VaultNotificationSession``
:rtype: ``osid.authorization.VaultNotificationSession``
:raise: ``NullArgument`` -- ``vault_receiver`` or ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_vault_notification() is false``
*compliance: optional -- This method must be implemented if
``supports_vault_notification()`` is true.*
"""
return # osid.authorization.VaultNotificationSession
@abc.abstractmethod
def get_vault_hierarchy_session(self, proxy):
"""Gets the session traversing vault hierarchies.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``VaultHierarchySession``
:rtype: ``osid.authorization.VaultHierarchySession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_vault_hierarchy() is false``
*compliance: optional -- This method must be implemented if
``supports_vault_hierarchy()`` is true.*
"""
return # osid.authorization.VaultHierarchySession
@abc.abstractmethod
def get_vault_hierarchy_design_session(self, proxy):
"""Gets the session designing vault hierarchies.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``VaultHierarchySession``
:rtype: ``osid.authorization.VaultHierarchyDesignSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_vault_hierarchy_design() is false``
*compliance: optional -- This method must be implemented if
``supports_vault_hierarchy_design()`` is true.*
"""
return # osid.authorization.VaultHierarchyDesignSession
@abc.abstractmethod
def get_authorization_batch_proxy_manager(self):
"""Gets an ``AuthorizationBatchProxyManager``.
:return: an ``AuthorizationBatchProxyManager``
:rtype: ``osid.authorization.batch.AuthorizationBatchProxyManager``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_batch() is false``
*compliance: optional -- This method must be implemented if
``supports_authorization_batch()`` is true.*
"""
return # osid.authorization.batch.AuthorizationBatchProxyManager
authorization_batch_proxy_manager = property(fget=get_authorization_batch_proxy_manager)
@abc.abstractmethod
def get_authorization_rules_proxy_manager(self):
"""Gets an ``AuthorizationRulesProxyManager``.
:return: an ``AuthorizationRulesProxyManager``
:rtype: ``osid.authorization.rules.AuthorizationRulesProxyManager``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``supports_authorization_rules() is false``
*compliance: optional -- This method must be implemented if
``supports_authorization_rules()`` is true.*
"""
return # osid.authorization.rules.AuthorizationRulesProxyManager
authorization_rules_proxy_manager = property(fget=get_authorization_rules_proxy_manager)
|
mitsei/dlkit
|
dlkit/abstract_osid/authorization/managers.py
|
Python
|
mit
| 119,516 | 0.002083 |
# -*- coding: utf-8 -*-
"""
Tests that the request came from a crawler or not.
"""
from __future__ import absolute_import
import ddt
from django.test import TestCase
from django.http import HttpRequest
from ..models import CrawlersConfig
@ddt.ddt
class CrawlersConfigTest(TestCase):
def setUp(self):
super(CrawlersConfigTest, self).setUp()
CrawlersConfig(known_user_agents='edX-downloader,crawler_foo', enabled=True).save()
@ddt.data(
"Mozilla/5.0 (Linux; Android 5.1; Nexus 5 Build/LMY47I; wv) AppleWebKit/537.36 (KHTML, like Gecko) "
"Version/4.0 Chrome/47.0.2526.100 Mobile Safari/537.36 edX/org.edx.mobile/2.0.0",
"Le Héros des Deux Mondes",
)
def test_req_user_agent_is_not_crawler(self, req_user_agent):
"""
verify that the request did not come from a crawler.
"""
fake_request = HttpRequest()
fake_request.META['HTTP_USER_AGENT'] = req_user_agent
self.assertFalse(CrawlersConfig.is_crawler(fake_request))
@ddt.data(
u"edX-downloader",
"crawler_foo".encode("utf-8")
)
def test_req_user_agent_is_crawler(self, req_user_agent):
"""
verify that the request came from a crawler.
"""
fake_request = HttpRequest()
fake_request.META['HTTP_USER_AGENT'] = req_user_agent
self.assertTrue(CrawlersConfig.is_crawler(fake_request))
|
ESOedX/edx-platform
|
openedx/core/djangoapps/crawlers/tests/test_models.py
|
Python
|
agpl-3.0
| 1,412 | 0.002126 |
# Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Handles database requests from other Sahara services."""
import copy
from sahara.db import base as db_base
from sahara.utils import configs
from sahara.utils import crypto
CLUSTER_DEFAULTS = {
"cluster_configs": {},
"status": "undefined",
"anti_affinity": [],
"status_description": "",
"info": {},
"rollback_info": {},
"sahara_info": {},
}
NODE_GROUP_DEFAULTS = {
"node_processes": [],
"node_configs": {},
"volumes_per_node": 0,
"volumes_size": 0,
"volumes_availability_zone": None,
"volume_mount_prefix": "/volumes/disk",
"volume_type": None,
"floating_ip_pool": None,
"security_groups": None,
"auto_security_group": False,
"availability_zone": None,
}
INSTANCE_DEFAULTS = {
"volumes": []
}
DATA_SOURCE_DEFAULTS = {
"credentials": {}
}
def _apply_defaults(values, defaults):
new_values = copy.deepcopy(defaults)
new_values.update(values)
return new_values
class ConductorManager(db_base.Base):
"""This class aimed to conduct things.
The methods in the base API for sahara-conductor are various proxy
operations that allows other services to get specific work done without
locally accessing the database.
Additionally it performs some template-to-object copying magic.
"""
def __init__(self):
super(ConductorManager, self).__init__()
# Common helpers
def _populate_node_groups(self, context, cluster):
node_groups = cluster.get('node_groups')
if not node_groups:
return []
populated_node_groups = []
for node_group in node_groups:
populated_node_group = self._populate_node_group(context,
node_group)
self._cleanup_node_group(populated_node_group)
populated_node_group["tenant_id"] = context.tenant_id
populated_node_groups.append(
populated_node_group)
return populated_node_groups
def _cleanup_node_group(self, node_group):
node_group.pop('id', None)
node_group.pop('created_at', None)
node_group.pop('updated_at', None)
def _populate_node_group(self, context, node_group):
node_group_merged = copy.deepcopy(NODE_GROUP_DEFAULTS)
ng_tmpl_id = node_group.get('node_group_template_id')
ng_tmpl = None
if ng_tmpl_id:
ng_tmpl = self.node_group_template_get(context, ng_tmpl_id)
self._cleanup_node_group(ng_tmpl)
node_group_merged.update(ng_tmpl)
node_group_merged.update(node_group)
if ng_tmpl:
node_group_merged['node_configs'] = configs.merge_configs(
ng_tmpl.get('node_configs'),
node_group.get('node_configs'))
return node_group_merged
# Cluster ops
def cluster_get(self, context, cluster):
"""Return the cluster or None if it does not exist."""
return self.db.cluster_get(context, cluster)
def cluster_get_all(self, context, **kwargs):
"""Get all clusters filtered by **kwargs.
e.g. cluster_get_all(plugin_name='vanilla', hadoop_version='1.1')
"""
return self.db.cluster_get_all(context, **kwargs)
def cluster_create(self, context, values):
"""Create a cluster from the values dictionary."""
# loading defaults
merged_values = copy.deepcopy(CLUSTER_DEFAULTS)
merged_values['tenant_id'] = context.tenant_id
private_key, public_key = crypto.generate_key_pair()
merged_values['management_private_key'] = private_key
merged_values['management_public_key'] = public_key
cluster_template_id = values.get('cluster_template_id')
c_tmpl = None
if cluster_template_id:
c_tmpl = self.cluster_template_get(context, cluster_template_id)
del c_tmpl['created_at']
del c_tmpl['updated_at']
del c_tmpl['id']
# updating with cluster_template values
merged_values.update(c_tmpl)
# updating with values provided in request
merged_values.update(values)
if c_tmpl:
merged_values['cluster_configs'] = configs.merge_configs(
c_tmpl.get('cluster_configs'),
values.get('cluster_configs'))
merged_values['node_groups'] = self._populate_node_groups(
context, merged_values)
return self.db.cluster_create(context, merged_values)
def cluster_update(self, context, cluster, values):
"""Set the given properties on cluster and update it."""
values = copy.deepcopy(values)
return self.db.cluster_update(context, cluster, values)
def cluster_destroy(self, context, cluster):
"""Destroy the cluster or raise if it does not exist."""
self.db.cluster_destroy(context, cluster)
# Node Group ops
def node_group_add(self, context, cluster, values):
"""Create a Node Group from the values dictionary."""
values = copy.deepcopy(values)
values = self._populate_node_group(context, values)
values['tenant_id'] = context.tenant_id
return self.db.node_group_add(context, cluster, values)
def node_group_update(self, context, node_group, values):
"""Set the given properties on node_group and update it."""
values = copy.deepcopy(values)
self.db.node_group_update(context, node_group, values)
def node_group_remove(self, context, node_group):
"""Destroy the node_group or raise if it does not exist."""
self.db.node_group_remove(context, node_group)
# Instance ops
def instance_add(self, context, node_group, values):
"""Create an Instance from the values dictionary."""
values = copy.deepcopy(values)
values = _apply_defaults(values, INSTANCE_DEFAULTS)
values['tenant_id'] = context.tenant_id
return self.db.instance_add(context, node_group, values)
def instance_update(self, context, instance, values):
"""Set the given properties on Instance and update it."""
values = copy.deepcopy(values)
self.db.instance_update(context, instance, values)
def instance_remove(self, context, instance):
"""Destroy the Instance or raise if it does not exist."""
self.db.instance_remove(context, instance)
# Volumes ops
def append_volume(self, context, instance, volume_id):
"""Append volume_id to instance."""
self.db.append_volume(context, instance, volume_id)
def remove_volume(self, context, instance, volume_id):
"""Remove volume_id in instance."""
self.db.remove_volume(context, instance, volume_id)
# Cluster Template ops
def cluster_template_get(self, context, cluster_template):
"""Return the cluster_template or None if it does not exist."""
return self.db.cluster_template_get(context, cluster_template)
def cluster_template_get_all(self, context):
"""Get all cluster_templates."""
return self.db.cluster_template_get_all(context)
def cluster_template_create(self, context, values):
"""Create a cluster_template from the values dictionary."""
values = copy.deepcopy(values)
values = _apply_defaults(values, CLUSTER_DEFAULTS)
values['tenant_id'] = context.tenant_id
values['node_groups'] = self._populate_node_groups(context, values)
return self.db.cluster_template_create(context, values)
def cluster_template_destroy(self, context, cluster_template):
"""Destroy the cluster_template or raise if it does not exist."""
self.db.cluster_template_destroy(context, cluster_template)
# Node Group Template ops
def node_group_template_get(self, context, node_group_template):
"""Return the Node Group Template or None if it does not exist."""
return self.db.node_group_template_get(context, node_group_template)
def node_group_template_get_all(self, context):
"""Get all Node Group Templates."""
return self.db.node_group_template_get_all(context)
def node_group_template_create(self, context, values):
"""Create a Node Group Template from the values dictionary."""
values = copy.deepcopy(values)
values = _apply_defaults(values, NODE_GROUP_DEFAULTS)
values['tenant_id'] = context.tenant_id
return self.db.node_group_template_create(context, values)
def node_group_template_destroy(self, context, node_group_template):
"""Destroy the Node Group Template or raise if it does not exist."""
self.db.node_group_template_destroy(context, node_group_template)
# Data Source ops
def data_source_get(self, context, data_source):
"""Return the Data Source or None if it does not exist."""
return self.db.data_source_get(context, data_source)
def data_source_get_all(self, context):
"""Get all Data Sources."""
return self.db.data_source_get_all(context)
def data_source_create(self, context, values):
"""Create a Data Source from the values dictionary."""
values = copy.deepcopy(values)
values = _apply_defaults(values, DATA_SOURCE_DEFAULTS)
values['tenant_id'] = context.tenant_id
return self.db.data_source_create(context, values)
def data_source_destroy(self, context, data_source):
"""Destroy the Data Source or raise if it does not exist."""
return self.db.data_source_destroy(context, data_source)
# JobExecution ops
def job_execution_get(self, context, job_execution):
"""Return the JobExecution or None if it does not exist."""
return self.db.job_execution_get(context, job_execution)
def job_execution_get_all(self, context, **kwargs):
"""Get all JobExecutions filtered by **kwargs.
e.g. job_execution_get_all(cluster_id=12, input_id=123)
"""
return self.db.job_execution_get_all(context, **kwargs)
def job_execution_count(self, context, **kwargs):
"""Count number of JobExecutions filtered by **kwargs.
e.g. job_execution_count(cluster_id=12, input_id=123)
"""
return self.db.job_execution_count(context, **kwargs)
def job_execution_create(self, context, values):
"""Create a JobExecution from the values dictionary."""
values = copy.deepcopy(values)
values['tenant_id'] = context.tenant_id
return self.db.job_execution_create(context, values)
def job_execution_update(self, context, job_execution, values):
"""Updates a JobExecution from the values dictionary."""
return self.db.job_execution_update(context, job_execution, values)
def job_execution_destroy(self, context, job_execution):
"""Destroy the JobExecution or raise if it does not exist."""
return self.db.job_execution_destroy(context, job_execution)
# Job ops
def job_get(self, context, job):
"""Return the Job or None if it does not exist."""
return self.db.job_get(context, job)
def job_get_all(self, context):
"""Get all Jobs."""
return self.db.job_get_all(context)
def job_create(self, context, values):
"""Create a Job from the values dictionary."""
values = copy.deepcopy(values)
values['tenant_id'] = context.tenant_id
return self.db.job_create(context, values)
def job_update(self, context, job, values):
"""Updates a Job from the values dictionary."""
return self.db.job_update(context, job, values)
def job_destroy(self, context, job):
"""Destroy the Job or raise if it does not exist."""
self.db.job_destroy(context, job)
# JobBinary ops
def job_binary_get_all(self, context):
"""Get all JobBinaries."""
return self.db.job_binary_get_all(context)
def job_binary_get(self, context, job_binary_id):
"""Return the JobBinary or None if it does not exist."""
return self.db.job_binary_get(context, job_binary_id)
def job_binary_create(self, context, values):
"""Create a JobBinary from the values dictionary."""
values = copy.deepcopy(values)
values['tenant_id'] = context.tenant_id
return self.db.job_binary_create(context, values)
def job_binary_destroy(self, context, job_binary):
"""Destroy the JobBinary or raise if it does not exist."""
self.db.job_binary_destroy(context, job_binary)
# JobBinaryInternal ops
def job_binary_internal_get_all(self, context):
"""Get all JobBinaryInternals
The JobBinaryInternals returned do not contain a data field.
"""
return self.db.job_binary_internal_get_all(context)
def job_binary_internal_get(self, context, job_binary_internal_id):
"""Return the JobBinaryInternal or None if it does not exist
The JobBinaryInternal returned does not contain a data field.
"""
return self.db.job_binary_internal_get(context, job_binary_internal_id)
def job_binary_internal_create(self, context, values):
"""Create a JobBinaryInternal from the values dictionary."""
# Since values["data"] is (should be) encoded as a string
# here the deepcopy of values only incs a reference count on data.
# This is nice, since data could be big...
values = copy.deepcopy(values)
values['tenant_id'] = context.tenant_id
return self.db.job_binary_internal_create(context, values)
def job_binary_internal_destroy(self, context, job_binary_internal):
"""Destroy the JobBinaryInternal or raise if it does not exist."""
self.db.job_binary_internal_destroy(context, job_binary_internal)
def job_binary_internal_get_raw_data(self,
context, job_binary_internal_id):
"""Return the binary data field from a JobBinaryInternal."""
return self.db.job_binary_internal_get_raw_data(
context,
job_binary_internal_id)
|
citrix-openstack-build/sahara
|
sahara/conductor/manager.py
|
Python
|
apache-2.0
| 14,758 | 0 |
#!/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.
'''Handling of the <message> element.
'''
import re
import types
from grit.node import base
import grit.format.rc_header
import grit.format.rc
from grit import clique
from grit import exception
from grit import lazy_re
from grit import tclib
from grit import util
BINARY, UTF8, UTF16 = range(3)
# Finds whitespace at the start and end of a string which can be multiline.
_WHITESPACE = lazy_re.compile('(?P<start>\s*)(?P<body>.+?)(?P<end>\s*)\Z',
re.DOTALL | re.MULTILINE)
class MessageNode(base.ContentNode):
'''A <message> element.'''
# For splitting a list of things that can be separated by commas or
# whitespace
_SPLIT_RE = lazy_re.compile('\s*,\s*|\s+')
def __init__(self):
super(type(self), self).__init__()
# Valid after EndParsing, this is the MessageClique that contains the
# source message and any translations of it that have been loaded.
self.clique = None
# We don't send leading and trailing whitespace into the translation
# console, but rather tack it onto the source message and any
# translations when formatting them into RC files or what have you.
self.ws_at_start = '' # Any whitespace characters at the start of the text
self.ws_at_end = '' # --"-- at the end of the text
# A list of "shortcut groups" this message is in. We check to make sure
# that shortcut keys (e.g. &J) within each shortcut group are unique.
self.shortcut_groups_ = []
def _IsValidChild(self, child):
return isinstance(child, (PhNode))
def _IsValidAttribute(self, name, value):
if name not in ['name', 'offset', 'translateable', 'desc', 'meaning',
'internal_comment', 'shortcut_groups', 'custom_type',
'validation_expr', 'use_name_for_id', 'sub_variable']:
return False
if (name in ('translateable', 'sub_variable') and
value not in ['true', 'false']):
return False
return True
def MandatoryAttributes(self):
return ['name|offset']
def DefaultAttributes(self):
return {
'custom_type' : '',
'desc' : '',
'internal_comment' : '',
'meaning' : '',
'shortcut_groups' : '',
'sub_variable' : 'false',
'translateable' : 'true',
'use_name_for_id' : 'false',
'validation_expr' : '',
}
def GetTextualIds(self):
'''
Returns the concatenation of the parent's node first_id and
this node's offset if it has one, otherwise just call the
superclass' implementation
'''
if 'offset' in self.attrs:
# we search for the first grouping node in the parents' list
# to take care of the case where the first parent is an <if> node
grouping_parent = self.parent
import grit.node.empty
while grouping_parent and not isinstance(grouping_parent,
grit.node.empty.GroupingNode):
grouping_parent = grouping_parent.parent
assert 'first_id' in grouping_parent.attrs
return [grouping_parent.attrs['first_id'] + '_' + self.attrs['offset']]
else:
return super(type(self), self).GetTextualIds()
def IsTranslateable(self):
return self.attrs['translateable'] == 'true'
def ItemFormatter(self, t):
# Only generate an output if the if condition is satisfied.
if not self.SatisfiesOutputCondition():
return super(type(self), self).ItemFormatter(t)
if t == 'rc_header':
return grit.format.rc_header.Item()
elif t in ('rc_all', 'rc_translateable', 'rc_nontranslateable'):
return grit.format.rc.Message()
elif t == 'c_format' and self.SatisfiesOutputCondition():
return grit.format.c_format.Message()
elif t == 'js_map_format':
return grit.format.js_map_format.Message()
else:
return super(type(self), self).ItemFormatter(t)
def EndParsing(self):
super(type(self), self).EndParsing()
# Make the text (including placeholder references) and list of placeholders,
# then strip and store leading and trailing whitespace and create the
# tclib.Message() and a clique to contain it.
text = ''
placeholders = []
for item in self.mixed_content:
if isinstance(item, types.StringTypes):
text += item
else:
presentation = item.attrs['name'].upper()
text += presentation
ex = ' '
if len(item.children):
ex = item.children[0].GetCdata()
original = item.GetCdata()
placeholders.append(tclib.Placeholder(presentation, original, ex))
m = _WHITESPACE.match(text)
if m:
self.ws_at_start = m.group('start')
self.ws_at_end = m.group('end')
text = m.group('body')
self.shortcut_groups_ = self._SPLIT_RE.split(self.attrs['shortcut_groups'])
self.shortcut_groups_ = [i for i in self.shortcut_groups_ if i != '']
description_or_id = self.attrs['desc']
if description_or_id == '' and 'name' in self.attrs:
description_or_id = 'ID: %s' % self.attrs['name']
assigned_id = None
if (self.attrs['use_name_for_id'] == 'true' and
self.SatisfiesOutputCondition()):
assigned_id = self.attrs['name']
message = tclib.Message(text=text, placeholders=placeholders,
description=description_or_id,
meaning=self.attrs['meaning'],
assigned_id=assigned_id)
self.InstallMessage(message)
def InstallMessage(self, message):
'''Sets this node's clique from a tclib.Message instance.
Args:
message: A tclib.Message.
'''
self.clique = self.UberClique().MakeClique(message, self.IsTranslateable())
for group in self.shortcut_groups_:
self.clique.AddToShortcutGroup(group)
if self.attrs['custom_type'] != '':
self.clique.SetCustomType(util.NewClassInstance(self.attrs['custom_type'],
clique.CustomType))
elif self.attrs['validation_expr'] != '':
self.clique.SetCustomType(
clique.OneOffCustomType(self.attrs['validation_expr']))
def SubstituteMessages(self, substituter):
'''Applies substitution to this message.
Args:
substituter: a grit.util.Substituter object.
'''
message = substituter.SubstituteMessage(self.clique.GetMessage())
if message is not self.clique.GetMessage():
self.InstallMessage(message)
def GetCliques(self):
if self.clique:
return [self.clique]
else:
return []
def Translate(self, lang):
'''Returns a translated version of this message.
'''
assert self.clique
msg = self.clique.MessageForLanguage(lang,
self.PseudoIsAllowed(),
self.ShouldFallbackToEnglish()
).GetRealContent()
return msg.replace('[GRITLANGCODE]', lang)
def NameOrOffset(self):
if 'name' in self.attrs:
return self.attrs['name']
else:
return self.attrs['offset']
def ExpandVariables(self):
'''We always expand variables on Messages.'''
return True
def GetDataPackPair(self, lang, encoding):
'''Returns a (id, string) pair that represents the string id and the string
in utf8. This is used to generate the data pack data file.
'''
from grit.format import rc_header
id_map = rc_header.Item.tids_
id = id_map[self.GetTextualIds()[0]]
message = self.ws_at_start + self.Translate(lang) + self.ws_at_end
# |message| is a python unicode string, so convert to a byte stream that
# has the correct encoding requested for the datapacks. We skip the first
# 2 bytes of text resources because it is the BOM.
if encoding == UTF8:
return id, message.encode('utf8')
if encoding == UTF16:
return id, message.encode('utf16')[2:]
# Default is BINARY
return id, message
# static method
def Construct(parent, message, name, desc='', meaning='', translateable=True):
'''Constructs a new message node that is a child of 'parent', with the
name, desc, meaning and translateable attributes set using the same-named
parameters and the text of the message and any placeholders taken from
'message', which must be a tclib.Message() object.'''
# Convert type to appropriate string
if translateable:
translateable = 'true'
else:
translateable = 'false'
node = MessageNode()
node.StartParsing('message', parent)
node.HandleAttribute('name', name)
node.HandleAttribute('desc', desc)
node.HandleAttribute('meaning', meaning)
node.HandleAttribute('translateable', translateable)
items = message.GetContent()
for ix in range(len(items)):
if isinstance(items[ix], types.StringTypes):
text = items[ix]
# Ensure whitespace at front and back of message is correctly handled.
if ix == 0:
text = "'''" + text
if ix == len(items) - 1:
text = text + "'''"
node.AppendContent(text)
else:
phnode = PhNode()
phnode.StartParsing('ph', node)
phnode.HandleAttribute('name', items[ix].GetPresentation())
phnode.AppendContent(items[ix].GetOriginal())
if len(items[ix].GetExample()) and items[ix].GetExample() != ' ':
exnode = ExNode()
exnode.StartParsing('ex', phnode)
exnode.AppendContent(items[ix].GetExample())
exnode.EndParsing()
phnode.AddChild(exnode)
phnode.EndParsing()
node.AddChild(phnode)
node.EndParsing()
return node
Construct = staticmethod(Construct)
class PhNode(base.ContentNode):
'''A <ph> element.'''
def _IsValidChild(self, child):
return isinstance(child, ExNode)
def MandatoryAttributes(self):
return ['name']
def EndParsing(self):
super(type(self), self).EndParsing()
# We only allow a single example for each placeholder
if len(self.children) > 1:
raise exception.TooManyExamples()
class ExNode(base.ContentNode):
'''An <ex> element.'''
pass
|
JoKaWare/WTL-DUI
|
tools/grit/grit/node/message.py
|
Python
|
bsd-3-clause
| 10,287 | 0.009138 |
from django.contrib import admin
from tasks import models
admin.site.register(models.Project)
admin.site.register(models.Priority)
admin.site.register(models.TaskStatus)
admin.site.register(models.Phase)
admin.site.register(models.Task)
|
jarnoln/mitasny
|
tasks/admin.py
|
Python
|
mit
| 238 | 0 |
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Resource execeptions."""
from googlecloudsdk.core import exceptions
class Error(exceptions.Error):
"""A base exception for all recoverable resource errors => no stack trace."""
pass
class InternalError(exceptions.InternalError):
"""A base exception for all unrecoverable resource errors => stack trace."""
pass
class ExpressionSyntaxError(Error):
"""Resource expression syntax error."""
pass
class ResourceRegistryAttributeError(exceptions.InternalError):
"""Missing or invalid resource registry attribute error."""
pass
class UnregisteredCollectionError(Error):
"""Unregistered resource collection error."""
pass
|
KaranToor/MA450
|
google-cloud-sdk/lib/googlecloudsdk/core/resource/resource_exceptions.py
|
Python
|
apache-2.0
| 1,244 | 0.008039 |
# Copyright (c) 2013 Red Hat, Inc.
# Author: William Benton (willb@redhat.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.
from proxy import Proxy, proxied_attr
from proxy import proxied_attr_get as pag, proxied_attr_set as pas, proxied_attr_getset as pags
from arc_utils import arcmethod, uniq
from singleton import v as store_singleton
import errors
from errors import not_implemented, fail
from constants import PARTITION_GROUP, LABEL_SENTINEL_PARAM, LABEL_SENTINEL_PARAM_ATTR
from datetime import datetime
import calendar
import urllib
def ts():
now = datetime.utcnow()
return (calendar.timegm(now.utctimetuple()) * 1000000) + now.microsecond
class node(Proxy):
name = property(pag("name"))
memberships = property(*pags("memberships"))
identity_group = property(lambda self : self.cm.make_proxy_object("group", self.attr_vals["identity_group"], refresh=True))
provisioned = property(*pags("provisioned"))
last_updated_version = property(pag("last_updated_version"))
modifyMemberships = arcmethod(pag("memberships"), pas("memberships"), heterogeneous=True, preserve_order=True)
def getConfig(self, **options):
if options.has_key("version"):
return self.cm.fetch_json_resource("/config/node/%s" % urllib.quote_plus(self.name), {"commit":options["version"]}, {})
return self.cm.fetch_json_resource("/config/node/%s" % urllib.quote_plus(self.name))
def makeProvisioned(self):
self.provisioned = True
self.update()
def explain(self):
not_implemented()
def checkin(self):
metapath = "/meta/node/%s" % self.name
# now = datetime.utcnow().isoformat()
now = ts()
meta = self.cm.fetch_json_resource(metapath, False, default={})
meta["last-checkin"] = now
self.cm.put_json_resource(metapath, meta, False)
return now
def last_checkin(self):
metapath = "/meta/node/%s" % self.name
meta = self.cm.fetch_json_resource(metapath, False, default={})
return meta.has_key("last-checkin") and meta["last-checkin"] or 0
def whatChanged(self, old, new):
oc = self.cm.fetch_json_resource("/config/node/%s" % urllib.quote_plus(self.name), {"commit":old}, {})
nc = self.cm.fetch_json_resource("/config/node/%s" % urllib.quote_plus(self.name), {"commit":new}, {})
ock = set(oc)
nck = set(nc)
params = set([p for p in (ock | nck) if p not in ock or p not in nck or oc[p] != nc[p]]) - set(["WALLABY_CONFIG_VERSION"])
mc_params = set([p for p in params if store_singleton().getParam(p).must_change])
subsystems = [store_singleton().getSubsys(sub) for sub in self.cm.list_objects("subsystem")]
restart, reconfig = [], []
for ss in subsystems:
ss.refresh
ssp = set(ss.parameters)
if ssp.intersection(mc_params):
restart.append(ss.name)
elif ssp.intersection(params):
reconfig.append(ss.name)
return [list(params), restart, reconfig]
# labeling support below
def getLabels(self):
memberships = self.memberships
if not PARTITION_GROUP in memberships:
return []
else:
partition = memberships.index(PARTITION_GROUP)
return memberships[partition+1:]
labels=property(getLabels)
def modifyLabels(self, op, labels, **options):
thestore = store_singleton()
memberships = self.memberships
current_labels = self.getLabels()
label_set = set(current_labels + [PARTITION_GROUP])
new_labels = []
if op == "ADD":
new_labels = current_labels + labels
pass
elif op == "REPLACE":
new_labels = labels
pass
elif op == "REMOVE":
new_labels = [label for label in current_labels if label not in labels]
else:
raise NotImplementedError("modifyLabels: operation " + op + " not understood")
just_memberships = [grp for grp in memberships if grp not in label_set]
new_memberships = uniq(just_memberships + [PARTITION_GROUP] + new_labels)
if "ensure_partition_group" in options and options["ensure_partition_group"] is not False:
if thestore is None:
raise RuntimeError("store singleton must be initialized before using the ensure_partition_group option")
thestore.getPartitionGroup()
if "create_missing_labels" in options and options["create_missing_labels"] is not False:
if thestore is None:
raise RuntimeError("store singleton must be initialized before using the create_missing_labels option")
for missing_label in thestore.checkGroupValidity(new_labels):
thestore.addLabel(missing_label)
return self.modifyMemberships("REPLACE", new_memberships, {})
proxied_attr(node, "name")
proxied_attr(node, "memberships")
proxied_attr(node, "identity_group")
proxied_attr(node, "provisioned")
|
willb/wallaroo
|
clients/python-wallaroo/wallaroo/client/node.py
|
Python
|
apache-2.0
| 5,705 | 0.009465 |
#
# Copyright 2013 Red Hat, Inc
#
# Author: Eoghan Glynn <eglynn@redhat.com>
# Author: Mehdi Abaakouk <mehdi.abaakouk@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.
import datetime
import operator
from oslo.utils import timeutils
from ceilometer.alarm import evaluator
from ceilometer.alarm.evaluator import utils
from ceilometer.openstack.common.gettextutils import _
from ceilometer.openstack.common import log
LOG = log.getLogger(__name__)
COMPARATORS = {
'gt': operator.gt,
'lt': operator.lt,
'ge': operator.ge,
'le': operator.le,
'eq': operator.eq,
'ne': operator.ne,
}
class ThresholdEvaluator(evaluator.Evaluator):
# the sliding evaluation window is extended to allow
# for reporting/ingestion lag
look_back = 1
# minimum number of datapoints within sliding window to
# avoid unknown state
quorum = 1
@classmethod
def _bound_duration(cls, alarm, constraints):
"""Bound the duration of the statistics query."""
now = timeutils.utcnow()
# when exclusion of weak datapoints is enabled, we extend
# the look-back period so as to allow a clearer sample count
# trend to be established
look_back = (cls.look_back if not alarm.rule.get('exclude_outliers')
else alarm.rule['evaluation_periods'])
window = (alarm.rule['period'] *
(alarm.rule['evaluation_periods'] + look_back))
start = now - datetime.timedelta(seconds=window)
LOG.debug(_('query stats from %(start)s to '
'%(now)s') % {'start': start, 'now': now})
after = dict(field='timestamp', op='ge', value=start.isoformat())
before = dict(field='timestamp', op='le', value=now.isoformat())
constraints.extend([before, after])
return constraints
@staticmethod
def _sanitize(alarm, statistics):
"""Sanitize statistics."""
LOG.debug(_('sanitize stats %s') % statistics)
if alarm.rule.get('exclude_outliers'):
key = operator.attrgetter('count')
mean = utils.mean(statistics, key)
stddev = utils.stddev(statistics, key, mean)
lower = mean - 2 * stddev
upper = mean + 2 * stddev
inliers, outliers = utils.anomalies(statistics, key, lower, upper)
if outliers:
LOG.debug(_('excluded weak datapoints with sample counts %s'),
[s.count for s in outliers])
statistics = inliers
else:
LOG.debug('no excluded weak datapoints')
# in practice statistics are always sorted by period start, not
# strictly required by the API though
statistics = statistics[-alarm.rule['evaluation_periods']:]
LOG.debug(_('pruned statistics to %d') % len(statistics))
return statistics
def _statistics(self, alarm, query):
"""Retrieve statistics over the current window."""
LOG.debug(_('stats query %s') % query)
try:
return self._client.statistics.list(
meter_name=alarm.rule['meter_name'], q=query,
period=alarm.rule['period'])
except Exception:
LOG.exception(_('alarm stats retrieval failed'))
return []
def _sufficient(self, alarm, statistics):
"""Check for the sufficiency of the data for evaluation.
Ensure there is sufficient data for evaluation, transitioning to
unknown otherwise.
"""
sufficient = len(statistics) >= self.quorum
if not sufficient and alarm.state != evaluator.UNKNOWN:
reason = _('%d datapoints are unknown') % alarm.rule[
'evaluation_periods']
reason_data = self._reason_data('unknown',
alarm.rule['evaluation_periods'],
None)
self._refresh(alarm, evaluator.UNKNOWN, reason, reason_data)
return sufficient
@staticmethod
def _reason_data(disposition, count, most_recent):
"""Create a reason data dictionary for this evaluator type."""
return {'type': 'threshold', 'disposition': disposition,
'count': count, 'most_recent': most_recent}
@classmethod
def _reason(cls, alarm, statistics, distilled, state):
"""Fabricate reason string."""
count = len(statistics)
disposition = 'inside' if state == evaluator.OK else 'outside'
last = getattr(statistics[-1], alarm.rule['statistic'])
transition = alarm.state != state
reason_data = cls._reason_data(disposition, count, last)
if transition:
return (_('Transition to %(state)s due to %(count)d samples'
' %(disposition)s threshold, most recent:'
' %(most_recent)s')
% dict(reason_data, state=state)), reason_data
return (_('Remaining as %(state)s due to %(count)d samples'
' %(disposition)s threshold, most recent: %(most_recent)s')
% dict(reason_data, state=state)), reason_data
def _transition(self, alarm, statistics, compared):
"""Transition alarm state if necessary.
The transition rules are currently hardcoded as:
- transitioning from a known state requires an unequivocal
set of datapoints
- transitioning from unknown is on the basis of the most
recent datapoint if equivocal
Ultimately this will be policy-driven.
"""
distilled = all(compared)
unequivocal = distilled or not any(compared)
unknown = alarm.state == evaluator.UNKNOWN
continuous = alarm.repeat_actions
if unequivocal:
state = evaluator.ALARM if distilled else evaluator.OK
reason, reason_data = self._reason(alarm, statistics,
distilled, state)
if alarm.state != state or continuous:
self._refresh(alarm, state, reason, reason_data)
elif unknown or continuous:
trending_state = evaluator.ALARM if compared[-1] else evaluator.OK
state = trending_state if unknown else alarm.state
reason, reason_data = self._reason(alarm, statistics,
distilled, state)
self._refresh(alarm, state, reason, reason_data)
def evaluate(self, alarm):
if not self.within_time_constraint(alarm):
LOG.debug(_('Attempted to evaluate alarm %s, but it is not '
'within its time constraint.') % alarm.alarm_id)
return
query = self._bound_duration(
alarm,
alarm.rule['query']
)
statistics = self._sanitize(
alarm,
self._statistics(alarm, query)
)
if self._sufficient(alarm, statistics):
def _compare(stat):
op = COMPARATORS[alarm.rule['comparison_operator']]
value = getattr(stat, alarm.rule['statistic'])
limit = alarm.rule['threshold']
LOG.debug(_('comparing value %(value)s against threshold'
' %(limit)s') %
{'value': value, 'limit': limit})
return op(value, limit)
self._transition(alarm,
statistics,
map(_compare, statistics))
|
MisterPup/Ceilometer-Juno-Extension
|
ceilometer/alarm/evaluator/threshold.py
|
Python
|
apache-2.0
| 8,086 | 0 |
from toee import *
import tpactions
def GetActionName():
return "Divine Spell Power"
def GetActionDefinitionFlags():
return D20ADF_None
def GetTargetingClassification():
return D20TC_Target0
def GetActionCostType():
return D20ACT_NULL
def AddToSequence(d20action, action_seq, tb_status):
action_seq.add_action(d20action)
return AEC_OK
|
GrognardsFromHell/TemplePlus
|
tpdatasrc/tpgamefiles/rules/d20_actions/action02603_feat_divine_spell_power.py
|
Python
|
mit
| 346 | 0.040462 |
WMC_RATE_LIMIT = 5
WMC_USER = ''
WMC_PASSWORD = ''
BLOCKHASH_COMMAND = 'blockhash'
SQLALCHEMY_URL = 'postgresql://user:pass@localhost/test'
BROKER_URL = 'amqp://guest@localhost/'
try:
from config_local import *
except ImportError:
pass
|
commonsmachinery/commonshasher
|
config.py
|
Python
|
gpl-3.0
| 246 | 0.004065 |
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import fsolve
import argparse
import json
class Diagramas(object):
def __init__(self, datos, w, h, den, units='SI'):
self.CAM = datos["CAM"]
self.sw = datos["sw"]
self.a3D = datos["a3D"]
self.MTOW = datos["MTOW"]
self.MLW = datos["MLW"]
self.MZFW = datos["MZFW"]
self.Vc = datos["Vc"]
self.clmax = datos["clmax"]
self.clmax_flap = datos["clmax_flap"]
self.clmin = datos["clmin"]
self.Zmo = datos["Zmo"]
self.W = w
self.h = h
self.den = den
self.units = units
self.carga_alar = {}
self.H = {}
self.Vs1 = {}
self.Vs0 = {}
self.Vsf = {}
self.Vd = {}
self.Va = {}
self.Vf = {}
self.Vf_n2 = {}
self.Vb = {}
self.Uref = {}
self.Uds = self.U = {}
self.Ude_25fts = {}
self.Ude_50fts = {}
self.Ude_60fts = {}
self.vel_label = {'IM': 'ft/s', 'SI': 'm/s'}
# constantes fijas:
self.ft2m = 0.3048
self.lb2kg = 0.453592
self.cte_fgz = {'IM': 250000}
self.cte_fgz['SI'] = self.cte_fgz['IM'] * self.ft2m
self.s = {'IM': 100.015}
self.s['SI'] = self.s['IM'] * self.ft2m
self.gravedad = {'SI': 9.81}
self.gravedad['IM'] = self.gravedad['SI'] / self.ft2m
self.cte_nmax_1 = {'IM': 24000}
self.cte_nmax_1['SI'] = self.cte_nmax_1['IM'] * self.lb2kg
self.cte_nmax_2 = {'IM': 10000}
self.cte_nmax_2['SI'] = self.cte_nmax_1['IM'] * self.lb2kg
self.cte_Uref_h1 = {'IM': 15000}
self.cte_Uref_h1['SI'] = self.cte_Uref_h1['IM'] * self.ft2m
self.cte_Uref_h2 = {'IM': 50000}
self.cte_Uref_h2['SI'] = self.cte_Uref_h2['IM'] * self.ft2m
self.cte_Uref_v1 = {'IM': 56}
self.cte_Uref_v1['SI'] = self.cte_Uref_v1['IM'] * self.ft2m
self.cte_Uref_v2 = {'IM': 56}
self.cte_Uref_v2['SI'] = self.cte_Uref_v2['IM'] * self.ft2m
self.cte_Uref_v3 = {'IM': 26}
self.cte_Uref_v3['SI'] = self.cte_Uref_v3['IM'] * self.ft2m
# Esta constante esta porque hay que usar la pendiente a_cn = dCn/dalpha, y no a_cl = dCl/dalpha, pero no se de donde sale el valor
self.ad_CN = 0.59248
self.cte_Vb = {'IM': 498.0} # lb/s**2
self.cte_Vb['SI'] = self.cte_Vb['IM'] * self.ft2m ** 4 / self.lb2kg
# Velocidad de rafadas
self.cte_Ude_h1 = {'IM': 20000}
self.cte_Ude_h1['SI'] = self.cte_Ude_h1['IM'] * self.ft2m
self.cte_Ude_h2 = {'IM': 50000}
self.cte_Ude_h2['SI'] = self.cte_Ude_h2['IM'] * self.ft2m
self.cte_25fts_v1 = {'IM': 25}
self.cte_25fts_v1['SI'] = self.cte_25fts_v1['IM'] * self.ft2m
self.cte_25fts_v2 = {'IM': 33.34}
self.cte_25fts_v2['SI'] = self.cte_25fts_v2['IM'] * self.ft2m
self.cte_25fts_m2 = 0.000417
self.cte_25fts_v3 = {'IM': 12.5}
self.cte_25fts_v3['SI'] = self.cte_25fts_v3['IM'] * self.ft2m
self.cte_50fts_v1 = {'IM': 50}
self.cte_50fts_v1['SI'] = self.cte_50fts_v1['IM'] * self.ft2m
self.cte_50fts_v2 = {'IM': 66.77}
self.cte_50fts_v2['SI'] = self.cte_50fts_v2['IM'] * self.ft2m
self.cte_50fts_m2 = 0.0008933
self.cte_50fts_v3 = {'IM': 25}
self.cte_50fts_v3['SI'] = self.cte_50fts_v3['IM'] * self.ft2m
self.cte_60fts_v1 = {'IM': 60}
self.cte_60fts_v1['SI'] = self.cte_60fts_v1['IM'] * self.ft2m
self.cte_60fts_v2 = {'IM': 60}
self.cte_60fts_v2['SI'] = self.cte_60fts_v2['IM'] * self.ft2m
self.cte_60fts_m2 = {'IM': 18}
self.cte_60fts_m2['SI'] = self.cte_60fts_m2['IM'] * self.ft2m
self.cte_60fts_v3 = {'IM': 38}
self.cte_60fts_v3['SI'] = self.cte_60fts_v3['IM'] * self.ft2m
# constantes relacionadas con el diagrama de rafagas
self.R1 = self.MLW[units] / self.MTOW[units]
self.R2 = self.MZFW[units] / self.MTOW[units]
self.fgm = np.sqrt(self.R2 * np.tan(np.pi * self.R1 / 4.0))
self.fgz = 1 - self.Zmo[units] / self.cte_fgz[units]
self.fg = 0.5 * (self.fgz + self.fgm)
def calculos(self):
self.R1 = self.MLW[self.units] / self.MTOW[self.units]
self.R2 = self.MZFW[self.units] / self.MTOW[self.units]
self.fgm = np.sqrt(self.R2 * np.tan(np.pi * self.R1 / 4.0))
self.fgz = 1 - self.Zmo[self.units] / self.cte_fgz[self.units]
self.fg = 0.5 * (self.fgz + self.fgm)
self.carga_alar[self.units] = self.W[self.units] / self.sw[self.units]
self.mu_g = 2 * self.carga_alar[self.units] / (self.den[self.units] * self.CAM[self.units] * self.a3D) # *gravedad[units])
self.Kg = 0.88 * (self.mu_g / (5.3 + self.mu_g))
self.Vs1[self.units] = np.sqrt((self.carga_alar[self.units] * self.gravedad[self.units]) / (0.5 * self.den[self.units] * self.clmax))
self.Vs0[self.units] = np.sqrt((-self.carga_alar[self.units] * self.gravedad[self.units]) / (0.5 * self.den[self.units] * self.clmin))
self.Vsf[self.units] = np.sqrt((self.carga_alar[self.units] * self.gravedad[self.units]) / (0.5 * self.den[self.units] * self.clmax_flap))
# Calculo de n_max
self.n_max = 2.1 + self.cte_nmax_1[self.units] / (self.MTOW[self.units] + self.cte_nmax_2[self.units])
if self.n_max < 2.5:
self.n_max = 2.5
elif self.n_max > 3.8:
self.n_max = 3.8
self.Va[self.units] = self.Vs1[self.units] * np.sqrt(self.n_max)
if self.Va[self.units] > self.Vc[self.units]:
self.Va[self.units] = self.Vc[self.units]
self.Vd[self.units] = self.Vc[self.units] / 0.85
self.Vf[self.units] = max(self.Vs1[self.units] * 1.6, self.Vsf[self.units] * 1.8)
if self.h[self.units] < self.cte_Uref_h1[self.units]:
self.Uref[self.units] = self.cte_Uref_v1[self.units] - 12.0 * self.h[self.units] / self.cte_Uref_h1[self.units]
elif self.h[self.units] < self.cte_Uref_h2[self.units]:
self.Uref[self.units] = self.cte_Uref_v2[self.units] - 18.0 * (self.h[self.units] - self.cte_Uref_h1[self.units]) / \
(self.cte_Uref_h2[self.units] - self.cte_Uref_h1[self.units])
else:
self.Uref[self.units] = self.cte_Uref_v3[self.units]
self.Vb[self.units] = min(self.Vc[self.units], self.Vs1[self.units] * np.sqrt(1 + self.Kg * self.Uref[self.units] * self.Vc[self.units] *
self.a3D * self.ad_CN / (self.cte_Vb[self.units] * self.carga_alar[self.units])))
if self.h[self.units] < self.cte_Ude_h1[self.units]:
self.Ude_25fts[self.units] = self.cte_25fts_v1[self.units]
self.Ude_50fts[self.units] = self.cte_50fts_v1[self.units]
self.Ude_60fts[self.units] = self.cte_60fts_v1[self.units]
elif self.h[self.units] < self.cte_Ude_h2[self.units]:
self.Ude_25fts[self.units] = self.cte_25fts_v2[self.units] - self.cte_25fts_m2 * self.h[self.units]
self.Ude_50fts[self.units] = self.cte_50fts_v2[self.units] - self.cte_50fts_m2 * self.h[self.units]
self.Ude_60fts[self.units] = self.cte_60fts_v2[self.units] - self.cte_60fts_m2[self.units] * \
(self.h[self.units] - self.cte_Ude_h1[self.units]) \
/(self.cte_Ude_h2[self.units] - self.cte_Ude_h1[self.units])
else:
self.Ude_25fts[self.units] = self.cte_25fts_v3[self.units]
self.Ude_50fts[self.units] = self.cte_50fts_v3[self.units]
self.Ude_60fts[self.units] = self.cte_60fts_v3[self.units]
self.Vf_n2[self.units] = np.sqrt(2 * self.W[self.units] * self.gravedad[self.units] / (0.5 * self.den[self.units] * self.clmax_flap * self.sw[self.units]))
def n_25fts(self, vel):
return self.fg * self.Ude_25fts[self.units] * self.a3D * self.ad_CN * vel / (self.cte_Vb[self.units] * self.carga_alar[self.units])
def n_50fts(self, vel):
return self.Kg * self.Ude_50fts[self.units] * self.a3D * self.ad_CN * vel / (self.cte_Vb[self.units] * self.carga_alar[self.units])
def n_60fts(self, vel):
return self.Kg * self.Ude_60fts[self.units] * self.a3D * self.ad_CN * vel / (self.cte_Vb[self.units] * self.carga_alar[self.units])
def n_gust_pos(self, vel):
if 0 <= vel <= self.Vb[self.units]:
return 1 + self.n_60fts(vel)
elif vel <= self.Vc[self.units]:
m = (self.n_50fts(self.Vc[self.units]) - self.n_60fts(self.Vb[self.units])) / (self.Vc[self.units] - self.Vb[self.units])
b = self.n_50fts(self.Vc[self.units]) - m * self.Vc[self.units]
return 1 + m * vel + b
elif vel <= self.Vd[self.units]:
m = (self.n_25fts(self.Vd[self.units]) - self.n_50fts(self.Vc[self.units])) / (self.Vd[self.units] - self.Vc[self.units])
b = self.n_25fts(self.Vd[self.units]) - m * self.Vd[self.units]
return 1 + m * vel + b
return 0.0
def n_gust_neg(self, vel):
if 0 <= vel <= self.Vb[self.units]:
return 1 - self.n_60fts(vel)
elif vel <= self.Vc[self.units]:
m = -(self.n_50fts(self.Vc[self.units]) - self.n_60fts(self.Vb[self.units])) / (self.Vc[self.units] - self.Vb[self.units])
b = -self.n_50fts(self.Vc[self.units]) - m * self.Vc[self.units]
return 1 + m * vel + b
elif vel <= self.Vd[self.units]:
m = -(self.n_25fts(self.Vd[self.units]) - self.n_50fts(self.Vc[self.units])) / (self.Vd[self.units] - self.Vc[self.units])
b = -self.n_25fts(self.Vd[self.units]) - m * self.Vd[self.units]
return 1 + m * vel + b
return 0.0
def n_stall_pos(self, vel):
return 0.5 * self.den[self.units] * vel**2 * self.sw[self.units] * self.clmax / (self.W[self.units] * self.gravedad[self.units])
def n_stall_neg(self, vel):
return 0.5 * self.den[self.units] * vel**2 * self.sw[self.units] * self.clmin / (self.W[self.units] * self.gravedad[self.units])
def n_stall_flap(self, vel):
return 0.5 * self.den[self.units] * vel**2 * self.sw[self.units] * self.clmax_flap / (self.W[self.units] * self.gravedad[self.units])
def n_manoeuvre_pos(self, vel):
if 0 <= vel <= self.Va[self.units]:
return self.n_stall_pos(vel)
elif vel <= self.Vd[self.units]:
return self.n_max
return None
def n_manoeuvre_neg(self, vel):
if 0 <= vel <= self.Vs0[self.units]:
return self.n_stall_neg(vel)
elif vel <= self.Vc[self.units]:
return -1.0
elif vel <= self.Vd[self.units]:
return -1 + 1 / (self.Vd[self.units] - self.Vc[self.units]) * (vel - self.Vc[self.units])
return None
def plot_diagrama_de_rafagas(self, ax, dv):
ax.plot(np.arange(0, self.Vb[self.units], dv), [1 + self.n_60fts(vel) for vel in np.arange(0, self.Vb[self.units], dv)], color='r')
ax.plot(np.arange(0, self.Vb[self.units], dv), [1 - self.n_60fts(vel) for vel in np.arange(0, self.Vb[self.units], dv)], color='r')
ax.plot(np.arange(0, self.Vc[self.units], dv), [1 + self.n_50fts(vel) for vel in np.arange(0, self.Vc[self.units], dv)], color='b')
ax.plot(np.arange(0, self.Vc[self.units], dv), [1 - self.n_50fts(vel) for vel in np.arange(0, self.Vc[self.units], dv)], color='b')
ax.plot(np.arange(0, self.Vd[self.units], dv), [1 + self.n_25fts(vel) for vel in np.arange(0, self.Vd[self.units], dv)], color='g')
ax.plot(np.arange(0, self.Vd[self.units], dv), [1 - self.n_25fts(vel) for vel in np.arange(0, self.Vd[self.units], dv)], color='g')
ax.plot([self.Vb[self.units], self.Vc[self.units]], [1 + self.n_60fts(self.Vb[self.units]), 1 + self.n_50fts(self.Vc[self.units])], color='m')
ax.plot([self.Vb[self.units], self.Vc[self.units]], [1 - self.n_60fts(self.Vb[self.units]), 1 - self.n_50fts(self.Vc[self.units])], color='m')
ax.plot([self.Vc[self.units], self.Vd[self.units]], [1 + self.n_50fts(self.Vc[self.units]), 1 + self.n_25fts(self.Vd[self.units])], color='m')
ax.plot([self.Vc[self.units], self.Vd[self.units]], [1 - self.n_50fts(self.Vc[self.units]), 1 - self.n_25fts(self.Vd[self.units])], color='m')
ax.plot([self.Vd[self.units], self.Vd[self.units]], [1 + self.n_25fts(self.Vd[self.units]), 1 - self.n_25fts(self.Vd[self.units])], color='m')
ax.set_xlabel("Speed [{}]".format(self.vel_label[self.units]))
ax.set_ylabel("n")
ax.set_title("Gust Diagram")
def plot_diagrama_de_maniobras(self, ax, dv):
ax.plot(np.arange(0, self.Vs1[self.units], dv), [self.n_stall_pos(vel) for vel in np.arange(0, self.Vs1[self.units], dv)], color='m',
linestyle='--')
ax.plot([self.Vs1[self.units], self.Vs1[self.units]], [0, self.n_stall_pos(self.Vs1[self.units])], color='m')
ax.plot(np.arange(self.Vs1[self.units], self.Va[self.units], dv),
[self.n_stall_pos(vel) for vel in np.arange(self.Vs1[self.units], self.Va[self.units], dv)],
color='m', linestyle='-')
ax.plot(np.arange(0, self.Vs0[self.units] + dv, dv), [self.n_stall_neg(vel) for vel in np.arange(0, self.Vs0[self.units] + dv, dv)],
color='m', linestyle='--')
ax.plot([self.Vs0[self.units], self.Vs0[self.units]], [0, -1.0], color='m')
ax.plot([self.Vs1[self.units], self.Vs0[self.units]], [0.0, 0.0], color='m')
ax.plot([self.Va[self.units], self.Vd[self.units]], [self.n_max, self.n_max], color='m')
ax.plot([self.Vd[self.units], self.Vd[self.units]], [self.n_max, 0], color='m')
ax.plot([self.Vs0[self.units], self.Vc[self.units]], [-1.0, -1.0], color='m')
ax.plot([self.Vc[self.units], self.Vd[self.units]], [-1.0, 0.0], color='m')
ax.set_xlabel("Speed [{}]".format(self.vel_label[self.units]))
ax.set_ylabel("n")
ax.set_title("Manoeuvre Diagram")
def plot_diagrama_de_maniobras_con_flap(self, ax, dv):
ax.plot(np.arange(0, self.Vsf[self.units] + dv, dv), [self.n_stall_flap(vel) for vel in np.arange(0, self.Vsf[self.units] + dv, dv)],
color='b', linestyle='--')
ax.plot(np.arange(self.Vsf[self.units], self.Vf_n2[self.units] + dv, dv),
[self.n_stall_flap(vel) for vel in np.arange(self.Vsf[self.units], self.Vf_n2[self.units] + dv, dv)],
color='b', linestyle='-')
ax.plot([self.Vsf[self.units], self.Vsf[self.units]], [0.0, self.n_stall_flap(self.Vsf[self.units])], color='b', linestyle='-')
ax.plot([self.Vf_n2[self.units], self.Vf[self.units]], [2.0, 2.0], color='b', linestyle='-')
ax.plot([self.Vf[self.units], self.Vf[self.units]], [0.0, 2.0], color='b', linestyle='-')
ax.plot([self.Vsf[self.units], self.Vf[self.units]], [0.0, 0.0], color='b', linestyle='-')
ax.set_xlabel("Speed [{}]".format(self.vel_label[self.units]))
ax.set_ylabel("n")
ax.set_title("Manoeuvre Diagram")
def plot_diagrama_de_maniobras_y_rafagas(self, ax, dv):
# Calculo de las intersecciones:
if self.n_gust_pos(self.Va[self.units]) > self.n_max:
# extender stall hasta interseccion con gust y arrancar la comparacion desde ese punto
def func1(vel):
return self.n_gust_pos(vel) - self.n_stall_pos(vel)
v_intersec_pos = fsolve(func1, self.Va[self.units])[0]
else:
v_intersec_pos = self.Va[self.units]
if self.n_gust_pos(self.Vs0[self.units]) < -1.0:
# extender stall hasta interseccion con gust y arrancar la comparacion desde ese punto
def func2(vel):
return self.n_gust_neg(vel) - self.n_stall_neg(vel)
v_intersec_neg = fsolve(func2, self.Vs0[self.units])[0]
else:
v_intersec_neg = self.Vs0[self.units]
ax.fill_between(np.arange(0, v_intersec_pos, dv), 0,
[self.n_stall_pos(vel) for vel in np.arange(0, v_intersec_pos, dv)],
color='m', alpha=0.2)
ax.fill_between(np.arange(v_intersec_pos, self.Vd[self.units], dv), 0, [max(self.n_gust_pos(vel), self.n_manoeuvre_pos(vel))
for vel in
np.arange(v_intersec_pos, self.Vd[self.units], dv)],
color='m', alpha=0.2)
ax.fill_between(np.arange(0, v_intersec_neg, dv), 0,
[self.n_stall_neg(vel) for vel in np.arange(0, v_intersec_neg, dv)],
color='m', alpha=0.2)
ax.fill_between(np.arange(v_intersec_neg, self.Vd[self.units], dv), 0, [min(self.n_gust_neg(vel), self.n_manoeuvre_neg(vel))
for vel in
np.arange(v_intersec_neg, self.Vd[self.units], dv)],
color='m', alpha=0.2)
ax.fill_between([self.Vd[self.units], self.Vd[self.units]], 0, [max(self.n_manoeuvre_pos(self.Vd[self.units]), self.n_gust_pos(self.Vd[self.units])),
min(self.n_manoeuvre_neg(self.Vd[self.units]), self.n_gust_neg(self.Vd[self.units]))], color='m',
alpha=0.2)
ax.set_xlabel("Speed [{}]".format(self.vel_label[self.units]))
ax.set_ylabel("n")
ax.set_title("Combined Gust & Manoeuvre Diagram")
def parse():
parser = argparse.ArgumentParser(description='Plot Gust and Manoeuver diagrams')
parser.add_argument('--units', type=str, default='SI', choices=('SI', 'IM'), help='select units system')
parser.add_argument('-H', '--height', type=float, default=0.0, help='Select height')
parser.add_argument('-W', '--weight', type=float, help='select airplane weight')
parser.add_argument('--file', type=str, help='select Json file to read airplane data')
args = parser.parse_args()
return args
if __name__ == "__main__":
ft2m = 0.3048
lb2kg = 0.453592
args = parse()
units = args.units if args.units else 'SI'
h = {units: args.height}
if units == 'SI':
h['IM'] = h[units] / ft2m
else:
h['SI'] = h[units] * ft2m
if args.weight:
W = {units: args.weight}
if units == 'SI':
W['IM'] = W[units] / lb2kg
else:
W['SI'] = W[units] * lb2kg
else:
W = {'SI': 20000, 'IM': 20000 / lb2kg}
# Input Data:
if args.file:
with open(args.file, 'r') as fileID:
datos = json.load(fileID)
fileID.close()
else:
CAM = {'SI': 2.461}
CAM['IM'] = CAM['SI'] / ft2m
sw = {'SI': 60}
sw['IM'] = sw['SI'] / ft2m / ft2m
a3D = 5.0037 # 1/rad
MTOW = {'SI': 23000}
MTOW['IM'] = MTOW['SI'] / lb2kg
MLW = {'SI': 23000}
MLW['IM'] = MLW['SI'] / lb2kg
MZFW = {'SI': 16376.0}
MZFW['IM'] = MZFW['SI'] / lb2kg
Vc = {'SI': 151.93}
Vc['IM'] = Vc['SI'] / ft2m
clmax = 1.2463
clmax_flap = 1.499
clmin = -0.75 * clmax
Zmo = {'SI': 9999.2}
Zmo['IM'] = Zmo['SI'] / ft2m
datos = {
'CAM': CAM,
'sw': sw,
'a3D': a3D,
'MTOW': MTOW,
'MLW': MLW,
'MZFW': MZFW,
'Vc': Vc,
'clmax': clmax,
'clmax_flap': clmax,
'clmin': clmin,
'Zmo': Zmo
}
# Variables
den = {'SI': 1.225}
den['IM'] = den['SI'] / lb2kg * ft2m ** 3
diagrama = Diagramas(datos, W, h, den, units=units)
diagrama.calculos()
fig, ax1 = plt.subplots(nrows=1, ncols=1, sharex=True, sharey=True, squeeze=True)
diagrama.plot_diagrama_de_rafagas(ax1, 0.5)
fig, ax2 = plt.subplots(nrows=1, ncols=1, sharex=True, sharey=True, squeeze=True)
diagrama.plot_diagrama_de_maniobras(ax2, 0.5)
diagrama.plot_diagrama_de_maniobras_con_flap(ax2, 0.5)
fig, ax4 = plt.subplots(nrows=1, ncols=1, sharex=True, sharey=True, squeeze=True)
diagrama.plot_diagrama_de_maniobras_y_rafagas(ax4, 0.5)
plt.grid(True)
plt.show()
with open('airplane_data.json','w') as fileID:
json.dump(datos, fileID)
fileID.close()
|
enritoomey/DiagramaDeRafagasyManiobras
|
diagramas_class.py
|
Python
|
mit
| 20,658 | 0.004211 |
# -*- coding: utf-8 -*-
users = {
'Jean-jacques': ('12345678', 'api-key'),
}
|
Glandos/FreeMobile-SMS
|
config.sample.py
|
Python
|
mit
| 82 | 0 |
from django.conf import settings
from django.core.cache import cache
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.products.models import HOT_TOPIC_SLUG
from kitsune.products.tests import ProductFactory, TopicFactory
from kitsune.questions.models import QuestionLocale
from kitsune.search.tests.test_es import ElasticTestCase
from kitsune.sumo.urlresolvers import reverse
from kitsune.wiki.tests import DocumentFactory, ApprovedRevisionFactory, HelpfulVoteFactory
class ProductViewsTestCase(ElasticTestCase):
def test_products(self):
"""Verify that /products page renders products."""
# Create some products.
for i in range(3):
p = ProductFactory(visible=True)
l = QuestionLocale.objects.get(locale=settings.LANGUAGE_CODE)
p.questions_locales.add(l)
# GET the products page and verify the content.
r = self.client.get(reverse('products'), follow=True)
eq_(200, r.status_code)
doc = pq(r.content)
eq_(3, len(doc('#products-and-services li')))
def test_product_landing(self):
"""Verify that /products/<slug> page renders topics."""
# Create a product.
p = ProductFactory()
l = QuestionLocale.objects.get(locale=settings.LANGUAGE_CODE)
p.questions_locales.add(l)
# Create some topics.
TopicFactory(slug=HOT_TOPIC_SLUG, product=p, visible=True)
topics = TopicFactory.create_batch(11, product=p, visible=True)
# Create a document and assign the product and 10 topics.
d = DocumentFactory(products=[p], topics=topics[:10])
ApprovedRevisionFactory(document=d)
self.refresh()
# GET the product landing page and verify the content.
url = reverse('products.product', args=[p.slug])
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
doc = pq(r.content)
eq_(11, len(doc('#help-topics li')))
eq_(p.slug, doc('#support-search input[name=product]').attr['value'])
def test_firefox_product_landing(self):
"""Verify that there are no firefox button at header in the firefox landing page"""
p = ProductFactory(slug="firefox")
url = reverse('products.product', args=[p.slug])
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
doc = pq(r.content)
eq_(False, doc(".firefox-download-button").length)
def test_document_listing(self):
"""Verify /products/<product slug>/<topic slug> renders articles."""
# Create a topic and product.
p = ProductFactory()
t1 = TopicFactory(product=p)
# Create 3 documents with the topic and product and one without.
ApprovedRevisionFactory.create_batch(3, document__products=[p], document__topics=[t1])
ApprovedRevisionFactory()
self.refresh()
# GET the page and verify the content.
url = reverse('products.documents', args=[p.slug, t1.slug])
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
doc = pq(r.content)
eq_(3, len(doc('#document-list > ul > li')))
eq_(p.slug, doc('#support-search input[name=product]').attr['value'])
def test_document_listing_order(self):
"""Verify documents are sorted by display_order and number of helpful votes."""
# Create topic, product and documents.
p = ProductFactory()
t = TopicFactory(product=p)
docs = []
# FIXME: Can't we do this with create_batch and build the document
# in the approvedrevisionfactory
for i in range(3):
doc = DocumentFactory(products=[p], topics=[t])
ApprovedRevisionFactory(document=doc)
docs.append(doc)
# Add a lower display order to the second document. It should be first now.
docs[1].display_order = 0
docs[1].save()
self.refresh()
url = reverse('products.documents', args=[p.slug, t.slug])
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
doc = pq(r.content)
eq_(doc('#document-list > ul > li:first-child > a').text(),
docs[1].title)
# Add a helpful vote to the third document. It should be second now.
rev = docs[2].current_revision
HelpfulVoteFactory(revision=rev, helpful=True)
docs[2].save() # Votes don't trigger a reindex.
self.refresh()
cache.clear() # documents_for() is cached
url = reverse('products.documents', args=[p.slug, t.slug])
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
doc = pq(r.content)
eq_(doc('#document-list > ul > li:nth-child(2) > a').text(),
docs[2].title)
# Add 2 helpful votes the first document. It should be second now.
rev = docs[0].current_revision
HelpfulVoteFactory(revision=rev, helpful=True)
HelpfulVoteFactory(revision=rev, helpful=True)
docs[0].save() # Votes don't trigger a reindex.
self.refresh()
cache.clear() # documents_for() is cached
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
doc = pq(r.content)
eq_(doc('#document-list > ul > li:nth-child(2) > a').text(),
docs[0].title)
def test_subtopics(self):
"""Verifies subtopics appear on document listing page."""
# Create a topic and product.
p = ProductFactory()
t = TopicFactory(product=p, visible=True)
# Create a documents with the topic and product
doc = DocumentFactory(products=[p], topics=[t])
ApprovedRevisionFactory(document=doc)
self.refresh()
# GET the page and verify no subtopics yet.
url = reverse('products.documents', args=[p.slug, t.slug])
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
pqdoc = pq(r.content)
eq_(0, len(pqdoc('li.subtopic')))
# Create a subtopic, it still shouldn't show up because no
# articles are assigned.
subtopic = TopicFactory(parent=t, product=p, visible=True)
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
pqdoc = pq(r.content)
eq_(0, len(pqdoc('li.subtopic')))
# Add a document to the subtopic, now it should appear.
doc.topics.add(subtopic)
self.refresh()
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
pqdoc = pq(r.content)
eq_(1, len(pqdoc('li.subtopic')))
|
safwanrahman/kitsune
|
kitsune/products/tests/test_templates.py
|
Python
|
bsd-3-clause
| 6,625 | 0.001057 |
from __future__ import absolute_import
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.exceptions import APIException
class ResourceDoesNotExist(APIException):
status_code = status.HTTP_404_NOT_FOUND
class SentryAPIException(APIException):
code = ''
message = ''
def __init__(self, code=None, message=None, detail=None, **kwargs):
if detail is None:
detail = {
'code': code or self.code,
'message': message or self.message,
'extra': kwargs,
}
super(SentryAPIException, self).__init__(detail=detail)
class ProjectMoved(SentryAPIException):
status_code = status.HTTP_302_FOUND
# code/message currently don't get used
code = 'resource-moved'
message = 'Resource has been moved'
def __init__(self, new_url, slug):
super(ProjectMoved, self).__init__(
url=new_url,
slug=slug,
)
class SsoRequired(SentryAPIException):
status_code = status.HTTP_401_UNAUTHORIZED
code = 'sso-required'
message = 'Must login via SSO'
def __init__(self, organization):
super(SsoRequired, self).__init__(
loginUrl=reverse('sentry-auth-organization', args=[organization.slug])
)
class SuperuserRequired(SentryAPIException):
status_code = status.HTTP_403_FORBIDDEN
code = 'superuser-required'
message = 'You need to re-authenticate for superuser.'
class SudoRequired(SentryAPIException):
status_code = status.HTTP_401_UNAUTHORIZED
code = 'sudo-required'
message = 'Account verification required.'
def __init__(self, user):
super(SudoRequired, self).__init__(username=user.username)
class TwoFactorRequired(APIException):
status_code = status.HTTP_401_UNAUTHORIZED
code = '2fa-required'
message = 'Organization requires two-factor authentication to be enabled'
class InvalidRepository(Exception):
pass
|
ifduyue/sentry
|
src/sentry/api/exceptions.py
|
Python
|
bsd-3-clause
| 2,003 | 0.000499 |
import yeti
class ModuleUno(yeti.Module):
def module_init(self):
raise Exception()
|
Team4819/Yeti
|
tests/resources/engine/module2.py
|
Python
|
bsd-3-clause
| 96 | 0.010417 |
import matplotlib.pyplot as pl
import random as rnd
a = rnd.sample(range(10),10)
print([a])
pl.imshow([a])
|
JaeGyu/PythonEx_1
|
MatplotlibEx.py
|
Python
|
mit
| 116 | 0.051724 |
import time
import urllib2
from urllib2 import urlopen
import datetime
from sys import argv
website = argv[1]
topSplit = '<div class=\"post\">'
bottomSplit = '<div class=\"sp_right\">'
def main():
try:
sourceCode = urllib2.urlopen(website).read()
#print sourceCode
sourceSplit = sourceCode.split(topSplit)[1].split(bottomSplit)[0]
print sourceSplit
except Exception,e:
print 'failed in the main loop'
print str(e)
main()
|
genokan/Python-Learning
|
scraper.py
|
Python
|
gpl-2.0
| 443 | 0.031603 |
#!/usr/bin/python3
import exhibition
from data import TILE_SIZE
import pygame
import collections
import logging
log = logging.getLogger(__name__)
DEBUG_RENDER_COORDS = True
class Tile:
""" A tile represents one tile in an area's map.
It has an image, a position rectangle, and an optional collision rectangle.
An abstract base class. Child classes must define an image."""
def __init__(self, pos):
""" Initializes a tile with position. No image or collision rect set. """
self.tile_pos = pos
x, y = pos
self.rect = pygame.Rect(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE)
self.collision_rect = None
self.image = None
if DEBUG_RENDER_COORDS:
font = pygame.font.Font(None, 24)
self.coord_text = font.render("({}, {})".format(self.tile_pos[0], self.tile_pos[1]), True, (0, 0, 0, 100))
def render(self, camera):
""" Renders the map tile to the screen using the provided camera. """
screen = pygame.display.get_surface()
pos = camera.world_to_screen(self.rect.topleft)
screen.blit(self.image, pos)
if DEBUG_RENDER_COORDS:
x, y = pos
screen.blit(self.coord_text, (x + 4, y + 4))
##################################
class FloorTile(Tile):
def __init__(self, pos):
super().__init__(pos)
self.image = exhibition.images()["floor"]
class WallTile(Tile):
def __init__(self, pos):
super().__init__(pos)
self.collision_rect = self.rect
self.image = exhibition.images()["wall"]
class MissingTile(Tile):
def __init__(self, pos):
super().__init__(pos)
self.image = exhibition.images()["missing"]
log.error("Missing tile created at {}, {}".format(pos[0], pos[1]))
class VerticalDoorTile(Tile):
def __init__(self, pos):
super().__init__(pos)
self.image = exhibition.images()["vwalldoor"]
self.collision_rect = pygame.Rect(self.rect)
self.collision_rect.width /= 8
self.collision_rect.center = self.rect.center
# This tile mapping maps the integers in the map file format to the appropriate tile types.
# This dictionary IS the file format for the map.
tile_mapping = collections.defaultdict(MissingTile, {0: FloorTile, 1: WallTile, 2: VerticalDoorTile})
|
kjwilcox/digital_heist
|
src/tile.py
|
Python
|
gpl-2.0
| 2,393 | 0.006268 |
# -*- coding: cp1250 -*-
try:
import datetime
import time
except ImportError as err:
print("Error import module: " + str(err))
exit(128)
__author__ = 'kszalai'
class Timing:
def __init__(self):
self.start = time.clock()
def end(self):
elapsed = time.clock() - self.start
# return self.__seconds_to_str(elapsed)
return str(datetime.timedelta(seconds=elapsed))
def __seconds_to_str(self, t):
return "%d:%02d:%02d.%03d" % \
reduce(lambda ll, b: divmod(ll[0], b) + ll[1:],
[(t * 1000,), 1000, 60, 60])
|
KAMI911/histogrammer
|
libs/timing.py
|
Python
|
mpl-2.0
| 609 | 0 |
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from django.views.generic.base import TemplateView
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from autostew_web_session.models.models import Track
from autostew_web_session.models.session import SessionSetup, Session
from autostew_web_session.models.server import Server
from autostew_web_session.views import ParticipantDetailView, SessionList, TrackDetailView, SessionView
from . import views
app_name = 'session'
urlpatterns = [
url(r'^tracks/?$', ListView.as_view(model=Track), name='tracks'),
url(r'^tracks/(?P<pk>[0-9]+)/?$', TrackDetailView.as_view(), name='track'),
url(r'^list/?$', SessionList.as_view(), name='sessions'),
url(r'^servers/?$', ListView.as_view(model=Server), name='servers'),
url(r'^servers/(?P<slug>.+)/?$', DetailView.as_view(model=Server, slug_field='name'), name='server'),
url(r'^(?P<pk>[0-9]+)/?$', SessionView.as_view(), name='session'),
url(r'^(?P<pk>[0-9]+)/events/?$', views.SessionEvents.as_view(), name='events'),
url(r'^(?P<session_id>[0-9]+)/participant/(?P<participant_id>[0-9]+)/?$', ParticipantDetailView.as_view(), name='participant'),
url(r'^snapshot/(?P<pk>[0-9]+)/?$', SessionView.as_view(), name='snapshot'),
url(r'^setup/create/?$', login_required(views.CreateSessionView.as_view()), name='create_setup'),
url(r'^setup/list/?$', ListView.as_view(model=SessionSetup, queryset=SessionSetup.objects.filter(is_template=True)), name='setups'),
url(r'^setup/(?P<pk>[0-9]+)/?$', DetailView.as_view(model=SessionSetup), name='setup'),
]
|
Autostew/autostew
|
autostew_web_session/urls.py
|
Python
|
agpl-3.0
| 1,673 | 0.004782 |
import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate()
mobileTemplate.setCreatureName('frenzied_donkuwah')
mobileTemplate.setLevel(78)
mobileTemplate.setDifficulty(Difficulty.NORMAL)
mobileTemplate.setMinSpawnDistance(3)
mobileTemplate.setMaxSpawnDistance(5)
mobileTemplate.setDeathblow(True)
mobileTemplate.setSocialGroup('donkuwah tribe')
mobileTemplate.setAssistRange(1)
mobileTemplate.setOptionsBitmask(Options.AGGRESSIVE | Options.ATTACKABLE)
mobileTemplate.setStalker(True)
templates = Vector()
templates.add('object/mobile/shared_jinda_male.iff')
templates.add('object/mobile/shared_jinda_female.iff')
mobileTemplate.setTemplates(templates)
weaponTemplates = Vector()
weapontemplate = WeaponTemplate('object/weapon/melee/unarmed/shared_unarmed_default.iff', WeaponType.UNARMED, 1.0, 6, 'kinetic')
weaponTemplates.add(weapontemplate)
mobileTemplate.setWeaponTemplateVector(weaponTemplates)
attacks = Vector()
mobileTemplate.setDefaultAttack('meleeHit')
mobileTemplate.setAttacks(attacks)
lootPoolNames_1 = ['Junk']
lootPoolChances_1 = [100]
lootGroupChance_1 = 65
mobileTemplate.addToLootGroups(lootPoolNames_1,lootPoolChances_1,lootGroupChance_1)
lootPoolNames_2 = ['random_loot_primitives']
lootPoolChances_2 = [100]
lootGroupChance_2 = 35
mobileTemplate.addToLootGroups(lootPoolNames_2,lootPoolChances_2,lootGroupChance_2)
core.spawnService.addMobileTemplate('frenzied_donkuwah', mobileTemplate)
return
|
agry/NGECore2
|
scripts/mobiles/endor/frenzied_donkuwah.py
|
Python
|
lgpl-3.0
| 1,767 | 0.032258 |
try:
from urllib.parse import quote, urljoin
except ImportError:
from urllib import quote
from urlparse import urljoin
import requests
class BandsintownError(Exception):
def __init__(self, message, response=None):
self.message = message
self.response = response
def __str__(self):
return self.message
class BandsintownInvalidAppIdError(BandsintownError):
pass
class BandsintownInvalidDateFormatError(BandsintownError):
pass
class Client(object):
api_base_url = 'https://rest.bandsintown.com'
def __init__(self, app_id):
"""
Args:
app_id: Required app id, can be any string
"""
self.app_id = app_id
self.default_params = {'app_id': self.app_id}
def request(self, path, params={}):
"""
Executes a request to the Bandsintown API and returns the response
object from `requests`
Args:
path: The API path to append to the base API URL for the request
params: Optional dict to tack on query string parameters to request
Returns:
Response object from `requests`
"""
url = urljoin(self.api_base_url, path)
request_params = self.default_params.copy()
request_params.update(params)
response = requests.get(
url,
headers={'Accept': 'application/json'},
params=request_params
)
data = response.json()
if 'message' in data and data['message'] == 'Missing required request parameters: [app_id]':
message = 'Missing required API key, which must be a single string argument to Client instantiation, e.g.: client = Client("my-app-id")'
raise BandsintownInvalidAppIdError(message, response)
else:
return data
def artists(self, artistname):
"""
Searches for a single artist using this endpoint:
https://app.swaggerhub.com/apis/Bandsintown/PublicAPI/3.0.0#/single_artist_information/artist
Args:
artistname: Artist name to search for
Returns:
A dict of artist data when the artist is found, and returns
None when not found
Usage:
client = Client(app_id='my-app-id')
client.artists('Bad Religion')
"""
try:
return self.request('artists/%s' % quote(artistname))
except ValueError:
# Currently the API's response when the artist doesn't exist is
# badly formed JSON. In such a case, we're catching the exception
# and returning None
return None
def artists_events(self, artistname, date=None):
"""
Searches for events for a single artist, with an optional date range,
using this endpoint:
https://app.swaggerhub.com/apis/Bandsintown/PublicAPI/3.0.0#/upcoming_artist_events/artistEvents
Args:
artistname: Artist name to search for
date: Optional date string filter, can be a specific date in the
format: "yyyy-mm-dd", a range "yyyy-mm-dd,yyyy-mm-dd", or can be a
few keyword values like "upcoming" or "all"
Returns:
A list of event data, which could be empty, None if artist not
found, raises `BandsintownInvalidDateFormatError` for bad `date`
param, or raises `BandsintownError` for other unknown error
Usage:
client = Client(app_id=1234)
client.artists_events('Bad Religion')
client.artists_events('Bad Religion', date='2018-02-01,2018-02-28')
"""
params = {}
if date:
params['date'] = date
data = self.request('artists/%s/events' % quote(artistname), params)
if 'errors' in data:
if data['errors'][0] == 'Invalid date format':
raise BandsintownInvalidDateFormatError(
'Invalid date parameter: "%s", must be in the format: "yyyy-mm-dd", or "yyyy-mm-dd,yyyy-mm-dd" for a range, or keywords "upcoming" or "all"' % date
)
elif data['errors'][0] == 'Unknown Artist':
return None
else:
raise BandsintownError('Unknown error with request', data)
return data
|
jolbyandfriends/python-bandsintown
|
bandsintown/client.py
|
Python
|
mit
| 4,358 | 0.000688 |
#!/usr/bin/env python
"""
A script for automated nagging emails based on passed in queries
These can be collated into several 'queries' through the use of multiple query files with
a 'query_name' param set eg: 'Bugs tracked for Firefox Beta (13)'
Once the bugs have been collected from Bugzilla they are sorted into buckets cc: assignee manager
and to the assignee(s) or need-info? for each query
"""
import sys
import os
import smtplib
import subprocess
import tempfile
import collections
from datetime import datetime
from argparse import ArgumentParser
from auto_nag.bugzilla.agents import BMOAgent
import phonebook
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates'))
REPLY_TO_EMAIL = 'release-mgmt@mozilla.com'
DEFAULT_CC = ['release-mgmt@mozilla.com']
EMAIL_SUBJECT = ''
SMTP = 'smtp.mozilla.org'
# TODO - Sort by who a bug is blocked on (thanks @dturner)
# TODO - write tests!
# TODO - look into knocking out duplicated bugs in queries -- perhaps print out if there are dupes in queries when queries > 1
# TODO - should compare bugmail from API results to phonebook bugmail in to_lower()
def get_last_manager_comment(comments, manager, person):
# go through in reverse order to get most recent
for comment in comments[::-1]:
if person is not None:
if comment.creator.name == manager['mozillaMail'] or comment.creator.name == manager['bugzillaEmail']:
return comment.creation_time.replace(tzinfo=None)
return None
def get_last_assignee_comment(comments, person):
# go through in reverse order to get most recent
for comment in comments[::-1]:
if person is not None:
if comment.creator.name == person['mozillaMail'] or comment.creator.name == person['bugzillaEmail']:
return comment.creation_time.replace(tzinfo=None)
return None
def query_url_to_dict(url):
if (';')in url:
fields_and_values = url.split("?")[1].split(";")
else:
fields_and_values = url.split("?")[1].split("&")
d = collections.defaultdict(list)
for pair in fields_and_values:
(key, val) = pair.split("=")
if key != "list_id":
d[key].append(val)
return d
def generateEmailOutput(subject, queries, template, people, show_comment=False,
manager_email=None, rollup=False, rollupEmail=None):
cclist = []
toaddrs = []
template_params = {}
# stripping off the templates dir, just in case it gets passed in the args
template = env.get_template(template.replace('templates/', '', 1))
def addToAddrs(bug):
if bug.assigned_to.name in people.people_by_bzmail:
person = dict(people.people_by_bzmail[bug.assigned_to.name])
if person['mozillaMail'] not in toaddrs:
toaddrs.append(person['mozillaMail'])
for query in queries.keys():
# Avoid dupes in the cclist from several queries
query_cc = queries[query].get('cclist', [])
for qcc in query_cc:
if qcc not in cclist:
cclist.append(qcc)
if query not in template_params:
template_params[query] = {'buglist': []}
if len(queries[query]['bugs']) != 0:
for bug in queries[query]['bugs']:
if 'show_summary' in queries[query]:
if queries[query]['show_summary'] == '1':
summary = bug.summary
else:
summary = ""
else:
summary = ""
template_params[query]['buglist'].append(
{
'id': bug.id,
'summary': summary,
# 'comment': bug.comments[-1].creation_time.replace(tzinfo=None),
'assignee': bug.assigned_to.real_name,
'flags': bug.flags
}
)
# more hacking for JS special casing
if bug.assigned_to.name == 'general@js.bugs' and 'nihsanullah@mozilla.com' not in toaddrs:
toaddrs.append('nihsanullah@mozilla.com')
# if needinfo? in flags, add the flag.requestee to the toaddrs instead of bug assignee
if bug.flags:
for flag in bug.flags:
if 'needinfo' in flag.name and flag.status == '?':
try:
person = dict(people.people_by_bzmail[str(flag.requestee)])
if person['mozillaMail'] not in toaddrs:
toaddrs.append(person['mozillaMail'])
except:
if str(flag.requestee) not in toaddrs:
toaddrs.append(str(flag.requestee))
else:
addToAddrs(bug)
else:
addToAddrs(bug)
message_body = template.render(queries=template_params, show_comment=show_comment)
if manager_email is not None and manager_email not in cclist:
cclist.append(manager_email)
# no need to and cc the manager if more than one email
if len(toaddrs) > 1:
for email in toaddrs:
if email in cclist:
toaddrs.remove(email)
if cclist == ['']:
cclist = None
if rollup:
joined_to = ",".join(rollupEmail)
else:
joined_to = ",".join(toaddrs)
message = (
"From: %s\r\n" % REPLY_TO_EMAIL
+ "To: %s\r\n" % joined_to
+ "CC: %s\r\n" % ",".join(cclist)
+ "Subject: %s\r\n" % subject
+ "\r\n"
+ message_body)
toaddrs = toaddrs + cclist
return toaddrs, message
def sendMail(toaddrs, msg, username, password, dryrun=False):
if dryrun:
print "\n****************************\n* DRYRUN: not sending mail *\n****************************\n"
print msg
else:
server = smtplib.SMTP_SSL(SMTP, 465)
server.set_debuglevel(1)
server.login(username, password)
# note: toaddrs is required for transport agents, the msg['To'] header is not modified
server.sendmail(username, toaddrs, msg)
server.quit()
if __name__ == '__main__':
parser = ArgumentParser(__doc__)
parser.set_defaults(
dryrun=False,
username=None,
password=None,
roll_up=False,
show_comment=False,
email_cc_list=None,
queries=[],
days_since_comment=-1,
verbose=False,
keywords=None,
email_subject=None,
no_verification=False,
)
parser.add_argument("-d", "--dryrun", dest="dryrun", action="store_true",
help="just do the query, and print emails to console without emailing anyone")
parser.add_argument("-m", "--mozilla-email", dest="mozilla_mail",
help="specify a specific address for sending email"),
parser.add_argument("-p", "--email-password", dest="email_password",
help="specify a specific password for sending email")
parser.add_argument("-b", "--bz-api-key", dest="bz_api_key",
help="Bugzilla API key")
parser.add_argument("-t", "--template", dest="template",
required=True,
help="template to use for the buglist output")
parser.add_argument("-e", "--email-cc-list", dest="email_cc_list",
action="append",
help="email addresses to include in cc when sending mail")
parser.add_argument("-q", "--query", dest="queries",
action="append",
required=True,
help="a file containing a dictionary of a bugzilla query")
parser.add_argument("-k", "--keyword", dest="keywords",
action="append",
help="keywords to collate buglists")
parser.add_argument("-s", "--subject", dest="email_subject",
required=True,
help="The subject of the email being sent")
parser.add_argument("-r", "--roll-up", dest="roll_up", action="store_true",
help="flag to get roll-up output in one email instead of creating multiple emails")
parser.add_argument("--show-comment", dest="show_comment", action="store_true",
help="flag to display last comment on a bug in the message output")
parser.add_argument("--days-since-comment", dest="days_since_comment",
help="threshold to check comments against to take action based on days since comment")
parser.add_argument("--verbose", dest="verbose", action="store_true",
help="turn on verbose output")
parser.add_argument("--no-verification", dest="no_verification", action="store_true",
help="don't wait for human verification of every email")
options, args = parser.parse_known_args()
people = phonebook.PhonebookDirectory(dryrun=options.dryrun)
try:
int(options.days_since_comment)
except:
if options.days_since_comment is not None:
parser.error("Need to provide a number for days \
since last comment value")
if options.email_cc_list is None:
options.email_cc_list = DEFAULT_CC
# Load our agent for BMO
bmo = BMOAgent(options.bz_api_key)
# Get the buglist(s)
collected_queries = {}
for query in options.queries:
# import the query
if os.path.exists(query):
info = {}
execfile(query, info)
query_name = info['query_name']
if query_name not in collected_queries:
collected_queries[query_name] = {
'channel': info.get('query_channel', ''),
'bugs': [],
'show_summary': info.get('show_summary', 0),
'cclist': options.email_cc_list,
}
if 'cc' in info:
for c in info.get('cc').split(','):
collected_queries[query_name]['cclist'].append(c)
if 'query_params' in info:
print "Gathering bugs from query_params in %s" % query
collected_queries[query_name]['bugs'] = bmo.get_bug_list(info['query_params'])
elif 'query_url' in info:
print "Gathering bugs from query_url in %s" % query
collected_queries[query_name]['bugs'] = bmo.get_bug_list(query_url_to_dict(info['query_url']))
# print "DEBUG: %d bug(s) found for query %s" % \
# (len(collected_queries[query_name]['bugs']), info['query_url'])
else:
print "Error - no valid query params or url in the config file"
sys.exit(1)
else:
print "Not a valid path: %s" % query
total_bugs = 0
for channel in collected_queries.keys():
total_bugs += len(collected_queries[channel]['bugs'])
print "Found %s bugs total for %s queries" % (total_bugs, len(collected_queries.keys()))
print "Queries to collect: %s" % collected_queries.keys()
managers = people.managers
manual_notify = {}
counter = 0
def add_to_managers(manager_email, query, info={}):
if manager_email not in managers:
managers[manager_email] = {}
managers[manager_email]['nagging'] = {query: {'bugs': [bug],
'show_summary': info.get('show_summary', 0),
'cclist': info.get('cclist', [])}, }
return
if 'nagging' in managers[manager_email]:
if query in managers[manager_email]['nagging']:
managers[manager_email]['nagging'][query]['bugs'].append(bug)
if options.verbose:
print "Adding %s to %s in nagging for %s" % \
(bug.id, query, manager_email)
else:
managers[manager_email]['nagging'][query] = {
'bugs': [bug],
'show_summary': info.get('show_summary', 0),
'cclist': info.get('cclist', [])
}
if options.verbose:
print "Adding new query key %s for bug %s in nagging \
and %s" % (query, bug.id, manager_email)
else:
managers[manager_email]['nagging'] = {query: {'bugs': [bug],
'show_summary': info.get('show_summary', 0),
'cclist': info.get('cclist', [])}, }
if options.verbose:
print "Creating query key %s for bug %s in nagging and \
%s" % (query, bug.id, manager_email)
for query, info in collected_queries.items():
if len(collected_queries[query]['bugs']) != 0:
manual_notify[query] = {'bugs': [], 'show_summary': info.get('show_summary', 0)}
for b in collected_queries[query]['bugs']:
counter = counter + 1
send_mail = True
bug = bmo.get_bug(b.id)
manual_notify[query]['bugs'].append(bug)
assignee = bug.assigned_to.name
if "@" not in assignee:
print "Error - email address expect. Found '" + assignee + "' instead"
print "Check that the authentication worked correctly"
sys.exit(1)
if assignee in people.people_by_bzmail:
person = dict(people.people_by_bzmail[assignee])
else:
person = None
# kick bug out if days since comment check is on
if options.days_since_comment != -1:
# try to get last_comment by assignee & manager
if person is not None:
last_comment = get_last_assignee_comment(bug.comments, person)
if 'manager' in person and person['manager'] is not None:
manager_email = person['manager']['dn'].split('mail=')[1].split(',')[0]
manager = people.people[manager_email]
last_manager_comment = get_last_manager_comment(bug.comments,
people.people_by_bzmail[manager['bugzillaEmail']],
person)
# set last_comment to the most recent of last_assignee and last_manager
if last_manager_comment is not None and last_comment is not None and last_manager_comment > last_comment:
last_comment = last_manager_comment
# otherwise just get the last comment
else:
last_comment = bug.comments[-1].creation_time.replace(tzinfo=None)
if last_comment is not None:
timedelta = datetime.now() - last_comment
if timedelta.days <= int(options.days_since_comment):
if options.verbose:
print "Skipping bug %s since it's had an assignee or manager comment within the past %s days" % (bug.id, options.days_since_comment)
send_mail = False
counter = counter - 1
manual_notify[query]['bugs'].remove(bug)
else:
if options.verbose:
print "This bug needs notification, it's been %s since last comment of note" % timedelta.days
if send_mail:
if 'nobody' in assignee:
if options.verbose:
print "No one assigned to: %s, will be in the manual notification list..." % bug.id
# TODO - get rid of this, SUCH A HACK!
elif 'general@js.bugs' in assignee:
if options.verbose:
print "No one assigned to JS bug: %s, adding to Naveed's list..." % bug.id
add_to_managers('nihsanullah@mozilla.com', query, info)
else:
if bug.assigned_to.real_name is not None:
if person is not None:
# check if assignee is already a manager, add to their own list
if 'mozillaMail' in managers:
add_to_managers(person['mozillaMail'], query, info)
# otherwise we search for the assignee's manager
else:
# check for manager key first, a few people don't have them
if 'manager' in person and person['manager'] is not None:
manager_email = person['manager']['dn'].split('mail=')[1].split(',')[0]
if manager_email in managers:
add_to_managers(manager_email, query, info)
elif manager_email in people.vices:
# we're already at the highest level we'll go
if assignee in managers:
add_to_managers(assignee, query, info)
else:
if options.verbose:
print "%s has a V-level for a manager, and is not in the manager list" % assignee
managers[person['mozillaMail']] = {}
add_to_managers(person['mozillaMail'], query, info)
else:
# try to go up one level and see if we find a manager
if manager_email in people.people:
person = dict(people.people[manager_email])
manager_email = person['manager']['dn'].split('mail=')[1].split(',')[0]
if manager_email in managers:
add_to_managers(manager_email, query, info)
else:
print "Manager could not be found: %s" % manager_email
# if you don't have a manager listed, but are an employee, we'll nag you anyway
else:
add_to_managers(person['mozillaMail'], query, info)
print "%s's entry doesn't list a manager! Let's ask them to update phonebook but in the meantime they get the email directly." % person['name']
if options.roll_up:
# only send one email
toaddrs, msg = generateEmailOutput(subject=options.email_subject,
queries=manual_notify,
template=options.template,
people=people,
show_comment=options.show_comment,
rollup=options.roll_up,
rollupEmail=options.email_cc_list)
if options.email_password is None or options.mozilla_mail is None:
print "Please supply a username/password (-m, -p) for sending email"
sys.exit(1)
if not options.dryrun:
print "SENDING EMAIL"
sendMail(toaddrs, msg, options.mozilla_mail, options.email_password, options.dryrun)
else:
# Get yr nag on!
for email, info in managers.items():
inp = ''
if 'nagging' in info:
toaddrs, msg = generateEmailOutput(
subject=options.email_subject,
manager_email=email,
queries=info['nagging'],
people=people,
template=options.template,
show_comment=options.show_comment)
while True and not options.no_verification:
print "\nRelMan Nag is ready to send the following email:\n<------ MESSAGE BELOW -------->"
print msg
print "<------- END MESSAGE -------->\nWould you like to send now?"
inp = raw_input('\n Please select y/Y to send, v/V to edit, or n/N to skip and continue to next email: ')
if inp != 'v' and inp != 'V':
break
tempfilename = tempfile.mktemp()
temp_file = open(tempfilename, 'w')
temp_file.write(msg)
temp_file.close()
subprocess.call(['vi', tempfilename])
temp_file = open(tempfilename, 'r')
msg = temp_file.read()
toaddrs = msg.split("To: ")[1].split("\r\n")[0].split(',') + msg.split("CC: ")[1].split("\r\n")[0].split(',')
os.remove(tempfilename)
if inp == 'y' or inp == 'Y' or options.no_verification:
if options.email_password is None or options.mozilla_mail is None:
print "Please supply a username/password (-m, -p) for sending email"
sys.exit(1)
if not options.dryrun:
print "SENDING EMAIL"
sendMail(toaddrs, msg, options.mozilla_mail, options.email_password, options.dryrun)
sent_bugs = 0
for query, info in info['nagging'].items():
sent_bugs += len(info['bugs'])
# take sent bugs out of manual notification list
for bug in info['bugs']:
manual_notify[query]['bugs'].remove(bug)
counter = counter - sent_bugs
if not options.roll_up:
emailed_bugs = []
# Send RelMan the manual notification list only when there are bugs that didn't go out
msg_body = """\n******************************************\nNo nag emails were generated for these bugs because
they are either assigned to no one or to non-employees (though ni? on non-employees will get nagged).
\nYou will need to look at the following bugs:\n******************************************\n\n"""
for k, v in manual_notify.items():
if len(v['bugs']) != 0:
for bug in v['bugs']:
if bug.id not in emailed_bugs:
if k not in msg_body:
msg_body += "\n=== %s ===\n" % k
emailed_bugs.append(bug.id)
msg_body += "http://bugzil.la/" + "%s -- assigned to: %s\n -- Last commented on: %s\n" % (bug.id, bug.assigned_to.real_name, bug.comments[-1].creation_time.replace(tzinfo=None))
msg = ("From: %s\r\n" % REPLY_TO_EMAIL
+ "To: %s\r\n" % REPLY_TO_EMAIL
+ "Subject: RelMan Attention Needed: %s\r\n" % options.email_subject
+ "\r\n"
+ msg_body)
sendMail(['release-mgmt@mozilla.com'], msg, options.mozilla_mail, options.email_password, options.dryrun)
|
anoopvalluthadam/bztools
|
auto_nag/scripts/email_nag.py
|
Python
|
bsd-3-clause
| 24,245 | 0.003465 |
#!/usr/bin/env python2
from os import listdir
from os.path import isfile, isdir, join, dirname
from re import sub
from urllib import urlopen
from subprocess import Popen, PIPE
from configparser import ConfigParser
import fcntl, socket, struct
def getHwAddr(ifname):
"""The pure python solution for this problem under Linux to get the MAC for a specific local interface,
originally posted as a comment by vishnubob and improved by on Ben Mackey in http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15]))
return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]
def bonding(config):
try:
out, err = Popen([config['binaries']['quattor-query'], "/hardware/name"], stdout=PIPE).communicate()
system_id = out.splitlines()[-1].split("'")[1].replace('system','')
except:
system_id = False
mac_addresses = {}
if system_id:
record = {
"systemId" : system_id,
"bonds" : {}
}
if isdir(config['paths']['bonding']):
bonds = listdir(config['paths']['bonding'])
if bonds:
for bond in bonds:
bond_file = join(config['paths']['bonding'],bond)
if isfile(bond_file) and 'bond' in bond:
# Read bond information and tokenise
fh = open(bond_file)
data = fh.read()
fh.close()
data = data.splitlines()
data = [ l.split(': ', 1) for l in data ]
# Initialise structure
sections = [{}]
for line in data:
if len(line) == 2:
key, value = line
# Munge the keys slightly
key = sub(r'\(.+\)', '', key)
key = key.title().replace(' ', '')
sections[-1][key] = value
else:
sections.append({})
record["bonds"][bond] = sections
# Store the mac addresses behind bonded links for later use
for section in sections:
if 'PermanentHwAddr' in section:
mac_addresses[section['SlaveInterface']] = section['PermanentHwAddr']
print "Submitting bonding data to MagDB."
record = str(record).replace("'", '"')
try:
f = urlopen(config['urls']['bonding'], "system="+system_id+"&record="+record)
print "MagDB says: " + f.read()
except IOError:
print "Unable to submit results to MagDB"
else:
print "No network bonds found."
else:
print "No bonding information on system."
else:
print "Unable to determine systemId, will not look for network bonds."
return mac_addresses
def lldp(config, mac_addresses):
try:
out, err = Popen([config['binaries']['lldpctl'], "-f", "keyvalue"], stdout=PIPE).communicate()
except:
out = False
if out:
out = out.split('\n')[:-1]
data = []
for line in out:
if 'via=LLDP' in line:
data.append({})
if 'unknown-tlvs' in line:
continue
key, value = line.split('=')
key = key.split('.')[1:]
leaf = data[-1]
for k in key[:-1]:
if k not in leaf:
leaf[k] = {}
leaf = leaf[k]
leaf[key[-1]] = value.replace("'", "`")
# Initialise structure
record = []
for d in data:
link = {}
rid = 0
for k, v in d.iteritems():
rid = int(v['rid'])
# If the port is a member of a bonded link, the apparent mac address may have changed therefore we should use the mac address behind the bond
if k in mac_addresses:
mac = mac_addresses[k]
else:
mac = getHwAddr(k)
link[mac] = v
link[mac]['name'] = k
if rid <= 1:
record.append(link)
print "Submitting LLDP data to MagDB."
record = str(record).replace("'", '"')
try:
f = urlopen(config['urls']['lldp'], "record="+record)
print "MagDB says: " + f.read()
except IOError:
print "Unable to submit results to MagDB"
else:
print "No LLDP data found."
print "Complete."
def main():
config = ConfigParser()
config.read(['/etc/magdb-discover.conf', join(dirname(__file__), 'magdb-discover.conf')])
mac_addresses = bonding(config)
lldp(config, mac_addresses)
if __name__ == "__main__":
main()
|
stfc/MagDB
|
client/magdb-discover.py
|
Python
|
apache-2.0
| 5,206 | 0.00365 |
from mrjob.job import MRJob
from mrjob.protocol import JSONValueProtocol
import json
class WordCount(MRJob):
'''
The default MRJob.INPUT_PROTOCOL is `RawValueProtocol`, but we are reading tweets,
so we'll add a parser before we even get to the mapper.
'''
# incoming line needs to be parsed (I think), so we set a protocol to do so
INPUT_PROTOCOL = JSONValueProtocol
def mapper(self, key, line):
'''The key to the first mapper in the step-pipeline is always None.'''
# GNIP-style streams sometimes have metadata lines, but we can just ignore them
if 'info' in line and line['info']['message'] == 'Replay Request Completed':
return
# GNIP-style tweets have the tweet text in {'body': '...'} instead of the standard {'text': '...'}
if 'body' not in line:
raise Exception('Missing body field in tweet:\n ' + json.dumps(line))
text = line['body']
yield '~~~TOTAL~~~', 1
for token in text.split():
yield token.lower(), 1
def combiner(self, key, value_iter):
yield key, sum(value_iter)
def reducer(self, key, value_iter):
yield key, sum(value_iter)
if __name__ == '__main__':
WordCount.run()
|
dssg/tweedr
|
tweedr/emr/gnip_wc.py
|
Python
|
mit
| 1,253 | 0.00399 |
#!/usr/bin/env python
import sys
import os
os.environ['MPLCONFIGDIR'] = "/tmp/"
import pandas as pd
import numpy as np
import commands
import csv
from sklearn import svm
from sklearn.cross_validation import StratifiedKFold
from sklearn import preprocessing
from sklearn.externals import joblib
current_key = None
key = None
dayList = []
def qt_rmvd( string ):
string = string.strip()
if string.startswith("'") and string.endswith("'"):
string = string[1:-1]
return string
for line in sys.stdin:
# remove leading and trailing whitespace
line = line.strip()
# parse the input we got from mapper.py
key, values = line.split('\t', 1)
values = values[1:-1]
values = values.split(",")
day = qt_rmvd(values[0])
values = values[1:]
#print line, key, day ,values
#print key
#continue
if current_key is None:
current_key = key
if current_key == key:
dayList.append([day,qt_rmvd(values[0])])
else:
dayList.sort(key= lambda x: int(x[0].split("_")[-1]))
fname = "Event_DailyRecord_"+current_key.strip()+".csv"
f = open(fname,"wt")
w = csv.writer(f)
w.writerow(("Day","Event"))
for elem in dayList:
w.writerow((elem[0],elem[1]))
f.close()
#print commands.getoutput("ls")
#print commands.getoutput("hadoop fs -rm /user/dropuser/schlumberger-result/"+fname)
print commands.getoutput("hadoop fs -put "+fname+" /user/dropuser/schlumberger-result/")
dayList = []
current_key = key
dayList.append([day,qt_rmvd(values[0])])
if len(dayList) > 0:
dayList.sort(key= lambda x: int(x[0].split("_")[-1]))
fname = "Event_DailyRecord_"+current_key.strip()+".csv"
f = open(fname,"wt")
w = csv.writer(f)
w.writerow(("Day","Event"))
for elem in dayList:
w.writerow((elem[0],elem[1]))
f.close()
#print commands.getoutput("ls")
#print commands.getoutput("hadoop fs -rm /user/dropuser/schlumberger-result/"+fname)
print commands.getoutput("hadoop fs -put "+fname+" /user/dropuser/schlumberger-result/")
|
WiproOpenSourcePractice/bdreappstore
|
enu/real_time_event_detection/hadoopstream/reducer_post.py
|
Python
|
apache-2.0
| 2,141 | 0.015413 |
# encoding: utf-8
from __future__ import unicode_literals
from ..compat import compat_urllib_parse
from .common import InfoExtractor
from ..utils import (
parse_duration,
int_or_none,
ExtractorError,
)
class Porn91IE(InfoExtractor):
IE_NAME = '91porn'
_VALID_URL = r'(?:https?://)(?:www\.|)91porn\.com/.+?\?viewkey=(?P<id>[\w\d]+)'
_TEST = {
'url': 'http://91porn.com/view_video.php?viewkey=7e42283b4f5ab36da134',
'md5': '6df8f6d028bc8b14f5dbd73af742fb20',
'info_dict': {
'id': '7e42283b4f5ab36da134',
'title': '18岁大一漂亮学妹,水嫩性感,再爽一次!',
'ext': 'mp4',
'duration': 431,
}
}
def _real_extract(self, url):
video_id = self._match_id(url)
url = 'http://91porn.com/view_video.php?viewkey=%s' % video_id
self._set_cookie('91porn.com', 'language', 'cn_CN')
webpage = self._download_webpage(url, video_id, 'get HTML content')
if '作为游客,你每天只可观看10个视频' in webpage:
raise ExtractorError('91 Porn says: Daily limit 10 videos exceeded', expected=True)
title = self._search_regex(
r'<div id="viewvideo-title">([^<]+)</div>', webpage, 'title')
title = title.replace('\n', '')
# get real url
file_id = self._search_regex(
r'so.addVariable\(\'file\',\'(\d+)\'', webpage, 'file id')
sec_code = self._search_regex(
r'so.addVariable\(\'seccode\',\'([^\']+)\'', webpage, 'sec code')
max_vid = self._search_regex(
r'so.addVariable\(\'max_vid\',\'(\d+)\'', webpage, 'max vid')
url_params = compat_urllib_parse.urlencode({
'VID': file_id,
'mp4': '1',
'seccode': sec_code,
'max_vid': max_vid,
})
info_cn = self._download_webpage(
'http://91porn.com/getfile.php?' + url_params, video_id,
'get real video url')
video_url = self._search_regex(r'file=([^&]+)&', info_cn, 'url')
duration = parse_duration(self._search_regex(
r'时长:\s*</span>\s*(\d+:\d+)', webpage, 'duration', fatal=False))
comment_count = int_or_none(self._search_regex(
r'留言:\s*</span>\s*(\d+)', webpage, 'comment count', fatal=False))
return {
'id': video_id,
'title': title,
'url': video_url,
'duration': duration,
'comment_count': comment_count,
}
|
apllicationCOM/youtube-dl-api-server
|
youtube_dl_server/youtube_dl/extractor/porn91.py
|
Python
|
unlicense
| 2,548 | 0.000808 |
import sys
sys.path.append('../..')
import codestudio
z = codestudio.load('s1level108')
z.speed = 'faster'
def draw_tree(depth,branches):
if depth > 0:
z.color = z.random_color()
z.move_forward(7*depth)
z.turn_left(130)
for count in range(branches):
z.turn_right(180/branches)
draw_tree(depth-1,branches)
z.turn_left(50)
z.jump_backward(7*depth)
draw_tree(9,2)
z.wait()
|
skilstak/code-dot-org-python
|
solutions/stage19-artist5/s1level108.py
|
Python
|
unlicense
| 449 | 0.013363 |
#!/usr/bin/env python
import warnings as _warnings
_warnings.resetwarnings()
_warnings.filterwarnings('error')
from tdi.tools import javascript
x = javascript.escape_string(u'\xe9--"\'\\-----]]></script>')
print type(x).__name__, x
x = javascript.escape_string(u'\xe9---"\'\\----]]></script>', inlined=False)
print type(x).__name__, x
x = javascript.escape_string('\xe9--"\'\\-----]]></script>')
print type(x).__name__, x
x = javascript.escape_string('\xe9---"\'\\----]]></script>', inlined=False)
print type(x).__name__, x
try:
x = javascript.escape_string('\xe9--"\'\\-----]]></script>',
encoding='utf-8'
)
except UnicodeError:
print "UnicodeError - OK"
try:
x = javascript.escape_string('\xe9--"\'\\-----]]></script>',
inlined=False, encoding='utf-8'
)
except UnicodeError:
print "UnicodeError - OK"
x = javascript.escape_string('\xc3\xa9---"\'\\----]]></script>',
encoding='utf-8'
)
print type(x).__name__, x
x = javascript.escape_string('\xc3\xa9---"\'\\----]]></script>',
inlined=False, encoding='utf-8'
)
print type(x).__name__, x
# Bigunicode test: 𝔞 - MATHEMATICAL FRAKTUR SMALL A
# 1st: the real character must be replaced by surrogates.
# 2nd: The unreal one must stay.
a, s = u'a', u'\\'
for u in ('5\xd8\x1e\xdd'.decode("utf-16-le"), u'\\U0001d51e'):
for c in xrange(5):
x = javascript.escape_string(s * c + u + u'--"\'\\-----]]></script>')
print type(x).__name__, x
x = javascript.escape_string(s * c + u + u'--"\'\\-----]]></script>',
inlined=False
)
print type(x).__name__, x
x = javascript.escape_string(a + s * c + u + u'-"\'\\---]]></script>')
print type(x).__name__, x
x = javascript.escape_string(a + s * c + u + u'-"\'\\---]]></script>',
inlined = False
)
print type(x).__name__, x
|
ndparker/tdi
|
tests/tools/js_escape_string.py
|
Python
|
apache-2.0
| 1,877 | 0.007991 |
names = list()
times = list()
keys = list()
names.append("HeadPitch")
times.append([0.96, 1.68, 3.28, 3.96, 4.52, 5.08])
keys.append([-0.0261199, 0.427944, 0.308291, 0.11194, -0.013848, 0.061318])
names.append("HeadYaw")
times.append([0.96, 1.68, 3.28, 3.96, 4.52, 5.08])
keys.append([-0.234743, -0.622845, -0.113558, -0.00617796, -0.027654, -0.036858])
names.append("LElbowRoll")
times.append([0.8, 1.52, 3.12, 3.8, 4.36, 4.92])
keys.append([-0.866668, -0.868202, -0.822183, -0.992455, -0.966378, -0.990923])
names.append("LElbowYaw")
times.append([0.8, 1.52, 3.12, 3.8, 4.36, 4.92])
keys.append([-0.957257, -0.823801, -1.00788, -0.925044, -1.24412, -0.960325])
names.append("LHand")
times.append([1.52, 3.12, 3.8, 4.92])
keys.append([0.132026, 0.132026, 0.132026, 0.132026])
names.append("LShoulderPitch")
times.append([0.8, 1.52, 3.12, 3.8, 4.36, 4.92])
keys.append([0.863599, 0.858999, 0.888144, 0.929562, 1.017, 0.977116])
names.append("LShoulderRoll")
times.append([0.8, 1.52, 3.12, 3.8, 4.36, 4.92])
keys.append([0.286815, 0.230059, 0.202446, 0.406468, 0.360449, 0.31903])
names.append("LWristYaw")
times.append([1.52, 3.12, 3.8, 4.92])
keys.append([0.386526, 0.386526, 0.386526, 0.386526])
names.append("RElbowRoll")
times.append([0.64, 1.36, 2.96, 3.64, 4.2, 4.76])
keys.append([1.28093, 1.39752, 1.57239, 1.24105, 1.22571, 0.840674])
names.append("RElbowYaw")
times.append([0.64, 1.36, 2.96, 3.64, 4.2, 4.76])
keys.append([-0.128898, -0.285367, -0.15651, 0.754686, 1.17193, 0.677985])
names.append("RHand")
times.append([1.36, 2.96, 3.64, 4.76])
keys.append([0.166571, 0.166208, 0.166571, 0.166208])
names.append("RShoulderPitch")
times.append([0.64, 1.36, 2.96, 3.64, 4.2, 4.76])
keys.append([0.0767419, -0.59515, -0.866668, -0.613558, 0.584497, 0.882091])
names.append("RShoulderRoll")
times.append([0.64, 1.36, 2.96, 3.64, 4.2, 4.76])
keys.append([-0.019984, -0.019984, -0.615176, -0.833004, -0.224006, -0.214801])
names.append("RWristYaw")
times.append([1.36, 2.96, 3.64, 4.76])
keys.append([-0.058334, -0.0521979, -0.067538, -0.038392])
def run_animation(motion):
"""Use the motion module to run the angular interpolations and execute the animation
:param motion: the ALMotion module
:return the id of the request
"""
# Request the execution of the animation
motion_id = motion.post.angleInterpolation(names, keys, times, True)
return motion_id
|
davinellulinvega/COM1005
|
Lab8/wipe.py
|
Python
|
gpl-3.0
| 2,414 | 0.000829 |
from interpreter.heap import stringify
from interpreter.interpret import DTREE, CTREE
class execute():
def __init__( self, program ):
self.len = 0
self.heap = {}
self.stack = []
H = "H" + str( self.len )
self.heap[H] = { "$": "nil" }
self.len = self.len + 1
self.stack.append( H )
for declaration in program[0]: DTREE( self, declaration )
for command in program[1]: CTREE( self, command )
stringify( self )
|
brian-joseph-petersen/oply
|
interpreter/execute.py
|
Python
|
mit
| 503 | 0.035785 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_pyramid_sendgrid_webhooks
----------------------------------
Tests for `pyramid_sendgrid_webhooks` module.
"""
from __future__ import unicode_literals
import unittest
import pyramid_sendgrid_webhooks as psw
from pyramid_sendgrid_webhooks import events, errors
class EventGrabber(object):
""" Grabs events as they're dispatched """
def __init__(self):
self.events = []
self.last = None
def __call__(self, event):
self.events.append(event)
self.last = event
def simple_app(global_config, **settings):
from pyramid.config import Configurator
config = Configurator(settings=settings)
config.include('pyramid_sendgrid_webhooks', WebhookTestBase._PREFIX)
config.registry.grabber = EventGrabber()
config.add_subscriber(config.registry.grabber, events.BaseWebhookEvent)
return config.make_wsgi_app()
class WebhookTestBase(unittest.TestCase):
_PREFIX = '/webhook'
_PATH = _PREFIX + '/receive'
def setUp(self):
from pyramid import testing
self.request = testing.DummyRequest()
self.config = testing.setUp(request=self.request)
def tearDown(self):
from pyramid import testing
testing.tearDown()
def _createGrabber(self, event_cls=events.BaseWebhookEvent):
grabber = EventGrabber()
self.config.add_subscriber(grabber, event_cls)
return grabber
def _createRequest(self, event_body):
if not isinstance(event_body, list):
event_body = [event_body]
self.request.json_body = event_body
return self.request
def _createApp(self, event_cls=events.BaseWebhookEvent):
from webtest.app import TestApp
app = TestApp(simple_app({}))
app.grabber = app.app.registry.grabber
return app
class TestBaseEvents(WebhookTestBase):
def _makeOne(self, event_type='bounce', category='category'):
return {
'asm_group_id': 1,
'category': category,
'cert_error': '0',
'email': 'email@example.com',
'event': event_type,
'ip': '127.0.0.1',
'reason': '500 No Such User',
'smtp-id': '<original-smtp-id@domain.com>',
'status': '5.0.0',
'timestamp': 1249948800,
'tls': '1',
'type': 'bounce',
'unique_arg_key': 'unique_arg_value',
}
def _create_dt(self):
import datetime
return datetime.datetime(2009, 8, 11, 0, 0)
def test_event_parsed(self):
grabber = self._createGrabber()
request = self._createRequest(self._makeOne())
psw.receive_events(request)
self.assertEqual(len(grabber.events), 1)
def test_event_parsed_from_request(self):
app = self._createApp()
grabber = app.grabber
app.post_json(self._PATH, [self._makeOne()])
self.assertEqual(len(grabber.events), 1)
def test_multiple_events_parsed_from_request(self, n=3):
app = self._createApp()
grabber = app.grabber
app.post_json(self._PATH, [self._makeOne()] * n)
self.assertEqual(len(grabber.events), n)
def test_specific_event_caught(self):
grabber = self._createGrabber(events.BounceEvent)
request = self._createRequest(self._makeOne())
psw.receive_events(request)
self.assertEqual(len(grabber.events), 1)
def test_unspecified_event_ignored(self):
grabber = self._createGrabber(events.DeferredEvent)
request = self._createRequest(self._makeOne())
psw.receive_events(request)
self.assertEqual(len(grabber.events), 0)
def test_timestamp_parsed(self):
grabber = self._createGrabber()
request = self._createRequest(self._makeOne())
psw.receive_events(request)
self.assertEqual(grabber.last.dt, self._create_dt())
def test_unique_arguments_extracted(self):
grabber = self._createGrabber()
request = self._createRequest(self._makeOne())
psw.receive_events(request)
self.assertDictEqual(grabber.last.unique_arguments, {
'unique_arg_key': 'unique_arg_value',
})
def test_correct_subclass(self):
grabber = self._createGrabber()
request = self._createRequest(self._makeOne())
psw.receive_events(request)
self.assertIsInstance(grabber.last, events.BounceEvent)
def test_unknown_event_raises_exception(self):
request = self._createRequest(self._makeOne(event_type='UNKNOWN'))
self.assertRaises(
errors.UnknownEventError, psw.receive_events, request)
def test_single_category_is_list_wrapped(self):
grabber = self._createGrabber()
request = self._createRequest(self._makeOne())
psw.receive_events(request)
self.assertEqual([grabber.last.category], grabber.last.categories)
def test_multiple_categories_are_unchanged(self):
grabber = self._createGrabber()
request = self._createRequest(self._makeOne(category=['c1', 'c2']))
psw.receive_events(request)
self.assertEqual(grabber.last.category, grabber.last.categories)
def test_empty_categories_is_empty_list(self):
grabber = self._createGrabber()
request = self._createRequest(self._makeOne(category=None))
psw.receive_events(request)
self.assertEqual(grabber.last.categories, [])
class TestDeliveryEvents(WebhookTestBase):
def _makeOne(self):
return {
'asm_group_id': 1,
'category': ['category1', 'category2'],
'cert_error': '0',
'email': 'email@example.com',
'event': 'bounce',
'ip': '127.0.0.1',
'reason': '500 No Such User',
'smtp-id': '<original-smtp-id@domain.com>',
'status': '5.0.0',
'timestamp': 1249948800,
'tls': '1',
'type': 'bounce',
'unique_arg_key': 'unique_arg_value',
}
class TestEngagementEvents(WebhookTestBase):
def _makeOne(self):
return {
'asm_group_id': 1,
'category': ['category1', 'category2'],
'email': 'email@example.com',
'event': 'click',
'ip': '255.255.255.255',
'timestamp': 1249948800,
'unique_arg_key': 'unique_arg_value',
'url': 'http://yourdomain.com/blog/news.html',
'useragent': 'Example Useragent',
}
if __name__ == '__main__':
import sys
sys.exit(unittest.main())
|
GoodRx/pyramid-sendgrid-webhooks
|
tests/test_pyramid_sendgrid_webhooks.py
|
Python
|
mit
| 6,637 | 0 |
# coding: utf-8
# This file is a part of VK4XMPP transport
# © simpleApps, 2013 — 2015.
from datetime import datetime
if not require("attachments"):
raise AssertionError("'forwardMessages' requires 'attachments'")
BASE_SPACER = chr(32) + unichr(183) + chr(32)
def parseForwardedMessages(self, msg, depth=0):
body = ""
if msg.has_key("fwd_messages"):
spacer = BASE_SPACER * depth
body = "\n" + spacer
body += _("Forwarded messages:")
fwd_messages = sorted(msg["fwd_messages"], sortMsg)
for fwd in fwd_messages:
source = fwd["user_id"]
date = fwd["date"]
fwdBody = escape("", uhtml(compile_eol.sub("\n" + spacer + BASE_SPACER, fwd["body"])))
date = datetime.fromtimestamp(date).strftime("%d.%m.%Y %H:%M:%S")
name = self.vk.getUserData(source)["name"]
body += "\n%s[%s] <%s> %s" % (spacer + BASE_SPACER, date, name, fwdBody)
body += parseAttachments(self, fwd, spacer + (BASE_SPACER * 2))
if depth < MAXIMUM_FORWARD_DEPTH:
body += parseForwardedMessages(self, fwd, (depth + 1))
return body
if not isdef("MAXIMUM_FORWARD_DEPTH"):
MAXIMUM_FORWARD_DEPTH = 29
registerHandler("msg01", parseForwardedMessages)
|
unclev/vk.unclev.ru
|
extensions/forwarded_messages.py
|
Python
|
mit
| 1,156 | 0.021683 |
# 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/.
from configman import ConfigurationManager, Namespace
from configman.converters import list_converter, class_converter
from socorro.external.postgresql.connection_context import ConnectionContext
from socorro.unittest.testbase import TestCase
class PostgreSQLTestCase(TestCase):
"""Base class for PostgreSQL related unit tests. """
app_name = 'PostgreSQLTestCase'
app_version = '1.0'
app_description = __doc__
metadata = ''
required_config = Namespace()
# we use this class here because it is a convenient way to pull in
# both a database connection context and a transaction executor
required_config.add_option(
'crashstorage_class',
default='socorro.external.postgresql.crashstorage.'
'PostgreSQLCrashStorage',
from_string_converter=class_converter
)
required_config.add_option(
name='database_superusername',
default='test',
doc='Username to connect to database',
)
required_config.add_option(
name='database_superuserpassword',
default='aPassword',
doc='Password to connect to database',
)
required_config.add_option(
name='dropdb',
default=False,
doc='Whether or not to drop database_name',
exclude_from_print_conf=True,
exclude_from_dump_conf=True
)
required_config.add_option(
'platforms',
default=[{
"id": "windows",
"name": "Windows NT"
}, {
"id": "mac",
"name": "Mac OS X"
}, {
"id": "linux",
"name": "Linux"
}],
doc='Array associating OS ids to full names.',
)
required_config.add_option(
'non_release_channels',
default=['beta', 'aurora', 'nightly'],
doc='List of channels, excluding the `release` one.',
from_string_converter=list_converter
)
required_config.add_option(
'restricted_channels',
default=['beta'],
doc='List of channels to restrict based on build ids.',
from_string_converter=list_converter
)
@classmethod
def get_standard_config(cls):
config_manager = ConfigurationManager(
[cls.required_config,
],
app_name='PostgreSQLTestCase',
app_description=__doc__,
argv_source=[]
)
with config_manager.context() as config:
return config
@classmethod
def setUpClass(cls):
"""Create a configuration context and a database connection.
This will create (and later destroy) one connection per test
case (aka. test class).
"""
cls.config = cls.get_standard_config()
cls.database = ConnectionContext(cls.config)
cls.connection = cls.database.connection()
@classmethod
def tearDownClass(cls):
"""Close the database connection. """
cls.connection.close()
|
Tayamarn/socorro
|
socorro/unittest/external/postgresql/unittestbase.py
|
Python
|
mpl-2.0
| 3,175 | 0 |
from __future__ import absolute_import, unicode_literals
import pytest
from case import Mock, patch, skip
try:
import librabbitmq
except ImportError:
librabbitmq = None # noqa
else:
from kombu.transport import librabbitmq # noqa
@skip.unless_module('librabbitmq')
class lrmqCase:
pass
class test_Message(lrmqCase):
def test_init(self):
chan = Mock(name='channel')
message = librabbitmq.Message(
chan, {'prop': 42}, {'delivery_tag': 337}, 'body',
)
assert message.body == 'body'
assert message.delivery_tag == 337
assert message.properties['prop'] == 42
class test_Channel(lrmqCase):
def test_prepare_message(self):
conn = Mock(name='connection')
chan = librabbitmq.Channel(conn, 1)
assert chan
body = 'the quick brown fox...'
properties = {'name': 'Elaine M.'}
body2, props2 = chan.prepare_message(
body, properties=properties,
priority=999,
content_type='ctype',
content_encoding='cenc',
headers={'H': 2},
)
assert props2['name'] == 'Elaine M.'
assert props2['priority'] == 999
assert props2['content_type'] == 'ctype'
assert props2['content_encoding'] == 'cenc'
assert props2['headers'] == {'H': 2}
assert body2 == body
body3, props3 = chan.prepare_message(body, priority=777)
assert props3['priority'] == 777
assert body3 == body
class test_Transport(lrmqCase):
def setup(self):
self.client = Mock(name='client')
self.T = librabbitmq.Transport(self.client)
def test_driver_version(self):
assert self.T.driver_version()
def test_create_channel(self):
conn = Mock(name='connection')
chan = self.T.create_channel(conn)
assert chan
conn.channel.assert_called_with()
def test_drain_events(self):
conn = Mock(name='connection')
self.T.drain_events(conn, timeout=1.33)
conn.drain_events.assert_called_with(timeout=1.33)
def test_establish_connection_SSL_not_supported(self):
self.client.ssl = True
with pytest.raises(NotImplementedError):
self.T.establish_connection()
def test_establish_connection(self):
self.T.Connection = Mock(name='Connection')
self.T.client.ssl = False
self.T.client.port = None
self.T.client.transport_options = {}
conn = self.T.establish_connection()
assert self.T.client.port == self.T.default_connection_params['port']
assert conn.client == self.T.client
assert self.T.client.drain_events == conn.drain_events
def test_collect__no_conn(self):
self.T.client.drain_events = 1234
self.T._collect(None)
assert self.client.drain_events is None
assert self.T.client is None
def test_collect__with_conn(self):
self.T.client.drain_events = 1234
conn = Mock(name='connection')
chans = conn.channels = {1: Mock(name='chan1'), 2: Mock(name='chan2')}
conn.callbacks = {'foo': Mock(name='cb1'), 'bar': Mock(name='cb2')}
for i, chan in enumerate(conn.channels.values()):
chan.connection = i
with patch('os.close') as close:
self.T._collect(conn)
close.assert_called_with(conn.fileno())
assert not conn.channels
assert not conn.callbacks
for chan in chans.values():
assert chan.connection is None
assert self.client.drain_events is None
assert self.T.client is None
with patch('os.close') as close:
self.T.client = self.client
close.side_effect = OSError()
self.T._collect(conn)
close.assert_called_with(conn.fileno())
def test_collect__with_fileno_raising_value_error(self):
conn = Mock(name='connection')
conn.channels = {1: Mock(name='chan1'), 2: Mock(name='chan2')}
with patch('os.close') as close:
self.T.client = self.client
conn.fileno.side_effect = ValueError("Socket not connected")
self.T._collect(conn)
close.assert_not_called()
conn.fileno.assert_called_with()
assert self.client.drain_events is None
assert self.T.client is None
def test_register_with_event_loop(self):
conn = Mock(name='conn')
loop = Mock(name='loop')
self.T.register_with_event_loop(conn, loop)
loop.add_reader.assert_called_with(
conn.fileno(), self.T.on_readable, conn, loop,
)
def test_verify_connection(self):
conn = Mock(name='connection')
conn.connected = True
assert self.T.verify_connection(conn)
def test_close_connection(self):
conn = Mock(name='connection')
self.client.drain_events = 1234
self.T.close_connection(conn)
assert self.client.drain_events is None
conn.close.assert_called_with()
|
urbn/kombu
|
t/unit/transport/test_librabbitmq.py
|
Python
|
bsd-3-clause
| 5,055 | 0 |
"""
Django settings for tiny_hands_pac project.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import os
from os.path import abspath, dirname, join, normpath
from sys import path
from django.core.exceptions import ImproperlyConfigured
def get_env_variable(var_name):
""" Get the environment variable or return exception """
try:
return os.environ[var_name]
except KeyError:
error_msg = "Set the %s environment variable" % var_name
raise ImproperlyConfigured(error_msg)
# Absolute filesystem path to the Django project directory:
DJANGO_ROOT = dirname(dirname(abspath(__file__)))
# Absolute filesystem path to the top-level project folder:
PROJECT_ROOT = dirname(DJANGO_ROOT)
# Add our project to our pythonpath, this way we don't need to type our project
# name in our dotted import paths:
path.append(DJANGO_ROOT)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# Do not set SECRET_KEY or LDAP password or any other sensitive data here.
# Instead, create a local.py file on the server.
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'compressor',
'taggit',
'modelcluster',
'wagtail.contrib.wagtailsitemaps',
'wagtail.contrib.wagtailsearchpromotions',
'wagtail.wagtailforms',
'wagtail.wagtailredirects',
'wagtail.wagtailembeds',
'wagtail.wagtailsites',
'wagtail.wagtailusers',
'wagtail.wagtailsnippets',
'wagtail.wagtaildocs',
'wagtail.wagtailimages',
'wagtail.wagtailsearch',
'wagtail.wagtailadmin',
'wagtail.wagtailcore',
'wagtail.contrib.settings',
'wagtailfontawesome',
'utils',
'pages',
'blog',
'events',
'contact',
'people',
'photo_gallery',
'products',
'documents_gallery',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'wagtail.wagtailcore.middleware.SiteMiddleware',
'wagtail.wagtailredirects.middleware.RedirectMiddleware',
)
ROOT_URLCONF = 'tiny_hands_pac.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'debug' : DEBUG,
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'pages.context_processors.site_url',
],
},
},
]
WSGI_APPLICATION = 'tiny_hands_pac.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'tiny_hands_pac',
'USER': '',
'HOST': '', # Set to empty string for localhost.
'PORT': '', # Set to empty string for default.
'CONN_MAX_AGE': 600,
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-gb'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_ROOT = join(PROJECT_ROOT, 'static')
STATIC_URL = '/static/'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'compressor.finders.CompressorFinder',
)
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
MEDIA_ROOT = join(PROJECT_ROOT, 'media')
MEDIA_URL = '/files/'
# Django compressor settings
# http://django-compressor.readthedocs.org/en/latest/settings/
COMPRESS_PRECOMPILERS = (
('text/x-scss', 'django_libsass.SassCompiler'),
)
COMPRESS_OFFLINE = True
# Feeds app for Wagtail CMS
FEED_APP_LABEL = 'blog'
FEED_MODEL_NAME = 'BlogPage'
FEED_ITEM_DESCRIPTION_FIELD = 'intro'
FEED_ITEM_CONTENT_FIELD = 'body'
FEED_TITLE = 'Tiny Hands Big News'
FEED_LINK = '/news/'
FEED_DESCRIPTION = ""
FEED_AUTHOR_EMAIL = 'donaldtrumphastinyhands@gmail.com'
FEED_AUTHOR_LINK = 'https://www.donaldtrumphastinyhands.com'
# Settings for wagalytics
GA_KEY_FILEPATH = ''
GA_VIEW_ID = ''
# Google Maps Key
GOOGLE_MAPS_KEY = ''
DYNAMIC_MAP_URL = ''
STATIC_MAP_URL = ''
# Facebook Open Tags
FB_SITE_NAME = ''
FB_URL = ''
FB_DESCRIPTION = ''
FB_APP_ID = ''
# Twitter Cards
TWITTER_URL = ''
TWITTER_CREATOR = ''
TWITTER_DESCRIPTION = ''
# Use Redis as the cache backend for extra performance
# CACHES = {
# 'default': {
# 'BACKEND': 'redis_cache.cache.RedisCache',
# 'LOCATION': '127.0.0.1:6379',
# 'KEY_PREFIX': 'tiny_hands_pac',
# 'OPTIONS': {
# 'CLIENT_CLASS': 'redis_cache.client.DefaultClient',
# }
# }
# }
# Wagtail settings
LOGIN_URL = 'wagtailadmin_login'
LOGIN_REDIRECT_URL = 'wagtailadmin_home'
WAGTAIL_SITE_NAME = "Tiny Hands PAC"
WAGTAILSEARCH_RESULTS_TEMPLATE = 'utils/tags/search/search_results.html'
# Use Elasticsearch as the search backend for extra performance and better search results
# WAGTAILSEARCH_BACKENDS = {
# 'default': {
# 'BACKEND': 'wagtail.wagtailsearch.backends.elasticsearch.ElasticSearch',
# 'INDEX': 'tiny_hands_pac',
# },
# }
# Celery settings
# When you have multiple sites using the same Redis server,
# specify a different Redis DB. e.g. redis://localhost/5
BROKER_URL = 'redis://'
CELERY_SEND_TASK_ERROR_EMAILS = True
CELERYD_LOG_COLOR = False
|
DonaldTrumpHasTinyHands/tiny_hands_pac
|
tiny_hands_pac/settings/base.py
|
Python
|
mit
| 6,665 | 0.0006 |
from couchpotato.core.helpers.encoding import toUnicode
from couchpotato.core.helpers.variable import tryInt
from couchpotato.core.logger import CPLog
from couchpotato.core.notifications.base import Notification
import base64
import json
log = CPLog(__name__)
class Pushbullet(Notification):
url = 'https://api.pushbullet.com/api/%s'
def notify(self, message = '', data = None, listener = None):
if not data: data = {}
devices = self.getDevices()
if devices is None:
return False
# Get all the device IDs linked to this user
if not len(devices):
response = self.request('devices')
if not response:
return False
devices += [device.get('id') for device in response['devices']]
successful = 0
for device in devices:
response = self.request(
'pushes',
cache = False,
device_id = device,
type = 'note',
title = self.default_title,
body = toUnicode(message)
)
if response:
successful += 1
else:
log.error('Unable to push notification to Pushbullet device with ID %s' % device)
return successful == len(devices)
def getDevices(self):
devices = [d.strip() for d in self.conf('devices').split(',')]
# Remove empty items
devices = [d for d in devices if len(d)]
# Break on any ids that aren't integers
valid_devices = []
for device_id in devices:
d = tryInt(device_id, None)
if not d:
log.error('Device ID "%s" is not valid', device_id)
return None
valid_devices.append(d)
return valid_devices
def request(self, method, cache = True, **kwargs):
try:
base64string = base64.encodestring('%s:' % self.conf('api_key'))[:-1]
headers = {
"Authorization": "Basic %s" % base64string
}
if cache:
return self.getJsonData(self.url % method, headers = headers, data = kwargs)
else:
data = self.urlopen(self.url % method, headers = headers, data = kwargs)
return json.loads(data)
except Exception, ex:
log.error('Pushbullet request failed')
log.debug(ex)
return None
|
rooi/CouchPotatoServer
|
couchpotato/core/notifications/pushbullet/main.py
|
Python
|
gpl-3.0
| 2,483 | 0.012485 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Joseph Herlant <herlantj@gmail.com>
# File name: hdfs_disk_usage_per_datanode.py
# Creation date: 2014-10-08
#
# Distributed under terms of the GNU GPLv3 license.
"""
This nagios active check parses the Hadoop HDFS web interface url:
http://<namenode>:<port>/dfsnodelist.jsp?whatNodes=LIVE
to check for active datanodes that use disk beyond the given thresholds.
The output includes performance datas and is truncated if longer than 1024
chars.
Tested on: Hadoop CDH3U5
"""
__author__ = 'Joseph Herlant'
__copyright__ = 'Copyright 2014, Joseph Herlant'
__credits__ = ['Joseph Herlant']
__license__ = 'GNU GPLv3'
__version__ = '1.0.2'
__maintainer__ = 'Joseph Herlant'
__email__ = 'herlantj@gmail.com'
__status__ = 'Production'
__website__ = 'https://github.com/aerostitch/'
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import argparse, sys
if __name__ == '__main__':
# use -h argument to get help
parser = argparse.ArgumentParser(
description='A Nagios check to verify all datanodes disk usage in \
an HDFS cluster from the namenode web interface.')
parser.add_argument('-n', '--namenode', required=True,
help='hostname of the namenode of the cluster')
parser.add_argument('-p', '--port', type=int, default=50070,
help='port of the namenode http interface. \
Defaults to 50070.')
parser.add_argument('-w', '--warning', type=int, default=80,
help='warning threshold. Defaults to 80.')
parser.add_argument('-c', '--critical', type=int, default=90,
help='critical threshold. Defaults to 90.')
args = parser.parse_args()
# Get the web page from the namenode
url = "http://%s:%d/dfsnodelist.jsp?whatNodes=LIVE" % \
(args.namenode, args.port)
try:
page = Browser().open(url)
except IOError:
print 'CRITICAL: Cannot access namenode interface on %s:%d!' % \
(args.namenode, args.port)
sys.exit(2)
# parse the page
html = page.read()
soup = BeautifulSoup(html)
datanodes = soup.findAll('td', {'class' : 'name'})
pcused = soup.findAll('td', {'class' : 'pcused', 'align' : 'right'})
w_msg = ''
c_msg = ''
perfdata = ''
for (idx, node) in enumerate(datanodes):
pct = float(pcused[idx].contents[0].strip())
node = datanodes[idx].findChildren('a')[0].contents[0].strip()
if pct >= args.critical:
c_msg += ' %s=%.1f%%,' % (node, pct)
perfdata += ' %s=%.1f,' % (node, pct)
elif pct >= args.warning:
w_msg += ' %s=%.1f%%,' % (node, pct)
perfdata += ' %s=%.1f,' % (node, pct)
else:
perfdata += ' %s=%.1f,' % (node, pct)
# Prints the values and exits with the nagios exit code
if len(c_msg) > 0:
print ('CRITICAL:%s%s |%s' % (c_msg, w_msg, perfdata)).strip(',')[:1024]
sys.exit(2)
elif len(w_msg) > 0:
print ('WARNING:%s |%s' % (w_msg, perfdata)).strip(',')[:1024]
sys.exit(1)
elif len(perfdata) == 0:
print 'CRITICAL: Unable to find any node data in the page.'
sys.exit(2)
else:
print ('OK |%s' % (perfdata)).strip(',')[:1024]
sys.exit(0)
|
aerostitch/nagios_checks
|
hdfs_disk_usage_per_datanode.py
|
Python
|
gpl-2.0
| 3,375 | 0.002963 |
#----------------------------------------------------------------------------------------------------------------------#
# Introdução a Programação de Computadores - IPC
# Universidade do Estado do Amazonas - UEA
#
# Adham Lucas da Silva Oliveira 1715310059
# Alexandre Marques Uchôa 1715310028
# André Luís Laborda Neves 1515070006
# Carlos Eduardo Tapudima de Oliveira 1715310030
# Diego Reis Figueira 1515070169
#
# Leia um valor de ponto flutuante com duas casas decimais. Este valor representa um valor monetário. A seguir, calcule
#o menor número de notas e moedas possíveis no qual o valor pode ser decomposto. As notas consideradas são de 100,50,20,
#10,5,2.As moedas possíveis são de 1, 0.50, 0.25, 0.10, 0.05 e 0.01. A seguir mostre a relação de notas necessárias.
#----------------------------------------------------------------------------------------------------------------------#
money = float(input())
if 0 <= money <= 1000000.00:
one_hundred_reals = money//100
money = money - (one_hundred_reals * 100)
fifty_reals = money//50
money = money - (fifty_reals * 50)
twent_reals = money//20
money = money - (twent_reals * 20)
ten_reals = money//10
money = money - (ten_reals * 10)
five_reals = money//5
money = money - (five_reals *5)
two_reals = money//2
money = money - (two_reals * 2)
one_real = money//1
money = money - (one_real * 1)
fifty_cents = money//0.50
money = money - (fifty_cents * 0.50)
twenty_five_cents = money//0.25
money = money - (twenty_five_cents * 0.25)
ten_cents = money//0.10
money = money - (ten_cents * 0.10)
five_cents = money//0.05
money = money - (five_cents * 0.05)
one_cent = money//0.01
money = money - (one_cent * 0.01)
print('NOTAS:')
print('%.0f nota(s) de R$ 100.00' % one_hundred_reals)
print('%.0f nota(s) de R$ 50.00' % fifty_reals)
print('%.0f nota(s) de R$ 20.00' % twent_reals)
print('%.0f nota(s) de R$ 10.00' % ten_reals)
print('%.0f nota(s) de R$ 5.00' % five_reals)
print('%.0f nota(s) de R$ 2.00' % two_reals)
print('MOEDAS:')
print('%.0f moeda(s) de R$ 1.00' % one_real)
print('%.0f moeda(s) de R$ 0.50' % fifty_cents)
print('%.0f moeda(s) de R$ 0.25' % twenty_five_cents)
print('%.0f moeda(s) de R$ 0.10' % ten_cents)
print('%.0f moeda(s) de R$ 0.05' % five_cents)
print('%.0f moeda(s) de R$ 0.01' % one_cent)
|
jucimarjr/IPC_2017-1
|
lista04/lista04_lista02_questao21.py
|
Python
|
apache-2.0
| 2,408 | 0.014632 |
# -*- test-case-name: twisted.names.test.test_dns -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
DNS protocol implementation.
Future Plans:
- Get rid of some toplevels, maybe.
"""
from __future__ import division, absolute_import
__all__ = [
'IEncodable', 'IRecord',
'A', 'A6', 'AAAA', 'AFSDB', 'CNAME', 'DNAME', 'HINFO',
'MAILA', 'MAILB', 'MB', 'MD', 'MF', 'MG', 'MINFO', 'MR', 'MX',
'NAPTR', 'NS', 'NULL', 'PTR', 'RP', 'SOA', 'SPF', 'SRV', 'TXT', 'WKS',
'ANY', 'CH', 'CS', 'HS', 'IN',
'ALL_RECORDS', 'AXFR', 'IXFR',
'EFORMAT', 'ENAME', 'ENOTIMP', 'EREFUSED', 'ESERVER',
'Record_A', 'Record_A6', 'Record_AAAA', 'Record_AFSDB', 'Record_CNAME',
'Record_DNAME', 'Record_HINFO', 'Record_MB', 'Record_MD', 'Record_MF',
'Record_MG', 'Record_MINFO', 'Record_MR', 'Record_MX', 'Record_NAPTR',
'Record_NS', 'Record_NULL', 'Record_PTR', 'Record_RP', 'Record_SOA',
'Record_SPF', 'Record_SRV', 'Record_TXT', 'Record_WKS', 'UnknownRecord',
'QUERY_CLASSES', 'QUERY_TYPES', 'REV_CLASSES', 'REV_TYPES', 'EXT_QUERIES',
'Charstr', 'Message', 'Name', 'Query', 'RRHeader', 'SimpleRecord',
'DNSDatagramProtocol', 'DNSMixin', 'DNSProtocol',
'OK', 'OP_INVERSE', 'OP_NOTIFY', 'OP_QUERY', 'OP_STATUS', 'OP_UPDATE',
'PORT',
'AuthoritativeDomainError', 'DNSQueryTimeoutError', 'DomainError',
]
# System imports
import warnings
import struct, random, types, socket
from itertools import chain
from io import BytesIO
AF_INET6 = socket.AF_INET6
from zope.interface import implementer, Interface, Attribute
# Twisted imports
from twisted.internet import protocol, defer
from twisted.internet.error import CannotListenError
from twisted.python import log, failure
from twisted.python import _utilpy3 as tputil
from twisted.python import randbytes
from twisted.python.compat import _PY3, unicode, comparable, cmp, nativeString
if _PY3:
def _ord2bytes(ordinal):
"""
Construct a bytes object representing a single byte with the given
ordinal value.
@type ordinal: C{int}
@rtype: C{bytes}
"""
return bytes([ordinal])
def _nicebytes(bytes):
"""
Represent a mostly textful bytes object in a way suitable for presentation
to an end user.
@param bytes: The bytes to represent.
@rtype: C{str}
"""
return repr(bytes)[1:]
def _nicebyteslist(list):
"""
Represent a list of mostly textful bytes objects in a way suitable for
presentation to an end user.
@param list: The list of bytes to represent.
@rtype: C{str}
"""
return '[%s]' % (
', '.join([_nicebytes(b) for b in list]),)
else:
_ord2bytes = chr
_nicebytes = _nicebyteslist = repr
def randomSource():
"""
Wrapper around L{randbytes.secureRandom} to return 2 random chars.
"""
return struct.unpack('H', randbytes.secureRandom(2, fallback=True))[0]
PORT = 53
(A, NS, MD, MF, CNAME, SOA, MB, MG, MR, NULL, WKS, PTR, HINFO, MINFO, MX, TXT,
RP, AFSDB) = range(1, 19)
AAAA = 28
SRV = 33
NAPTR = 35
A6 = 38
DNAME = 39
SPF = 99
QUERY_TYPES = {
A: 'A',
NS: 'NS',
MD: 'MD',
MF: 'MF',
CNAME: 'CNAME',
SOA: 'SOA',
MB: 'MB',
MG: 'MG',
MR: 'MR',
NULL: 'NULL',
WKS: 'WKS',
PTR: 'PTR',
HINFO: 'HINFO',
MINFO: 'MINFO',
MX: 'MX',
TXT: 'TXT',
RP: 'RP',
AFSDB: 'AFSDB',
# 19 through 27? Eh, I'll get to 'em.
AAAA: 'AAAA',
SRV: 'SRV',
NAPTR: 'NAPTR',
A6: 'A6',
DNAME: 'DNAME',
SPF: 'SPF'
}
IXFR, AXFR, MAILB, MAILA, ALL_RECORDS = range(251, 256)
# "Extended" queries (Hey, half of these are deprecated, good job)
EXT_QUERIES = {
IXFR: 'IXFR',
AXFR: 'AXFR',
MAILB: 'MAILB',
MAILA: 'MAILA',
ALL_RECORDS: 'ALL_RECORDS'
}
REV_TYPES = dict([
(v, k) for (k, v) in chain(QUERY_TYPES.items(), EXT_QUERIES.items())
])
IN, CS, CH, HS = range(1, 5)
ANY = 255
QUERY_CLASSES = {
IN: 'IN',
CS: 'CS',
CH: 'CH',
HS: 'HS',
ANY: 'ANY'
}
REV_CLASSES = dict([
(v, k) for (k, v) in QUERY_CLASSES.items()
])
# Opcodes
OP_QUERY, OP_INVERSE, OP_STATUS = range(3)
OP_NOTIFY = 4 # RFC 1996
OP_UPDATE = 5 # RFC 2136
# Response Codes
OK, EFORMAT, ESERVER, ENAME, ENOTIMP, EREFUSED = range(6)
class IRecord(Interface):
"""
An single entry in a zone of authority.
"""
TYPE = Attribute("An indicator of what kind of record this is.")
# Backwards compatibility aliases - these should be deprecated or something I
# suppose. -exarkun
from twisted.names.error import DomainError, AuthoritativeDomainError
from twisted.names.error import DNSQueryTimeoutError
def str2time(s):
"""
Parse a string description of an interval into an integer number of seconds.
@param s: An interval definition constructed as an interval duration
followed by an interval unit. An interval duration is a base ten
representation of an integer. An interval unit is one of the following
letters: S (seconds), M (minutes), H (hours), D (days), W (weeks), or Y
(years). For example: C{"3S"} indicates an interval of three seconds;
C{"5D"} indicates an interval of five days. Alternatively, C{s} may be
any non-string and it will be returned unmodified.
@type s: text string (C{str}) for parsing; anything else for passthrough.
@return: an C{int} giving the interval represented by the string C{s}, or
whatever C{s} is if it is not a string.
"""
suffixes = (
('S', 1), ('M', 60), ('H', 60 * 60), ('D', 60 * 60 * 24),
('W', 60 * 60 * 24 * 7), ('Y', 60 * 60 * 24 * 365)
)
if isinstance(s, str):
s = s.upper().strip()
for (suff, mult) in suffixes:
if s.endswith(suff):
return int(float(s[:-1]) * mult)
try:
s = int(s)
except ValueError:
raise ValueError("Invalid time interval specifier: " + s)
return s
def readPrecisely(file, l):
buff = file.read(l)
if len(buff) < l:
raise EOFError
return buff
class IEncodable(Interface):
"""
Interface for something which can be encoded to and decoded
from a file object.
"""
def encode(strio, compDict = None):
"""
Write a representation of this object to the given
file object.
@type strio: File-like object
@param strio: The stream to which to write bytes
@type compDict: C{dict} or C{None}
@param compDict: A dictionary of backreference addresses that have
have already been written to this stream and that may be used for
compression.
"""
def decode(strio, length = None):
"""
Reconstruct an object from data read from the given
file object.
@type strio: File-like object
@param strio: The stream from which bytes may be read
@type length: C{int} or C{None}
@param length: The number of bytes in this RDATA field. Most
implementations can ignore this value. Only in the case of
records similar to TXT where the total length is in no way
encoded in the data is it necessary.
"""
@implementer(IEncodable)
class Charstr(object):
def __init__(self, string=b''):
if not isinstance(string, bytes):
raise ValueError("%r is not a byte string" % (string,))
self.string = string
def encode(self, strio, compDict=None):
"""
Encode this Character string into the appropriate byte format.
@type strio: file
@param strio: The byte representation of this Charstr will be written
to this file.
"""
string = self.string
ind = len(string)
strio.write(_ord2bytes(ind))
strio.write(string)
def decode(self, strio, length=None):
"""
Decode a byte string into this Charstr.
@type strio: file
@param strio: Bytes will be read from this file until the full string
is decoded.
@raise EOFError: Raised when there are not enough bytes available from
C{strio}.
"""
self.string = b''
l = ord(readPrecisely(strio, 1))
self.string = readPrecisely(strio, l)
def __eq__(self, other):
if isinstance(other, Charstr):
return self.string == other.string
return NotImplemented
def __ne__(self, other):
if isinstance(other, Charstr):
return self.string != other.string
return NotImplemented
def __hash__(self):
return hash(self.string)
def __str__(self):
"""
Represent this L{Charstr} instance by its string value.
"""
return nativeString(self.string)
@implementer(IEncodable)
class Name:
"""
A name in the domain name system, made up of multiple labels. For example,
I{twistedmatrix.com}.
@ivar name: A byte string giving the name.
@type name: C{bytes}
"""
def __init__(self, name=b''):
if not isinstance(name, bytes):
raise TypeError("%r is not a byte string" % (name,))
self.name = name
def encode(self, strio, compDict=None):
"""
Encode this Name into the appropriate byte format.
@type strio: file
@param strio: The byte representation of this Name will be written to
this file.
@type compDict: dict
@param compDict: dictionary of Names that have already been encoded
and whose addresses may be backreferenced by this Name (for the purpose
of reducing the message size).
"""
name = self.name
while name:
if compDict is not None:
if name in compDict:
strio.write(
struct.pack("!H", 0xc000 | compDict[name]))
return
else:
compDict[name] = strio.tell() + Message.headerSize
ind = name.find(b'.')
if ind > 0:
label, name = name[:ind], name[ind + 1:]
else:
# This is the last label, end the loop after handling it.
label = name
name = None
ind = len(label)
strio.write(_ord2bytes(ind))
strio.write(label)
strio.write(b'\x00')
def decode(self, strio, length=None):
"""
Decode a byte string into this Name.
@type strio: file
@param strio: Bytes will be read from this file until the full Name
is decoded.
@raise EOFError: Raised when there are not enough bytes available
from C{strio}.
@raise ValueError: Raised when the name cannot be decoded (for example,
because it contains a loop).
"""
visited = set()
self.name = b''
off = 0
while 1:
l = ord(readPrecisely(strio, 1))
if l == 0:
if off > 0:
strio.seek(off)
return
if (l >> 6) == 3:
new_off = ((l&63) << 8
| ord(readPrecisely(strio, 1)))
if new_off in visited:
raise ValueError("Compression loop in encoded name")
visited.add(new_off)
if off == 0:
off = strio.tell()
strio.seek(new_off)
continue
label = readPrecisely(strio, l)
if self.name == b'':
self.name = label
else:
self.name = self.name + b'.' + label
def __eq__(self, other):
if isinstance(other, Name):
return self.name == other.name
return NotImplemented
def __ne__(self, other):
if isinstance(other, Name):
return self.name != other.name
return NotImplemented
def __hash__(self):
return hash(self.name)
def __str__(self):
"""
Represent this L{Name} instance by its string name.
"""
return nativeString(self.name)
@comparable
@implementer(IEncodable)
class Query:
"""
Represent a single DNS query.
@ivar name: The name about which this query is requesting information.
@ivar type: The query type.
@ivar cls: The query class.
"""
name = None
type = None
cls = None
def __init__(self, name=b'', type=A, cls=IN):
"""
@type name: C{bytes}
@param name: The name about which to request information.
@type type: C{int}
@param type: The query type.
@type cls: C{int}
@param cls: The query class.
"""
self.name = Name(name)
self.type = type
self.cls = cls
def encode(self, strio, compDict=None):
self.name.encode(strio, compDict)
strio.write(struct.pack("!HH", self.type, self.cls))
def decode(self, strio, length = None):
self.name.decode(strio)
buff = readPrecisely(strio, 4)
self.type, self.cls = struct.unpack("!HH", buff)
def __hash__(self):
return hash((str(self.name).lower(), self.type, self.cls))
def __cmp__(self, other):
if isinstance(other, Query):
return cmp(
(str(self.name).lower(), self.type, self.cls),
(str(other.name).lower(), other.type, other.cls))
return NotImplemented
def __str__(self):
t = QUERY_TYPES.get(self.type, EXT_QUERIES.get(self.type, 'UNKNOWN (%d)' % self.type))
c = QUERY_CLASSES.get(self.cls, 'UNKNOWN (%d)' % self.cls)
return '<Query %s %s %s>' % (self.name, t, c)
def __repr__(self):
return 'Query(%r, %r, %r)' % (str(self.name), self.type, self.cls)
@implementer(IEncodable)
class RRHeader(tputil.FancyEqMixin):
"""
A resource record header.
@cvar fmt: C{str} specifying the byte format of an RR.
@ivar name: The name about which this reply contains information.
@ivar type: The query type of the original request.
@ivar cls: The query class of the original request.
@ivar ttl: The time-to-live for this record.
@ivar payload: An object that implements the IEncodable interface
@ivar auth: A C{bool} indicating whether this C{RRHeader} was parsed from an
authoritative message.
"""
compareAttributes = ('name', 'type', 'cls', 'ttl', 'payload', 'auth')
fmt = "!HHIH"
name = None
type = None
cls = None
ttl = None
payload = None
rdlength = None
cachedResponse = None
def __init__(self, name=b'', type=A, cls=IN, ttl=0, payload=None, auth=False):
"""
@type name: C{bytes}
@param name: The name about which this reply contains information.
@type type: C{int}
@param type: The query type.
@type cls: C{int}
@param cls: The query class.
@type ttl: C{int}
@param ttl: Time to live for this record.
@type payload: An object implementing C{IEncodable}
@param payload: A Query Type specific data object.
@raises ValueError: if the ttl is negative.
"""
assert (payload is None) or isinstance(payload, UnknownRecord) or (payload.TYPE == type)
if ttl < 0:
raise ValueError("TTL cannot be negative")
self.name = Name(name)
self.type = type
self.cls = cls
self.ttl = ttl
self.payload = payload
self.auth = auth
def encode(self, strio, compDict=None):
self.name.encode(strio, compDict)
strio.write(struct.pack(self.fmt, self.type, self.cls, self.ttl, 0))
if self.payload:
prefix = strio.tell()
self.payload.encode(strio, compDict)
aft = strio.tell()
strio.seek(prefix - 2, 0)
strio.write(struct.pack('!H', aft - prefix))
strio.seek(aft, 0)
def decode(self, strio, length = None):
self.name.decode(strio)
l = struct.calcsize(self.fmt)
buff = readPrecisely(strio, l)
r = struct.unpack(self.fmt, buff)
self.type, self.cls, self.ttl, self.rdlength = r
def isAuthoritative(self):
return self.auth
def __str__(self):
t = QUERY_TYPES.get(self.type, EXT_QUERIES.get(self.type, 'UNKNOWN (%d)' % self.type))
c = QUERY_CLASSES.get(self.cls, 'UNKNOWN (%d)' % self.cls)
return '<RR name=%s type=%s class=%s ttl=%ds auth=%s>' % (self.name, t, c, self.ttl, self.auth and 'True' or 'False')
__repr__ = __str__
@implementer(IEncodable, IRecord)
class SimpleRecord(tputil.FancyStrMixin, tputil.FancyEqMixin):
"""
A Resource Record which consists of a single RFC 1035 domain-name.
@type name: L{Name}
@ivar name: The name associated with this record.
@type ttl: C{int}
@ivar ttl: The maximum number of seconds which this record should be
cached.
"""
showAttributes = (('name', 'name', '%s'), 'ttl')
compareAttributes = ('name', 'ttl')
TYPE = None
name = None
def __init__(self, name=b'', ttl=None):
self.name = Name(name)
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
self.name.encode(strio, compDict)
def decode(self, strio, length = None):
self.name = Name()
self.name.decode(strio)
def __hash__(self):
return hash(self.name)
# Kinds of RRs - oh my!
class Record_NS(SimpleRecord):
"""
An authoritative nameserver.
"""
TYPE = NS
fancybasename = 'NS'
class Record_MD(SimpleRecord):
"""
A mail destination.
This record type is obsolete.
@see: L{Record_MX}
"""
TYPE = MD
fancybasename = 'MD'
class Record_MF(SimpleRecord):
"""
A mail forwarder.
This record type is obsolete.
@see: L{Record_MX}
"""
TYPE = MF
fancybasename = 'MF'
class Record_CNAME(SimpleRecord):
"""
The canonical name for an alias.
"""
TYPE = CNAME
fancybasename = 'CNAME'
class Record_MB(SimpleRecord):
"""
A mailbox domain name.
This is an experimental record type.
"""
TYPE = MB
fancybasename = 'MB'
class Record_MG(SimpleRecord):
"""
A mail group member.
This is an experimental record type.
"""
TYPE = MG
fancybasename = 'MG'
class Record_MR(SimpleRecord):
"""
A mail rename domain name.
This is an experimental record type.
"""
TYPE = MR
fancybasename = 'MR'
class Record_PTR(SimpleRecord):
"""
A domain name pointer.
"""
TYPE = PTR
fancybasename = 'PTR'
class Record_DNAME(SimpleRecord):
"""
A non-terminal DNS name redirection.
This record type provides the capability to map an entire subtree of the
DNS name space to another domain. It differs from the CNAME record which
maps a single node of the name space.
@see: U{http://www.faqs.org/rfcs/rfc2672.html}
@see: U{http://www.faqs.org/rfcs/rfc3363.html}
"""
TYPE = DNAME
fancybasename = 'DNAME'
@implementer(IEncodable, IRecord)
class Record_A(tputil.FancyEqMixin):
"""
An IPv4 host address.
@type address: C{str}
@ivar address: The packed network-order representation of the IPv4 address
associated with this record.
@type ttl: C{int}
@ivar ttl: The maximum number of seconds which this record should be
cached.
"""
compareAttributes = ('address', 'ttl')
TYPE = A
address = None
def __init__(self, address='0.0.0.0', ttl=None):
address = socket.inet_aton(address)
self.address = address
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
strio.write(self.address)
def decode(self, strio, length = None):
self.address = readPrecisely(strio, 4)
def __hash__(self):
return hash(self.address)
def __str__(self):
return '<A address=%s ttl=%s>' % (self.dottedQuad(), self.ttl)
__repr__ = __str__
def dottedQuad(self):
return socket.inet_ntoa(self.address)
@implementer(IEncodable, IRecord)
class Record_SOA(tputil.FancyEqMixin, tputil.FancyStrMixin):
"""
Marks the start of a zone of authority.
This record describes parameters which are shared by all records within a
particular zone.
@type mname: L{Name}
@ivar mname: The domain-name of the name server that was the original or
primary source of data for this zone.
@type rname: L{Name}
@ivar rname: A domain-name which specifies the mailbox of the person
responsible for this zone.
@type serial: C{int}
@ivar serial: The unsigned 32 bit version number of the original copy of
the zone. Zone transfers preserve this value. This value wraps and
should be compared using sequence space arithmetic.
@type refresh: C{int}
@ivar refresh: A 32 bit time interval before the zone should be refreshed.
@type minimum: C{int}
@ivar minimum: The unsigned 32 bit minimum TTL field that should be
exported with any RR from this zone.
@type expire: C{int}
@ivar expire: A 32 bit time value that specifies the upper limit on the
time interval that can elapse before the zone is no longer
authoritative.
@type retry: C{int}
@ivar retry: A 32 bit time interval that should elapse before a failed
refresh should be retried.
@type ttl: C{int}
@ivar ttl: The default TTL to use for records served from this zone.
"""
fancybasename = 'SOA'
compareAttributes = ('serial', 'mname', 'rname', 'refresh', 'expire', 'retry', 'minimum', 'ttl')
showAttributes = (('mname', 'mname', '%s'), ('rname', 'rname', '%s'), 'serial', 'refresh', 'retry', 'expire', 'minimum', 'ttl')
TYPE = SOA
def __init__(self, mname=b'', rname=b'', serial=0, refresh=0, retry=0,
expire=0, minimum=0, ttl=None):
self.mname, self.rname = Name(mname), Name(rname)
self.serial, self.refresh = str2time(serial), str2time(refresh)
self.minimum, self.expire = str2time(minimum), str2time(expire)
self.retry = str2time(retry)
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
self.mname.encode(strio, compDict)
self.rname.encode(strio, compDict)
strio.write(
struct.pack(
'!LlllL',
self.serial, self.refresh, self.retry, self.expire,
self.minimum
)
)
def decode(self, strio, length = None):
self.mname, self.rname = Name(), Name()
self.mname.decode(strio)
self.rname.decode(strio)
r = struct.unpack('!LlllL', readPrecisely(strio, 20))
self.serial, self.refresh, self.retry, self.expire, self.minimum = r
def __hash__(self):
return hash((
self.serial, self.mname, self.rname,
self.refresh, self.expire, self.retry
))
@implementer(IEncodable, IRecord)
class Record_NULL(tputil.FancyStrMixin, tputil.FancyEqMixin):
"""
A null record.
This is an experimental record type.
@type ttl: C{int}
@ivar ttl: The maximum number of seconds which this record should be
cached.
"""
fancybasename = 'NULL'
showAttributes = (('payload', _nicebytes), 'ttl')
compareAttributes = ('payload', 'ttl')
TYPE = NULL
def __init__(self, payload=None, ttl=None):
self.payload = payload
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
strio.write(self.payload)
def decode(self, strio, length = None):
self.payload = readPrecisely(strio, length)
def __hash__(self):
return hash(self.payload)
@implementer(IEncodable, IRecord)
class Record_WKS(tputil.FancyEqMixin, tputil.FancyStrMixin):
"""
A well known service description.
This record type is obsolete. See L{Record_SRV}.
@type address: C{str}
@ivar address: The packed network-order representation of the IPv4 address
associated with this record.
@type protocol: C{int}
@ivar protocol: The 8 bit IP protocol number for which this service map is
relevant.
@type map: C{str}
@ivar map: A bitvector indicating the services available at the specified
address.
@type ttl: C{int}
@ivar ttl: The maximum number of seconds which this record should be
cached.
"""
fancybasename = "WKS"
compareAttributes = ('address', 'protocol', 'map', 'ttl')
showAttributes = [('_address', 'address', '%s'), 'protocol', 'ttl']
TYPE = WKS
_address = property(lambda self: socket.inet_ntoa(self.address))
def __init__(self, address='0.0.0.0', protocol=0, map='', ttl=None):
self.address = socket.inet_aton(address)
self.protocol, self.map = protocol, map
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
strio.write(self.address)
strio.write(struct.pack('!B', self.protocol))
strio.write(self.map)
def decode(self, strio, length = None):
self.address = readPrecisely(strio, 4)
self.protocol = struct.unpack('!B', readPrecisely(strio, 1))[0]
self.map = readPrecisely(strio, length - 5)
def __hash__(self):
return hash((self.address, self.protocol, self.map))
@implementer(IEncodable, IRecord)
class Record_AAAA(tputil.FancyEqMixin, tputil.FancyStrMixin):
"""
An IPv6 host address.
@type address: C{str}
@ivar address: The packed network-order representation of the IPv6 address
associated with this record.
@type ttl: C{int}
@ivar ttl: The maximum number of seconds which this record should be
cached.
@see: U{http://www.faqs.org/rfcs/rfc1886.html}
"""
TYPE = AAAA
fancybasename = 'AAAA'
showAttributes = (('_address', 'address', '%s'), 'ttl')
compareAttributes = ('address', 'ttl')
_address = property(lambda self: socket.inet_ntop(AF_INET6, self.address))
def __init__(self, address='::', ttl=None):
self.address = socket.inet_pton(AF_INET6, address)
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
strio.write(self.address)
def decode(self, strio, length = None):
self.address = readPrecisely(strio, 16)
def __hash__(self):
return hash(self.address)
@implementer(IEncodable, IRecord)
class Record_A6(tputil.FancyStrMixin, tputil.FancyEqMixin):
"""
An IPv6 address.
This is an experimental record type.
@type prefixLen: C{int}
@ivar prefixLen: The length of the suffix.
@type suffix: C{str}
@ivar suffix: An IPv6 address suffix in network order.
@type prefix: L{Name}
@ivar prefix: If specified, a name which will be used as a prefix for other
A6 records.
@type bytes: C{int}
@ivar bytes: The length of the prefix.
@type ttl: C{int}
@ivar ttl: The maximum number of seconds which this record should be
cached.
@see: U{http://www.faqs.org/rfcs/rfc2874.html}
@see: U{http://www.faqs.org/rfcs/rfc3363.html}
@see: U{http://www.faqs.org/rfcs/rfc3364.html}
"""
TYPE = A6
fancybasename = 'A6'
showAttributes = (('_suffix', 'suffix', '%s'), ('prefix', 'prefix', '%s'), 'ttl')
compareAttributes = ('prefixLen', 'prefix', 'suffix', 'ttl')
_suffix = property(lambda self: socket.inet_ntop(AF_INET6, self.suffix))
def __init__(self, prefixLen=0, suffix='::', prefix=b'', ttl=None):
self.prefixLen = prefixLen
self.suffix = socket.inet_pton(AF_INET6, suffix)
self.prefix = Name(prefix)
self.bytes = int((128 - self.prefixLen) / 8.0)
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
strio.write(struct.pack('!B', self.prefixLen))
if self.bytes:
strio.write(self.suffix[-self.bytes:])
if self.prefixLen:
# This may not be compressed
self.prefix.encode(strio, None)
def decode(self, strio, length = None):
self.prefixLen = struct.unpack('!B', readPrecisely(strio, 1))[0]
self.bytes = int((128 - self.prefixLen) / 8.0)
if self.bytes:
self.suffix = b'\x00' * (16 - self.bytes) + readPrecisely(strio, self.bytes)
if self.prefixLen:
self.prefix.decode(strio)
def __eq__(self, other):
if isinstance(other, Record_A6):
return (self.prefixLen == other.prefixLen and
self.suffix[-self.bytes:] == other.suffix[-self.bytes:] and
self.prefix == other.prefix and
self.ttl == other.ttl)
return NotImplemented
def __hash__(self):
return hash((self.prefixLen, self.suffix[-self.bytes:], self.prefix))
def __str__(self):
return '<A6 %s %s (%d) ttl=%s>' % (
self.prefix,
socket.inet_ntop(AF_INET6, self.suffix),
self.prefixLen, self.ttl
)
@implementer(IEncodable, IRecord)
class Record_SRV(tputil.FancyEqMixin, tputil.FancyStrMixin):
"""
The location of the server(s) for a specific protocol and domain.
This is an experimental record type.
@type priority: C{int}
@ivar priority: The priority of this target host. A client MUST attempt to
contact the target host with the lowest-numbered priority it can reach;
target hosts with the same priority SHOULD be tried in an order defined
by the weight field.
@type weight: C{int}
@ivar weight: Specifies a relative weight for entries with the same
priority. Larger weights SHOULD be given a proportionately higher
probability of being selected.
@type port: C{int}
@ivar port: The port on this target host of this service.
@type target: L{Name}
@ivar target: The domain name of the target host. There MUST be one or
more address records for this name, the name MUST NOT be an alias (in
the sense of RFC 1034 or RFC 2181). Implementors are urged, but not
required, to return the address record(s) in the Additional Data
section. Unless and until permitted by future standards action, name
compression is not to be used for this field.
@type ttl: C{int}
@ivar ttl: The maximum number of seconds which this record should be
cached.
@see: U{http://www.faqs.org/rfcs/rfc2782.html}
"""
TYPE = SRV
fancybasename = 'SRV'
compareAttributes = ('priority', 'weight', 'target', 'port', 'ttl')
showAttributes = ('priority', 'weight', ('target', 'target', '%s'), 'port', 'ttl')
def __init__(self, priority=0, weight=0, port=0, target=b'', ttl=None):
self.priority = int(priority)
self.weight = int(weight)
self.port = int(port)
self.target = Name(target)
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
strio.write(struct.pack('!HHH', self.priority, self.weight, self.port))
# This can't be compressed
self.target.encode(strio, None)
def decode(self, strio, length = None):
r = struct.unpack('!HHH', readPrecisely(strio, struct.calcsize('!HHH')))
self.priority, self.weight, self.port = r
self.target = Name()
self.target.decode(strio)
def __hash__(self):
return hash((self.priority, self.weight, self.port, self.target))
@implementer(IEncodable, IRecord)
class Record_NAPTR(tputil.FancyEqMixin, tputil.FancyStrMixin):
"""
The location of the server(s) for a specific protocol and domain.
@type order: C{int}
@ivar order: An integer specifying the order in which the NAPTR records
MUST be processed to ensure the correct ordering of rules. Low numbers
are processed before high numbers.
@type preference: C{int}
@ivar preference: An integer that specifies the order in which NAPTR
records with equal "order" values SHOULD be processed, low numbers
being processed before high numbers.
@type flag: L{Charstr}
@ivar flag: A <character-string> containing flags to control aspects of the
rewriting and interpretation of the fields in the record. Flags
are single characters from the set [A-Z0-9]. The case of the alphabetic
characters is not significant.
At this time only four flags, "S", "A", "U", and "P", are defined.
@type service: L{Charstr}
@ivar service: Specifies the service(s) available down this rewrite path.
It may also specify the particular protocol that is used to talk with a
service. A protocol MUST be specified if the flags field states that
the NAPTR is terminal.
@type regexp: L{Charstr}
@ivar regexp: A STRING containing a substitution expression that is applied
to the original string held by the client in order to construct the
next domain name to lookup.
@type replacement: L{Name}
@ivar replacement: The next NAME to query for NAPTR, SRV, or address
records depending on the value of the flags field. This MUST be a
fully qualified domain-name.
@type ttl: C{int}
@ivar ttl: The maximum number of seconds which this record should be
cached.
@see: U{http://www.faqs.org/rfcs/rfc2915.html}
"""
TYPE = NAPTR
compareAttributes = ('order', 'preference', 'flags', 'service', 'regexp',
'replacement')
fancybasename = 'NAPTR'
showAttributes = ('order', 'preference', ('flags', 'flags', '%s'),
('service', 'service', '%s'), ('regexp', 'regexp', '%s'),
('replacement', 'replacement', '%s'), 'ttl')
def __init__(self, order=0, preference=0, flags=b'', service=b'', regexp=b'',
replacement=b'', ttl=None):
self.order = int(order)
self.preference = int(preference)
self.flags = Charstr(flags)
self.service = Charstr(service)
self.regexp = Charstr(regexp)
self.replacement = Name(replacement)
self.ttl = str2time(ttl)
def encode(self, strio, compDict=None):
strio.write(struct.pack('!HH', self.order, self.preference))
# This can't be compressed
self.flags.encode(strio, None)
self.service.encode(strio, None)
self.regexp.encode(strio, None)
self.replacement.encode(strio, None)
def decode(self, strio, length=None):
r = struct.unpack('!HH', readPrecisely(strio, struct.calcsize('!HH')))
self.order, self.preference = r
self.flags = Charstr()
self.service = Charstr()
self.regexp = Charstr()
self.replacement = Name()
self.flags.decode(strio)
self.service.decode(strio)
self.regexp.decode(strio)
self.replacement.decode(strio)
def __hash__(self):
return hash((
self.order, self.preference, self.flags,
self.service, self.regexp, self.replacement))
@implementer(IEncodable, IRecord)
class Record_AFSDB(tputil.FancyStrMixin, tputil.FancyEqMixin):
"""
Map from a domain name to the name of an AFS cell database server.
@type subtype: C{int}
@ivar subtype: In the case of subtype 1, the host has an AFS version 3.0
Volume Location Server for the named AFS cell. In the case of subtype
2, the host has an authenticated name server holding the cell-root
directory node for the named DCE/NCA cell.
@type hostname: L{Name}
@ivar hostname: The domain name of a host that has a server for the cell
named by this record.
@type ttl: C{int}
@ivar ttl: The maximum number of seconds which this record should be
cached.
@see: U{http://www.faqs.org/rfcs/rfc1183.html}
"""
TYPE = AFSDB
fancybasename = 'AFSDB'
compareAttributes = ('subtype', 'hostname', 'ttl')
showAttributes = ('subtype', ('hostname', 'hostname', '%s'), 'ttl')
def __init__(self, subtype=0, hostname=b'', ttl=None):
self.subtype = int(subtype)
self.hostname = Name(hostname)
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
strio.write(struct.pack('!H', self.subtype))
self.hostname.encode(strio, compDict)
def decode(self, strio, length = None):
r = struct.unpack('!H', readPrecisely(strio, struct.calcsize('!H')))
self.subtype, = r
self.hostname.decode(strio)
def __hash__(self):
return hash((self.subtype, self.hostname))
@implementer(IEncodable, IRecord)
class Record_RP(tputil.FancyEqMixin, tputil.FancyStrMixin):
"""
The responsible person for a domain.
@type mbox: L{Name}
@ivar mbox: A domain name that specifies the mailbox for the responsible
person.
@type txt: L{Name}
@ivar txt: A domain name for which TXT RR's exist (indirection through
which allows information sharing about the contents of this RP record).
@type ttl: C{int}
@ivar ttl: The maximum number of seconds which this record should be
cached.
@see: U{http://www.faqs.org/rfcs/rfc1183.html}
"""
TYPE = RP
fancybasename = 'RP'
compareAttributes = ('mbox', 'txt', 'ttl')
showAttributes = (('mbox', 'mbox', '%s'), ('txt', 'txt', '%s'), 'ttl')
def __init__(self, mbox=b'', txt=b'', ttl=None):
self.mbox = Name(mbox)
self.txt = Name(txt)
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
self.mbox.encode(strio, compDict)
self.txt.encode(strio, compDict)
def decode(self, strio, length = None):
self.mbox = Name()
self.txt = Name()
self.mbox.decode(strio)
self.txt.decode(strio)
def __hash__(self):
return hash((self.mbox, self.txt))
@implementer(IEncodable, IRecord)
class Record_HINFO(tputil.FancyStrMixin, tputil.FancyEqMixin):
"""
Host information.
@type cpu: C{str}
@ivar cpu: Specifies the CPU type.
@type os: C{str}
@ivar os: Specifies the OS.
@type ttl: C{int}
@ivar ttl: The maximum number of seconds which this record should be
cached.
"""
TYPE = HINFO
fancybasename = 'HINFO'
showAttributes = (('cpu', _nicebytes), ('os', _nicebytes), 'ttl')
compareAttributes = ('cpu', 'os', 'ttl')
def __init__(self, cpu='', os='', ttl=None):
self.cpu, self.os = cpu, os
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
strio.write(struct.pack('!B', len(self.cpu)) + self.cpu)
strio.write(struct.pack('!B', len(self.os)) + self.os)
def decode(self, strio, length = None):
cpu = struct.unpack('!B', readPrecisely(strio, 1))[0]
self.cpu = readPrecisely(strio, cpu)
os = struct.unpack('!B', readPrecisely(strio, 1))[0]
self.os = readPrecisely(strio, os)
def __eq__(self, other):
if isinstance(other, Record_HINFO):
return (self.os.lower() == other.os.lower() and
self.cpu.lower() == other.cpu.lower() and
self.ttl == other.ttl)
return NotImplemented
def __hash__(self):
return hash((self.os.lower(), self.cpu.lower()))
@implementer(IEncodable, IRecord)
class Record_MINFO(tputil.FancyEqMixin, tputil.FancyStrMixin):
"""
Mailbox or mail list information.
This is an experimental record type.
@type rmailbx: L{Name}
@ivar rmailbx: A domain-name which specifies a mailbox which is responsible
for the mailing list or mailbox. If this domain name names the root,
the owner of the MINFO RR is responsible for itself.
@type emailbx: L{Name}
@ivar emailbx: A domain-name which specifies a mailbox which is to receive
error messages related to the mailing list or mailbox specified by the
owner of the MINFO record. If this domain name names the root, errors
should be returned to the sender of the message.
@type ttl: C{int}
@ivar ttl: The maximum number of seconds which this record should be
cached.
"""
TYPE = MINFO
rmailbx = None
emailbx = None
fancybasename = 'MINFO'
compareAttributes = ('rmailbx', 'emailbx', 'ttl')
showAttributes = (('rmailbx', 'responsibility', '%s'),
('emailbx', 'errors', '%s'),
'ttl')
def __init__(self, rmailbx=b'', emailbx=b'', ttl=None):
self.rmailbx, self.emailbx = Name(rmailbx), Name(emailbx)
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
self.rmailbx.encode(strio, compDict)
self.emailbx.encode(strio, compDict)
def decode(self, strio, length = None):
self.rmailbx, self.emailbx = Name(), Name()
self.rmailbx.decode(strio)
self.emailbx.decode(strio)
def __hash__(self):
return hash((self.rmailbx, self.emailbx))
@implementer(IEncodable, IRecord)
class Record_MX(tputil.FancyStrMixin, tputil.FancyEqMixin):
"""
Mail exchange.
@type preference: C{int}
@ivar preference: Specifies the preference given to this RR among others at
the same owner. Lower values are preferred.
@type name: L{Name}
@ivar name: A domain-name which specifies a host willing to act as a mail
exchange.
@type ttl: C{int}
@ivar ttl: The maximum number of seconds which this record should be
cached.
"""
TYPE = MX
fancybasename = 'MX'
compareAttributes = ('preference', 'name', 'ttl')
showAttributes = ('preference', ('name', 'name', '%s'), 'ttl')
def __init__(self, preference=0, name=b'', ttl=None, **kwargs):
self.preference, self.name = int(preference), Name(kwargs.get('exchange', name))
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
strio.write(struct.pack('!H', self.preference))
self.name.encode(strio, compDict)
def decode(self, strio, length = None):
self.preference = struct.unpack('!H', readPrecisely(strio, 2))[0]
self.name = Name()
self.name.decode(strio)
def __hash__(self):
return hash((self.preference, self.name))
@implementer(IEncodable, IRecord)
class Record_TXT(tputil.FancyEqMixin, tputil.FancyStrMixin):
"""
Freeform text.
@type data: C{list} of C{bytes}
@ivar data: Freeform text which makes up this record.
@type ttl: C{int}
@ivar ttl: The maximum number of seconds which this record should be cached.
"""
TYPE = TXT
fancybasename = 'TXT'
showAttributes = (('data', _nicebyteslist), 'ttl')
compareAttributes = ('data', 'ttl')
def __init__(self, *data, **kw):
self.data = list(data)
# arg man python sucks so bad
self.ttl = str2time(kw.get('ttl', None))
def encode(self, strio, compDict=None):
for d in self.data:
strio.write(struct.pack('!B', len(d)) + d)
def decode(self, strio, length=None):
soFar = 0
self.data = []
while soFar < length:
L = struct.unpack('!B', readPrecisely(strio, 1))[0]
self.data.append(readPrecisely(strio, L))
soFar += L + 1
if soFar != length:
log.msg(
"Decoded %d bytes in %s record, but rdlength is %d" % (
soFar, self.fancybasename, length
)
)
def __hash__(self):
return hash(tuple(self.data))
@implementer(IEncodable, IRecord)
class UnknownRecord(tputil.FancyEqMixin, tputil.FancyStrMixin, object):
"""
Encapsulate the wire data for unknown record types so that they can
pass through the system unchanged.
@type data: C{bytes}
@ivar data: Wire data which makes up this record.
@type ttl: C{int}
@ivar ttl: The maximum number of seconds which this record should be cached.
@since: 11.1
"""
fancybasename = 'UNKNOWN'
compareAttributes = ('data', 'ttl')
showAttributes = (('data', _nicebytes), 'ttl')
def __init__(self, data=b'', ttl=None):
self.data = data
self.ttl = str2time(ttl)
def encode(self, strio, compDict=None):
"""
Write the raw bytes corresponding to this record's payload to the
stream.
"""
strio.write(self.data)
def decode(self, strio, length=None):
"""
Load the bytes which are part of this record from the stream and store
them unparsed and unmodified.
"""
if length is None:
raise Exception('must know length for unknown record types')
self.data = readPrecisely(strio, length)
def __hash__(self):
return hash((self.data, self.ttl))
class Record_SPF(Record_TXT):
"""
Structurally, freeform text. Semantically, a policy definition, formatted
as defined in U{rfc 4408<http://www.faqs.org/rfcs/rfc4408.html>}.
@type data: C{list} of C{str}
@ivar data: Freeform text which makes up this record.
@type ttl: C{int}
@ivar ttl: The maximum number of seconds which this record should be cached.
"""
TYPE = SPF
fancybasename = 'SPF'
class Message:
"""
L{Message} contains all the information represented by a single
DNS request or response.
@ivar rCode: A response code, used to indicate success or failure in a
message which is a response from a server to a client request.
@type rCode: C{0 <= int < 16}
"""
headerFmt = "!H2B4H"
headerSize = struct.calcsize(headerFmt)
# Question, answer, additional, and nameserver lists
queries = answers = add = ns = None
def __init__(self, id=0, answer=0, opCode=0, recDes=0, recAv=0,
auth=0, rCode=OK, trunc=0, maxSize=512):
self.maxSize = maxSize
self.id = id
self.answer = answer
self.opCode = opCode
self.auth = auth
self.trunc = trunc
self.recDes = recDes
self.recAv = recAv
self.rCode = rCode
self.queries = []
self.answers = []
self.authority = []
self.additional = []
def addQuery(self, name, type=ALL_RECORDS, cls=IN):
"""
Add another query to this Message.
@type name: C{bytes}
@param name: The name to query.
@type type: C{int}
@param type: Query type
@type cls: C{int}
@param cls: Query class
"""
self.queries.append(Query(name, type, cls))
def encode(self, strio):
compDict = {}
body_tmp = BytesIO()
for q in self.queries:
q.encode(body_tmp, compDict)
for q in self.answers:
q.encode(body_tmp, compDict)
for q in self.authority:
q.encode(body_tmp, compDict)
for q in self.additional:
q.encode(body_tmp, compDict)
body = body_tmp.getvalue()
size = len(body) + self.headerSize
if self.maxSize and size > self.maxSize:
self.trunc = 1
body = body[:self.maxSize - self.headerSize]
byte3 = (( ( self.answer & 1 ) << 7 )
| ((self.opCode & 0xf ) << 3 )
| ((self.auth & 1 ) << 2 )
| ((self.trunc & 1 ) << 1 )
| ( self.recDes & 1 ) )
byte4 = ( ( (self.recAv & 1 ) << 7 )
| (self.rCode & 0xf ) )
strio.write(struct.pack(self.headerFmt, self.id, byte3, byte4,
len(self.queries), len(self.answers),
len(self.authority), len(self.additional)))
strio.write(body)
def decode(self, strio, length=None):
self.maxSize = 0
header = readPrecisely(strio, self.headerSize)
r = struct.unpack(self.headerFmt, header)
self.id, byte3, byte4, nqueries, nans, nns, nadd = r
self.answer = ( byte3 >> 7 ) & 1
self.opCode = ( byte3 >> 3 ) & 0xf
self.auth = ( byte3 >> 2 ) & 1
self.trunc = ( byte3 >> 1 ) & 1
self.recDes = byte3 & 1
self.recAv = ( byte4 >> 7 ) & 1
self.rCode = byte4 & 0xf
self.queries = []
for i in range(nqueries):
q = Query()
try:
q.decode(strio)
except EOFError:
return
self.queries.append(q)
items = ((self.answers, nans), (self.authority, nns), (self.additional, nadd))
for (l, n) in items:
self.parseRecords(l, n, strio)
def parseRecords(self, list, num, strio):
for i in range(num):
header = RRHeader(auth=self.auth)
try:
header.decode(strio)
except EOFError:
return
t = self.lookupRecordType(header.type)
if not t:
continue
header.payload = t(ttl=header.ttl)
try:
header.payload.decode(strio, header.rdlength)
except EOFError:
return
list.append(header)
# Create a mapping from record types to their corresponding Record_*
# classes. This relies on the global state which has been created so
# far in initializing this module (so don't define Record classes after
# this).
_recordTypes = {}
for name in globals():
if name.startswith('Record_'):
_recordTypes[globals()[name].TYPE] = globals()[name]
# Clear the iteration variable out of the class namespace so it
# doesn't become an attribute.
del name
def lookupRecordType(self, type):
"""
Retrieve the L{IRecord} implementation for the given record type.
@param type: A record type, such as L{A} or L{NS}.
@type type: C{int}
@return: An object which implements L{IRecord} or C{None} if none
can be found for the given type.
@rtype: L{types.ClassType}
"""
return self._recordTypes.get(type, UnknownRecord)
def toStr(self):
"""
Encode this L{Message} into a byte string in the format described by RFC
1035.
@rtype: C{bytes}
"""
strio = BytesIO()
self.encode(strio)
return strio.getvalue()
def fromStr(self, str):
"""
Decode a byte string in the format described by RFC 1035 into this
L{Message}.
@param str: L{bytes}
"""
strio = BytesIO(str)
self.decode(strio)
class DNSMixin(object):
"""
DNS protocol mixin shared by UDP and TCP implementations.
@ivar _reactor: A L{IReactorTime} and L{IReactorUDP} provider which will
be used to issue DNS queries and manage request timeouts.
"""
id = None
liveMessages = None
def __init__(self, controller, reactor=None):
self.controller = controller
self.id = random.randrange(2 ** 10, 2 ** 15)
if reactor is None:
from twisted.internet import reactor
self._reactor = reactor
def pickID(self):
"""
Return a unique ID for queries.
"""
while True:
id = randomSource()
if id not in self.liveMessages:
return id
def callLater(self, period, func, *args):
"""
Wrapper around reactor.callLater, mainly for test purpose.
"""
return self._reactor.callLater(period, func, *args)
def _query(self, queries, timeout, id, writeMessage):
"""
Send out a message with the given queries.
@type queries: C{list} of C{Query} instances
@param queries: The queries to transmit
@type timeout: C{int} or C{float}
@param timeout: How long to wait before giving up
@type id: C{int}
@param id: Unique key for this request
@type writeMessage: C{callable}
@param writeMessage: One-parameter callback which writes the message
@rtype: C{Deferred}
@return: a C{Deferred} which will be fired with the result of the
query, or errbacked with any errors that could happen (exceptions
during writing of the query, timeout errors, ...).
"""
m = Message(id, recDes=1)
m.queries = queries
try:
writeMessage(m)
except:
return defer.fail()
resultDeferred = defer.Deferred()
cancelCall = self.callLater(timeout, self._clearFailed, resultDeferred, id)
self.liveMessages[id] = (resultDeferred, cancelCall)
return resultDeferred
def _clearFailed(self, deferred, id):
"""
Clean the Deferred after a timeout.
"""
try:
del self.liveMessages[id]
except KeyError:
pass
deferred.errback(failure.Failure(DNSQueryTimeoutError(id)))
class DNSDatagramProtocol(DNSMixin, protocol.DatagramProtocol):
"""
DNS protocol over UDP.
"""
resends = None
def stopProtocol(self):
"""
Stop protocol: reset state variables.
"""
self.liveMessages = {}
self.resends = {}
self.transport = None
def startProtocol(self):
"""
Upon start, reset internal state.
"""
self.liveMessages = {}
self.resends = {}
def writeMessage(self, message, address):
"""
Send a message holding DNS queries.
@type message: L{Message}
"""
self.transport.write(message.toStr(), address)
def startListening(self):
self._reactor.listenUDP(0, self, maxPacketSize=512)
def datagramReceived(self, data, addr):
"""
Read a datagram, extract the message in it and trigger the associated
Deferred.
"""
m = Message()
try:
m.fromStr(data)
except EOFError:
log.msg("Truncated packet (%d bytes) from %s" % (len(data), addr))
return
except:
# Nothing should trigger this, but since we're potentially
# invoking a lot of different decoding methods, we might as well
# be extra cautious. Anything that triggers this is itself
# buggy.
log.err(failure.Failure(), "Unexpected decoding error")
return
if m.id in self.liveMessages:
d, canceller = self.liveMessages[m.id]
del self.liveMessages[m.id]
canceller.cancel()
# XXX we shouldn't need this hack of catching exception on callback()
try:
d.callback(m)
except:
log.err()
else:
if m.id not in self.resends:
self.controller.messageReceived(m, self, addr)
def removeResend(self, id):
"""
Mark message ID as no longer having duplication suppression.
"""
try:
del self.resends[id]
except KeyError:
pass
def query(self, address, queries, timeout=10, id=None):
"""
Send out a message with the given queries.
@type address: C{tuple} of C{str} and C{int}
@param address: The address to which to send the query
@type queries: C{list} of C{Query} instances
@param queries: The queries to transmit
@rtype: C{Deferred}
"""
if not self.transport:
# XXX transport might not get created automatically, use callLater?
try:
self.startListening()
except CannotListenError:
return defer.fail()
if id is None:
id = self.pickID()
else:
self.resends[id] = 1
def writeMessage(m):
self.writeMessage(m, address)
return self._query(queries, timeout, id, writeMessage)
class DNSProtocol(DNSMixin, protocol.Protocol):
"""
DNS protocol over TCP.
"""
length = None
buffer = b''
def writeMessage(self, message):
"""
Send a message holding DNS queries.
@type message: L{Message}
"""
s = message.toStr()
self.transport.write(struct.pack('!H', len(s)) + s)
def connectionMade(self):
"""
Connection is made: reset internal state, and notify the controller.
"""
self.liveMessages = {}
self.controller.connectionMade(self)
def connectionLost(self, reason):
"""
Notify the controller that this protocol is no longer
connected.
"""
self.controller.connectionLost(self)
def dataReceived(self, data):
self.buffer += data
while self.buffer:
if self.length is None and len(self.buffer) >= 2:
self.length = struct.unpack('!H', self.buffer[:2])[0]
self.buffer = self.buffer[2:]
if len(self.buffer) >= self.length:
myChunk = self.buffer[:self.length]
m = Message()
m.fromStr(myChunk)
try:
d, canceller = self.liveMessages[m.id]
except KeyError:
self.controller.messageReceived(m, self)
else:
del self.liveMessages[m.id]
canceller.cancel()
# XXX we shouldn't need this hack
try:
d.callback(m)
except:
log.err()
self.buffer = self.buffer[self.length:]
self.length = None
else:
break
def query(self, queries, timeout=60):
"""
Send out a message with the given queries.
@type queries: C{list} of C{Query} instances
@param queries: The queries to transmit
@rtype: C{Deferred}
"""
id = self.pickID()
return self._query(queries, timeout, id, self.writeMessage)
|
biddisco/VTK
|
ThirdParty/Twisted/twisted/names/dns.py
|
Python
|
bsd-3-clause
| 58,390 | 0.004436 |
from typing import Union
from asphalt.core.context import Context
from wsproto.connection import WSConnection, ConnectionType
from wsproto.events import ConnectionRequested, ConnectionClosed, DataReceived
from asphalt.web.api import AbstractEndpoint
from asphalt.web.request import HTTPRequest
from asphalt.web.servers.base import BaseHTTPClientConnection
class WebSocketEndpoint(AbstractEndpoint):
"""
Implements websocket endpoints.
Subprotocol negotiation is currently not supported.
"""
__slots__ = ('ctx', '_client', '_ws')
def __init__(self, ctx: Context, client: BaseHTTPClientConnection):
self.ctx = ctx
self._client = client
self._ws = WSConnection(ConnectionType.SERVER)
def _process_ws_events(self):
for event in self._ws.events():
if isinstance(event, ConnectionRequested):
self._ws.accept(event)
self.on_connect()
elif isinstance(event, DataReceived):
self.on_data(event.data)
elif isinstance(event, ConnectionClosed):
self.on_close()
bytes_to_send = self._ws.bytes_to_send()
if bytes_to_send:
self._client.write(bytes_to_send)
def begin_request(self, request: HTTPRequest):
trailing_data = self._client.upgrade()
self._ws.receive_bytes(trailing_data)
self._process_ws_events()
def receive_body_data(self, data: bytes) -> None:
self._ws.receive_bytes(data)
self._process_ws_events()
def send_message(self, payload: Union[str, bytes]) -> None:
"""
Send a message to the client.
:param payload: either a unicode string or a bytestring
"""
self._ws.send_data(payload)
bytes_to_send = self._ws.bytes_to_send()
self._client.write(bytes_to_send)
def close(self) -> None:
"""Close the websocket."""
self._ws.close()
self._process_ws_events()
def on_connect(self) -> None:
"""Called when the websocket handshake has been done."""
def on_close(self) -> None:
"""Called when the connection has been closed."""
def on_data(self, data: bytes) -> None:
"""Called when there is new data from the peer."""
|
asphalt-framework/asphalt-web
|
asphalt/web/websocket.py
|
Python
|
apache-2.0
| 2,282 | 0 |
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
from resource_management import *
def _ldap_common():
import params
File(os.path.join(params.knox_conf_dir, 'ldap-log4j.properties'),
mode=params.mode,
group=params.knox_group,
owner=params.knox_user,
content=params.ldap_log4j
)
File(os.path.join(params.knox_conf_dir, 'users.ldif'),
mode=params.mode,
group=params.knox_group,
owner=params.knox_user,
content=params.users_ldif
)
#@OsFamilyFuncImpl(os_#family=OSConst.WINSRV_FAMILY)
#def ldap():
# import params
#
# # Manually overriding service logon user & password set by the installation package
# ServiceConfig(params.knox_ldap_win_service_name,
# action="change_user",
# username = params.knox_user,
# password = Script.get_password(params.knox_user))
#
# _ldap_common()
#@OsFamilyFuncImpl(os_family=OsFamilyImpl.DEFAULT)
def ldap():
_ldap_common()
|
arenadata/ambari
|
ambari-server/src/main/resources/stacks/BigInsights/4.2/services/KNOX/package/scripts/ldap.py
|
Python
|
apache-2.0
| 1,729 | 0.004627 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-20 16:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('billjobs', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='service',
name='is_available',
field=models.BooleanField(default=True, verbose_name='Is available ?'),
),
]
|
ioO/billjobs
|
billjobs/migrations/0002_service_is_available.py
|
Python
|
mit
| 478 | 0.002092 |
from __future__ import division
from ._base import Descriptor
from ._graph_matrix import Radius3D as CRadius3D
from ._graph_matrix import Diameter3D as CDiameter3D
__all__ = ("Diameter3D", "Radius3D", "GeometricalShapeIndex", "PetitjeanIndex3D")
class GeometricalIndexBase(Descriptor):
__slots__ = ()
explicit_hydrogens = True
require_3D = True
@classmethod
def preset(cls, version):
yield cls()
def parameters(self):
return ()
rtype = float
class Radius3D(GeometricalIndexBase):
r"""geometric radius descriptor."""
since = "1.0.0"
__slots__ = ()
def description(self):
return "geometric radius"
def __str__(self):
return "GeomRadius"
def dependencies(self):
return {"R": CRadius3D(self.explicit_hydrogens)}
def calculate(self, R):
return R
class Diameter3D(GeometricalIndexBase):
r"""geometric diameter descriptor."""
since = "1.0.0"
__slots__ = ()
def description(self):
return "geometric diameter"
def __str__(self):
return "GeomDiameter"
def dependencies(self):
return {"D": CDiameter3D(self.explicit_hydrogens)}
def calculate(self, D):
return D
class GeometricalShapeIndex(GeometricalIndexBase):
r"""geometrical shape index descriptor.
.. math::
I_{\rm topo} = \frac{D - R}{R}
where
:math:`R` is geometric radius,
:math:`D` is geometric diameter.
:returns: NaN when :math:`R = 0`
"""
since = "1.0.0"
__slots__ = ()
def description(self):
return "geometrical shape index"
def __str__(self):
return "GeomShapeIndex"
def dependencies(self):
return {
"D": CDiameter3D(self.explicit_hydrogens),
"R": CRadius3D(self.explicit_hydrogens),
}
def calculate(self, R, D):
with self.rethrow_zerodiv():
return (D - R) / (R)
class PetitjeanIndex3D(GeometricalShapeIndex):
r"""geometric Petitjean index descriptor.
.. math::
I_{\rm Petitjean} = \frac{D - R}{D}
where
:math:`R` is geometric radius,
:math:`D` is geometric diameter.
:returns: NaN when :math:`D = 0`
"""
since = "1.0.0"
__slots__ = ()
def description(self):
return "geometric Petitjean index"
def __str__(self):
return "GeomPetitjeanIndex"
def calculate(self, R, D):
with self.rethrow_zerodiv():
return (D - R) / (D)
|
mordred-descriptor/mordred
|
mordred/GeometricalIndex.py
|
Python
|
bsd-3-clause
| 2,504 | 0.000399 |
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Yannick Vaucher
# Copyright 2013 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{'name': 'Report to printer - Paper tray selection',
'version': '8.0.1.0.1',
'category': 'Printer',
'author': "Camptocamp,Odoo Community Association (OCA)",
'maintainer': 'Camptocamp',
'website': 'http://www.camptocamp.com/',
'license': 'AGPL-3',
'depends': ['base_report_to_printer',
],
'data': [
'users_view.xml',
'ir_report_view.xml',
'printer_view.xml',
'report_xml_action_view.xml',
'security/ir.model.access.csv',
],
'external_dependencies': {
'python': ['cups'],
},
'installable': True,
'auto_install': False,
'application': True,
}
|
rosenvladimirov/addons
|
printer_tray/__openerp__.py
|
Python
|
agpl-3.0
| 1,538 | 0 |
# -*- coding: utf-8 -*-
"""
Module for the generation of docx format documents.
---
type:
python_module
validation_level:
v00_minimum
protection:
k00_public
copyright:
"Copyright 2016 High Integrity Artificial Intelligence Systems"
license:
"Licensed under the Apache License, Version 2.0 (the License);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an AS IS BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License."
...
"""
import jinja2
# -----------------------------------------------------------------------------
def build(_, section_list, filepath):
"""
Build and save the specified document.
"""
environment = jinja2.Environment(
loader = jinja2.PackageLoader(
'da.report', 'templates'),
trim_blocks = True,
lstrip_blocks = True)
template = environment.get_template('engineering_document.template.html')
# Filter out empty sections
filtered_list = []
for section in section_list:
if section['level'] != 1 and len(section['para']) == 0:
continue
filtered_list.append(section)
html = template.render( # pylint: disable=E1101
section_list = filtered_list)
with open(filepath, 'wt') as file:
file.write(html)
# _add_title_section(document, doc_data['_metadata'])
# _add_toc_section(document)
# for item in sorted(_generate_content_items(doc_data),
# key = _doc_data_sortkey):
# if item['section_level'] == 1:
# _add_content_section(document)
# if 0 < len(item['paragraph_list']):
# _add_content_para(document,
# level = item['section_level'],
# title = item['section_title'],
# type = item['section_type'],
# content = item['paragraph_list'])
# else:
# print('Skipping section: ' + item['section_title'])
# # Save the document.
# da.util.ensure_dir_exists(os.path.dirname(filepath))
# document.save(filepath)
|
wtpayne/hiai
|
a3_src/h70_internal/da/report/html_builder.py
|
Python
|
apache-2.0
| 2,607 | 0.003836 |
# -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# 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.
"""
Module for various constants
"""
PIERCING_DAMAGE = 'piercing'
CRUSHING_DAMAGE = 'crushing'
SLASHING_DAMAGE = 'slashing'
ELEMENTAL_DAMAGE = 'elemental'
DARK_DAMAGE = 'dark'
LIGHT_DAMAGE = 'light'
POISON_DAMAGE = 'poison'
INSTANT_ACTION = 1
FAST_ACTION = 2
NORMAL_ACTION = 4
SLOW_ACTION = 8
LONG_ACTION = 16
|
tuturto/pyherc
|
src/pyherc/rules/constants.py
|
Python
|
mit
| 1,438 | 0.002086 |
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
import unittest
from mock import Mock
from mock import patch
from airflow import configuration
from airflow.contrib.hooks.jira_hook import JiraHook
from airflow import models
from airflow.utils import db
jira_client_mock = Mock(
name="jira_client"
)
class TestJiraHook(unittest.TestCase):
def setUp(self):
configuration.load_test_config()
db.merge_conn(
models.Connection(
conn_id='jira_default', conn_type='jira',
host='https://localhost/jira/', port=443,
extra='{"verify": "False", "project": "AIRFLOW"}'))
@patch("airflow.contrib.hooks.jira_hook.JIRA", autospec=True,
return_value=jira_client_mock)
def test_jira_client_connection(self, jira_mock):
jira_hook = JiraHook()
self.assertTrue(jira_mock.called)
self.assertIsInstance(jira_hook.client, Mock)
self.assertEqual(jira_hook.client.name, jira_mock.return_value.name)
if __name__ == '__main__':
unittest.main()
|
akosel/incubator-airflow
|
tests/contrib/hooks/test_jira_hook.py
|
Python
|
apache-2.0
| 1,861 | 0 |
from django.conf.urls import url
from django.views.decorators.csrf import csrf_exempt
from . import views
urlpatterns = [
url(r"^$", csrf_exempt(views.SamlView.as_view())),
url(r"^metadata/$", views.serve_metadata),
]
|
FinnStutzenstein/OpenSlides
|
server/openslides/saml/urls.py
|
Python
|
mit
| 229 | 0 |
# proxy module
from __future__ import absolute_import
from mayavi.modules.slice_unstructured_grid import *
|
enthought/etsproxy
|
enthought/mayavi/modules/slice_unstructured_grid.py
|
Python
|
bsd-3-clause
| 107 | 0 |
import sys
if __name__ == "__main__":
print("Genoa python script")
sys.exit(0)
|
sfu-ireceptor/gateway
|
resources/agave_apps/genoa/genoa.py
|
Python
|
lgpl-3.0
| 88 | 0 |
#!/usr/bin/python -u
# -*- coding: utf-8 -*-
import libxml2
import time
import traceback
import sys
import logging
from pyxmpp.all import JID,Iq,Presence,Message,StreamError
from pyxmpp.jabber.all import Client
class Disconnected(Exception):
pass
class MyClient(Client):
def session_started(self):
self.stream.send(Presence())
def idle(self):
print "idle"
Client.idle(self)
if self.session_established:
target=JID("jajcus",s.jid.domain)
self.stream.send(Message(to_jid=target,body=unicode("Teścik","utf-8")))
def post_disconnect(self):
print "Disconnected"
raise Disconnected
logger=logging.getLogger()
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)
libxml2.debugMemory(1)
print "creating stream..."
s=MyClient(jid=JID("test@localhost/Test"),password=u"123",auth_methods=["sasl:DIGEST-MD5","digest"])
print "connecting..."
s.connect()
print "processing..."
try:
try:
s.loop(1)
finally:
s.disconnect()
except KeyboardInterrupt:
traceback.print_exc(file=sys.stderr)
except (StreamError,Disconnected),e:
raise
libxml2.cleanupParser()
if libxml2.debugMemory(1) == 0:
print "OK"
else:
print "Memory leak %d bytes" % (libxml2.debugMemory(1))
libxml2.dumpMemory()
# vi: sts=4 et sw=4
|
Jajcus/pyxmpp
|
examples/c2s_test.py
|
Python
|
lgpl-2.1
| 1,349 | 0.014837 |
# Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.compute.floating_ips import base
from tempest.common.utils.data_utils import rand_name
from tempest import exceptions
from tempest.test import attr
class FloatingIPsTestJSON(base.BaseFloatingIPsTest):
_interface = 'json'
server_id = None
floating_ip = None
@classmethod
def setUpClass(cls):
super(FloatingIPsTestJSON, cls).setUpClass()
cls.client = cls.floating_ips_client
#cls.servers_client = cls.servers_client
# Server creation
resp, server = cls.create_test_server(wait_until='ACTIVE')
cls.server_id = server['id']
# Floating IP creation
resp, body = cls.client.create_floating_ip()
cls.floating_ip_id = body['id']
cls.floating_ip = body['ip']
@classmethod
def tearDownClass(cls):
# Deleting the floating IP which is created in this method
resp, body = cls.client.delete_floating_ip(cls.floating_ip_id)
super(FloatingIPsTestJSON, cls).tearDownClass()
@attr(type='gate')
def test_allocate_floating_ip(self):
# Positive test:Allocation of a new floating IP to a project
# should be successful
resp, body = self.client.create_floating_ip()
floating_ip_id_allocated = body['id']
self.addCleanup(self.client.delete_floating_ip,
floating_ip_id_allocated)
self.assertEqual(200, resp.status)
resp, floating_ip_details = \
self.client.get_floating_ip_details(floating_ip_id_allocated)
# Checking if the details of allocated IP is in list of floating IP
resp, body = self.client.list_floating_ips()
self.assertIn(floating_ip_details, body)
@attr(type='gate')
def test_delete_floating_ip(self):
# Positive test:Deletion of valid floating IP from project
# should be successful
# Creating the floating IP that is to be deleted in this method
resp, floating_ip_body = self.client.create_floating_ip()
# Storing the details of floating IP before deleting it
cli_resp = self.client.get_floating_ip_details(floating_ip_body['id'])
resp, floating_ip_details = cli_resp
# Deleting the floating IP from the project
resp, body = self.client.delete_floating_ip(floating_ip_body['id'])
self.assertEqual(202, resp.status)
# Check it was really deleted.
self.client.wait_for_resource_deletion(floating_ip_body['id'])
@attr(type='gate')
def test_associate_disassociate_floating_ip(self):
# Positive test:Associate and disassociate the provided floating IP
# to a specific server should be successful
# Association of floating IP to fixed IP address
resp, body = self.client.associate_floating_ip_to_server(
self.floating_ip,
self.server_id)
self.assertEqual(202, resp.status)
# Disassociation of floating IP that was associated in this method
resp, body = self.client.disassociate_floating_ip_from_server(
self.floating_ip,
self.server_id)
self.assertEqual(202, resp.status)
@attr(type='gate')
def test_associate_already_associated_floating_ip(self):
# positive test:Association of an already associated floating IP
# to specific server should change the association of the Floating IP
# Create server so as to use for Multiple association
new_name = rand_name('floating_server')
resp, body = self.servers_client.create_server(new_name,
self.image_ref,
self.flavor_ref)
self.servers_client.wait_for_server_status(body['id'], 'ACTIVE')
self.new_server_id = body['id']
# Associating floating IP for the first time
resp, _ = self.client.associate_floating_ip_to_server(
self.floating_ip,
self.server_id)
# Associating floating IP for the second time
resp, body = self.client.associate_floating_ip_to_server(
self.floating_ip,
self.new_server_id)
self.addCleanup(self.servers_client.delete_server, self.new_server_id)
if (resp['status'] is not None):
self.addCleanup(self.client.disassociate_floating_ip_from_server,
self.floating_ip,
self.new_server_id)
# Make sure no longer associated with old server
self.assertRaises((exceptions.NotFound,
exceptions.UnprocessableEntity),
self.client.disassociate_floating_ip_from_server,
self.floating_ip, self.server_id)
class FloatingIPsTestXML(FloatingIPsTestJSON):
_interface = 'xml'
|
BeenzSyed/tempest
|
tempest/api/compute/floating_ips/test_floating_ips_actions.py
|
Python
|
apache-2.0
| 5,488 | 0.000182 |
resource_id = "celery-1"
_install_script = """
[ { "id": "celery-1",
"key": {"name": "Celery", "version": "2.3"},
"config_port": {
"password": "engage_129",
"username": "engage_celery",
"vhost": "engage_celery_vhost"
},
"input_ports": {
"broker": {
"BROKER_HOST": "${hostname}",
"BROKER_PORT": "5672",
"broker": "rabbitmqctl"
},
"host": {
"cpu_arch": "x86_64",
"genforma_home": "${deployment_home}",
"hostname": "${hostname}",
"log_directory": "${deployment_home}/log",
"os_type": "mac-osx",
"os_user_name": "${username}",
"private_ip": null,
"sudo_password": "GenForma/${username}/sudo_password"
},
"pip": {
"pipbin": "${deployment_home}/python/bin/pip"
},
"python": {
"PYTHONPATH": "${deployment_home}/python/lib/python2.7/site-packages/",
"home": "${deployment_home}/python/bin/python",
"python_bin_dir": "${deployment_home}/python/bin",
"type": "python",
"version": "2.7"
},
"setuptools": {
"easy_install": "${deployment_home}/python/bin/easy_install"
}
},
"output_ports": {
"celery": {
"broker": "rabbitmqctl",
"password": "engage_129",
"username": "engage_celery",
"vhost": "engage_celery_vhost"
}
},
"inside": {
"id": "${hostname}",
"key": {"name": "mac-osx", "version": "10.6"},
"port_mapping": {
"host": "host"
}
},
"environment": [
{
"id": "rabbitmq-1",
"key": {"name": "rabbitmq", "version": "2.4"},
"port_mapping": {
"broker": "broker"
}
},
{
"id": "python-1",
"key": {"name": "python", "version": "2.7"},
"port_mapping": {
"python": "python"
}
},
{
"id": "__GF_inst_2",
"key": {"name": "pip", "version": "any"},
"port_mapping": {
"pip": "pip"
}
},
{
"id": "setuptools-1",
"key": {"name": "setuptools", "version": "0.6"},
"port_mapping": {
"setuptools": "setuptools"
}
}
]
}
]
"""
def get_install_script():
return _install_script
def get_password_data():
return {}
|
quaddra/engage
|
python_pkg/engage/drivers/genforma/drivertest_celery.py
|
Python
|
apache-2.0
| 2,355 | 0.001274 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Smewt - A smart collection manager
# Copyright (c) 2008-2013 Nicolas Wack <wackou@smewt.com>
#
# Smewt 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.
#
# Smewt 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/>.
#
from smewt.base.utils import tolist, toresult
from smewt.base.textutils import u
from smewt.base.subtitletask import SubtitleTask
from smewt.plugins import mplayer
from guessit.language import Language
import smewt
import os, sys, time
import subprocess
import logging
log = logging.getLogger(__name__)
def get_episodes_and_subs(language, series, season=None):
if season:
episodes = set(ep for ep in tolist(series.episodes) if ep.season == int(season))
else:
episodes = set(tolist(series.episodes))
subs = []
for ep in episodes:
subs.extend(tolist(ep.get('subtitles')))
return episodes, subs
def get_subtitles(media_type, title, season=None, language=None):
db = smewt.SMEWTD_INSTANCE.database
language = language or db.config.get('subtitleLanguage') or 'en'
if media_type == 'episode':
series = db.find_one('Series', title=title)
episodes, subs = get_episodes_and_subs(language, series, season)
already_good = set(s.metadata for s in subs)
episodes = episodes - already_good
if episodes:
subtask = SubtitleTask(episodes, language)
smewt.SMEWTD_INSTANCE.taskManager.add(subtask)
return 'OK'
else:
msg = 'All episodes already have %s subtitles!' % Language(language).english_name
log.info(msg)
return msg
elif media_type == 'movie':
movie = db.find_one('Movie', title=title)
# check if we already have it
for sub in tolist(movie.get('subtitles')):
if sub.language == language:
msg = 'Movie already has a %s subtitle' % Language(language).english_name
log.info(msg)
return msg
subtask = SubtitleTask(movie, language)
smewt.SMEWTD_INSTANCE.taskManager.add(subtask)
return 'OK'
else:
msg = 'Don\'t know how to fetch subtitles for type: %s' % media_type
log.error(msg)
return msg
def _play(files, subs):
# launch external player
args = files
# make sure subs is as long as args so as to not cut it when zipping them together
subs = subs + [None] * (len(files) - len(subs))
if mplayer.variant != 'undefined':
# if we have mplayer (or one of its variant) installed, use it with
# subtitles support
opts = []
return mplayer.play(files, subs, opts)
elif sys.platform == 'linux2':
action = 'xdg-open'
# FIXME: xdg-open only accepts 1 argument, this will break movies split in multiple files...
args = args[:1]
# if we have smplayer installed, use it with subtitles support
if os.system('which smplayer') == 0:
action = 'smplayer'
args = [ '-fullscreen', '-close-at-end' ]
for video, subfile in zip(files, subs):
args.append(video)
if subfile:
args += [ '-sub', subfile ]
elif sys.platform == 'darwin':
action = 'open'
elif sys.platform == 'win32':
action = 'open'
log.info('launching %s with args = %s' % (action, str(args)))
subprocess.call([action]+args)
def play_video(metadata, sublang=None):
# FIXME: this should be handled properly with media player plugins
# files should be a list of (Metadata, sub), where sub is possibly None
# then we would look into the available graphs where such a Metadata has files,
# and choose the one on the fastest media (ie: local before nfs before tcp)
# it should also choose subtitles the same way, so we could even imagine reading
# the video from one location and the subs from another
# find list of all files to be played
# returns a list of (video_filename, sub_filename)
if sublang:
msg = 'Playing %s with %s subtitles' % (metadata, Language(sublang).english_name)
else:
msg = 'Playing %s with no subtitles' % metadata
log.info(u(msg))
# FIXME: we assume that sorting alphanumerically is good enough, but that is
# not necessarily the case...
# we should also look whether the file also has the 'cdNumber' attribute
files = tolist(metadata.get('files'))
files = sorted(files, key=lambda f: f.get('filename'))
if sublang is not None:
sublang = Language(sublang)
for sub in tolist(metadata.get('subtitles')):
if sub.language == sublang:
subs = sorted(tolist(sub.get('files')), key=lambda f: f.get('filename'))
break
else:
subs = [None]*len(files)
# update last viewed info
metadata.lastViewed = time.time()
metadata.watched = True
_play([ f.filename for f in files],
[ s.filename for s in subs if s ])
def play_file(filename):
_play([filename], [None])
|
wackou/smewt
|
smewt/actions.py
|
Python
|
gpl-3.0
| 5,613 | 0.004276 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-09-12 19:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("ui", "0010_video_default_sort"),
]
operations = [
migrations.AddField(
model_name="collection",
name="created_at",
field=models.DateTimeField(auto_now_add=True, null=True),
),
migrations.AlterModelOptions(
name="collection",
options={"ordering": ["-created_at"]},
),
]
|
mitodl/odl-video-service
|
ui/migrations/0011_collection_created_at.py
|
Python
|
bsd-3-clause
| 602 | 0 |
# x = [4, 6, 1, 3, 5, 7, 25]
# def stars (a):
# i = 0
# while (i < len(a)):
# print '*' * a[i]
# i += 1
# stars(x)
x = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"]
def stars (a):
i = 0
while (i < len(a)):
if type(a[i]) is int:
print '*' * a[i]
i+=1
else:
temp = a[i]
temp = temp.lower()
print (len(a[i])) * temp[0]
i += 1
stars(x)
|
jiobert/python
|
Paracha_Junaid/Assignments/Python/Web_fund/stars.py
|
Python
|
mit
| 368 | 0.048913 |
import os.path as op
import numpy as np
from numpy.testing import assert_array_equal
import pytest
from mne.parallel import parallel_func
from mne.utils import ProgressBar, array_split_idx, use_log_level
def test_progressbar():
"""Test progressbar class."""
a = np.arange(10)
pbar = ProgressBar(a)
assert a is pbar.iterable
assert pbar.max_value == 10
pbar = ProgressBar(10)
assert pbar.max_value == 10
assert pbar.iterable is None
# Make sure that non-iterable input raises an error
def iter_func(a):
for ii in a:
pass
pytest.raises(Exception, iter_func, ProgressBar(20))
def _identity(x):
return x
def test_progressbar_parallel_basic(capsys):
"""Test ProgressBar with parallel computing, basic version."""
assert capsys.readouterr().out == ''
parallel, p_fun, _ = parallel_func(_identity, total=10, n_jobs=1,
verbose=True)
with use_log_level(True):
out = parallel(p_fun(x) for x in range(10))
assert out == list(range(10))
cap = capsys.readouterr()
out = cap.err
assert '100%' in out
def _identity_block(x, pb):
for ii in range(len(x)):
pb.update(ii + 1)
return x
def test_progressbar_parallel_advanced(capsys):
"""Test ProgressBar with parallel computing, advanced version."""
assert capsys.readouterr().out == ''
# This must be "1" because "capsys" won't get stdout properly otherwise
parallel, p_fun, _ = parallel_func(_identity_block, n_jobs=1,
verbose=False)
arr = np.arange(10)
with use_log_level(True):
with ProgressBar(len(arr)) as pb:
out = parallel(p_fun(x, pb.subset(pb_idx))
for pb_idx, x in array_split_idx(arr, 2))
assert op.isfile(pb._mmap_fname)
sum_ = np.memmap(pb._mmap_fname, dtype='bool', mode='r',
shape=10).sum()
assert sum_ == len(arr)
assert not op.isfile(pb._mmap_fname), '__exit__ not called?'
out = np.concatenate(out)
assert_array_equal(out, arr)
cap = capsys.readouterr()
out = cap.err
assert '100%' in out
def _identity_block_wide(x, pb):
for ii in range(len(x)):
for jj in range(2):
pb.update(ii * 2 + jj + 1)
return x, pb.idx
def test_progressbar_parallel_more(capsys):
"""Test ProgressBar with parallel computing, advanced version."""
assert capsys.readouterr().out == ''
# This must be "1" because "capsys" won't get stdout properly otherwise
parallel, p_fun, _ = parallel_func(_identity_block_wide, n_jobs=1,
verbose=False)
arr = np.arange(10)
with use_log_level(True):
with ProgressBar(len(arr) * 2) as pb:
out = parallel(p_fun(x, pb.subset(pb_idx))
for pb_idx, x in array_split_idx(
arr, 2, n_per_split=2))
idxs = np.concatenate([o[1] for o in out])
assert_array_equal(idxs, np.arange(len(arr) * 2))
out = np.concatenate([o[0] for o in out])
assert op.isfile(pb._mmap_fname)
sum_ = np.memmap(pb._mmap_fname, dtype='bool', mode='r',
shape=len(arr) * 2).sum()
assert sum_ == len(arr) * 2
assert not op.isfile(pb._mmap_fname), '__exit__ not called?'
cap = capsys.readouterr()
out = cap.err
assert '100%' in out
|
Teekuningas/mne-python
|
mne/utils/tests/test_progressbar.py
|
Python
|
bsd-3-clause
| 3,513 | 0 |
#coding:UTF-8
"""
磁盘监控模块
"""
from config import disk
from lib import core
import os,re
def init():
"对外接口"
sign=True
for t in disk.DISK_PATH:
warn,data=check(t)
if not warn:
login_time=time.time()
message="磁盘监控预警提示,磁盘使用率超过%s"%(disk.DISK_USED)+"%\n监控结果:"+data
message=message.decode("UTF-8")
print message
core.sendEmail(message)
print u"邮件已经发出"
sign=False
return sign
def getIntervalTime():
"获取检测间隔时间"
return disk.DISK_DELAY
def check(path):
"检测是否超出预警"
r=os.popen("df -h "+path)
for line in r:
data=line.rstrip()
datas=re.split(r'\s+',data)
used=datas[4].encode("UTF-8").replace("%","")
return int(used) < disk.DISK_USED,data
|
yubang/smallMonitor
|
lib/disk.py
|
Python
|
apache-2.0
| 903 | 0.025094 |
"""Utility for changing directories and execution of commands in a subshell."""
from __future__ import print_function
import os
import shlex
import subprocess
# Store the previous working directory for the 'cd -' command.
class Holder:
"""Holds the _prev_dir_ class attribute for chdir() function."""
_prev_dir_ = None
@classmethod
def prev_dir(cls):
return cls._prev_dir_
@classmethod
def swap(cls, dir):
cls._prev_dir_ = dir
def chdir(debugger, args, result, dict):
"""Change the working directory, or cd to ${HOME}.
You can also issue 'cd -' to change to the previous working directory."""
new_dir = args.strip()
if not new_dir:
new_dir = os.path.expanduser('~')
elif new_dir == '-':
if not Holder.prev_dir():
# Bad directory, not changing.
print("bad directory, not changing")
return
else:
new_dir = Holder.prev_dir()
Holder.swap(os.getcwd())
os.chdir(new_dir)
print("Current working directory: %s" % os.getcwd())
def system(debugger, command_line, result, dict):
"""Execute the command (a string) in a subshell."""
args = shlex.split(command_line)
process = subprocess.Popen(
args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, error = process.communicate()
retcode = process.poll()
if output and error:
print("stdout=>\n", output)
print("stderr=>\n", error)
elif output:
print(output)
elif error:
print(error)
print("retcode:", retcode)
|
endlessm/chromium-browser
|
third_party/llvm/lldb/examples/customization/pwd-cd-and-system/utils.py
|
Python
|
bsd-3-clause
| 1,600 | 0 |
#!/usr/bin/python
#credits : https://gist.github.com/TheCrazyT/11263599
import socket
import ssl
import select
import time
import re
import sys
from thread import start_new_thread
from struct import pack
from random import randint
from subprocess import call
import os
import fnmatch
import argparse
import logging
class lakkucast:
def __init__(self):
self.status = None
self.session_id = None
self.protocolVersion = 0
self.source_id = "sender-0"
self.destination_id = "receiver-0"
self.chromecast_server = "192.168.1.23" #living room audio
self.socket = 0
self.type_enum = 0
self.type_string = 2
self.type_bytes = self.type_string
self.session = 0
self.play_state = None
self.sleep_between_media = 5
self.content_id = None
self.socket_fail_count = 100
def clean(self,s):
return re.sub(r'[\x00-\x1F\x7F]', '?',s)
def getType(self, fieldId,t):
return (fieldId << 3) | t
def getLenOf(self, s):
x = ""
l = len(s)
while(l > 0x7F):
x += pack("B",l & 0x7F | 0x80)
l >>= 7
x += pack("B",l & 0x7F)
return x
def init_status(self):
self.socket = socket.socket()
self.socket = ssl.wrap_socket(self.socket)
#print "connecting ..."
self.socket.connect((self.chromecast_server,8009))
payloadType = 0 #0=string
data = "{\"type\":\"CONNECT\",\"origin\":{}}"
lnData = self.getLenOf(data)
#print len(lnData),len(data),lnData.encode("hex")
namespace = "urn:x-cast:com.google.cast.tp.connection"
msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" %
(len(self.source_id),
len(self.destination_id),
len(namespace),
len(lnData),
len(data)),
self.getType(1,self.type_enum),
self.protocolVersion,
self.getType(2,self.type_string),
len(self.source_id),
self.source_id,
self.getType(3,self.type_string),
len(self.destination_id),
self.destination_id,
self.getType(4,self.type_string),
len(namespace),
namespace,
self.getType(5,self.type_enum),
payloadType,
self.getType(6,self.type_bytes),
lnData,
data)
msg = pack(">I%ds" % (len(msg)),len(msg),msg)
#print msg.encode("hex")
#print "Connecting ..."
self.socket.write(msg)
payloadType = 0 #0=string
data = "{\"type\":\"GET_STATUS\",\"requestId\":46479000}"
lnData = self.getLenOf(data)
namespace = "urn:x-cast:com.google.cast.receiver"
msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" % (len(self.source_id),
len(self.destination_id),
len(namespace),
len(lnData),
len(data)),
self.getType(1,self.type_enum),
self.protocolVersion,
self.getType(2,self.type_string),
len(self.source_id),
self.source_id,
self.getType(3,self.type_string),
len(self.destination_id),
self.destination_id,
self.getType(4,self.type_string),
len(namespace),
namespace,
self.getType(5,self.type_enum),
payloadType,
self.getType(6,self.type_bytes),
lnData,
data)
msg = pack(">I%ds" % (len(msg)),len(msg),msg)
#print "sending status request..."
self.socket.write(msg)
m1=None
m3=None
result=""
count = 0
while m1==None and m3==None:
lastresult = self.socket.read(2048)
result += lastresult
#print "#"+lastresult.encode("hex")
#if lastresult != "":
# print self.clean("\nH!"+lastresult)
#print result
m1 = re.search('"sessionId":"(?P<session>[^"]+)"', result)
m2 = re.search('"statusText":"(?P<status>[^"]+)"', result)
m3 = re.search('"playerState":"(?P<play_state>[^"]+)"', result)
m4 = re.search('"contentId":"(?P<content_id>[^"]+)"', result)
count = count + 1
if count > self.socket_fail_count:
self.status = None
self.play_state = None
self.status = None
break
#print "#%i" % (m==None)
if m1 != None:
#print "session:",m1.group("session")
self.session = m1.group("session")
if m2 != None:
#print "status:",m2.group("status")
self.status = m2.group("status")
if m3 != None:
#print "play_state:",m3.group("play_state")
self.play_state = m3.group("play_state")
if m4 != None:
#print "contentid:",m4.group("content_id")
self.content_id = m4.group("content_id")
payloadType = 0 #0=string
data = "{MESSAGE_TYPE: 'SET_VOLUME','volume': {'level': 0.2}}"
lnData = self.getLenOf(data)
#print len(lnData),len(data),lnData.encode("hex")
namespace = "urn:x-cast:com.google.cast.tp.connection"
msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" %
(len(self.source_id),
len(self.destination_id),
len(namespace),
len(lnData),
len(data)),
self.getType(1,self.type_enum),
self.protocolVersion,
self.getType(2,self.type_string),
len(self.source_id),
self.source_id,
self.getType(3,self.type_string),
len(self.destination_id),
self.destination_id,
self.getType(4,self.type_string),
len(namespace),
namespace,
self.getType(5,self.type_enum),
payloadType,
self.getType(6,self.type_bytes),
lnData,
data)
msg = pack(">I%ds" % (len(msg)),len(msg),msg)
#print msg.encode("hex")
#print "Connecting ..."
self.socket.write(msg)
def get_status(self):
return " ".join(["main_status:" , self.get_main_status() , "play_status:" , self.get_play_status()])
def get_main_status(self):
if self.status == None:
status_str = "None"
else:
status_str = self.status
return (status_str)
def get_play_status(self):
if self.play_state == None:
play_state_str = "None"
else:
play_state_str = self.play_state
return (play_state_str)
def ready_to_play(self):
if self.status == "Now Casting":
return False
if self.status == "Ready To Cast" or self.status == None or self.status == "Chromecast Home Screen":
if self.play_state == None:
return True
if self.play_state == "IDLE":
return True
if self.play_state == "PLAYING":
return False
if self.play_state == "BUFFERING":
return False
return True
else:
return False
def close_connection(self):
self.socket.close()
def play_url(self, url):
payloadType = 0 #0=string
data = "{\"type\":\"LAUNCH\",\"requestId\":46479001,\"appId\":\"CC1AD845\"}"
lnData = self.getLenOf(data)
namespace = "urn:x-cast:com.google.cast.receiver"
msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" %
(len(self.source_id),
len(self.destination_id),
len(namespace),
len(lnData),
len(data)),
self.getType(1,self.type_enum),
self.protocolVersion,
self.getType(2,self.type_string),
len(self.source_id),
self.source_id,
self.getType(3,self.type_string),
len(self.destination_id),
self.destination_id,
self.getType(4,self.type_string),
len(namespace),
namespace,
self.getType(5,self.type_enum),
payloadType,
self.getType(6,self.type_bytes),
lnData,
data)
msg = pack(">I%ds" % (len(msg)),len(msg),msg)
#print msg.encode("hex")
#print "sending ..."
self.socket.write(msg)
m=None
result=""
while m==None:
lastresult = self.socket.read(2048)
result += lastresult
#print "#"+lastresult.encode("hex")
#print clean("!"+lastresult)
m = re.search('"transportId":"(?P<transportId>[^"]+)"', result)
self.destination_id = m.group("transportId")
payloadType = 0 #0=string
data = "{\"type\":\"CONNECT\",\"origin\":{}}"
lnData = self.getLenOf(data)
#print len(lnData),len(data),lnData.encode("hex")
namespace = "urn:x-cast:com.google.cast.tp.connection"
msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" %
(len(self.source_id),
len(self.destination_id),
len(namespace),
len(lnData),
len(data)),
self.getType(1,self.type_enum),
self.protocolVersion,
self.getType(2,self.type_string),
len(self.source_id),
self.source_id,
self.getType(3,self.type_string),
len(self.destination_id),
self.destination_id,
self.getType(4,self.type_string),
len(namespace),
namespace,
self.getType(5,self.type_enum),
payloadType,
self.getType(6,self.type_bytes),
lnData,
data)
msg = pack(">I%ds" % (len(msg)),len(msg),msg)
#print msg.encode("hex")
#print "sending ..."
self.socket.write(msg)
payloadType = 0 #0=string
data = "{\"type\":\"LOAD\",\"requestId\":46479002,\"sessionId\":\""+self.session+"\",\"media\":{\"contentId\":\""+url+"\",\"streamType\":\"buffered\",\"contentType\":\"video/mp4\"},\"autoplay\":true,\"currentTime\":0,\"customData\":{\"payload\":{\"title:\":\"\"}}}"
lnData = self.getLenOf(data)
namespace = "urn:x-cast:com.google.cast.media"
msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" %
(len(self.source_id),
len(self.destination_id),
len(namespace),
len(lnData),
len(data)),
self.getType(1,self.type_enum),
self.protocolVersion,
self.getType(2,self.type_string),
len(self.source_id),
self.source_id,
self.getType(3,self.type_string),
len(self.destination_id),
self.destination_id,
self.getType(4,self.type_string),
len(namespace),
namespace,
self.getType(5,self.type_enum),
payloadType,
self.getType(6,self.type_bytes),
lnData,
data)
msg = pack(">I%ds" % (len(msg)),len(msg),msg)
#print msg.encode("hex")
#print "sending ..."
#print "LOADING"
self.socket.write(msg)
payloadType = 0 #0=string
volume = min(max(0, round(0.1, 1)), 1)
data = "{MESSAGE_TYPE: 'SET_VOLUME','volume': {'level': volume}}"
lnData = self.getLenOf(data)
#print len(lnData),len(data),lnData.encode("hex")
namespace = "urn:x-cast:com.google.cast.tp.connection"
msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" %
(len(self.source_id),
len(self.destination_id),
len(namespace),
len(lnData),
len(data)),
self.getType(1,self.type_enum),
self.protocolVersion,
self.getType(2,self.type_string),
len(self.source_id),
self.source_id,
self.getType(3,self.type_string),
len(self.destination_id),
self.destination_id,
self.getType(4,self.type_string),
len(namespace),
namespace,
self.getType(5,self.type_enum),
payloadType,
self.getType(6,self.type_bytes),
lnData,
data)
msg = pack(">I%ds" % (len(msg)),len(msg),msg)
#print msg.encode("hex")
#print "Connecting ..."
self.socket.write(msg)
self.close_connection()
#try:
# while True:
# print "before lastresult"
# lastresult = self.socket.read(2048)
# if lastresult!="":
# #print "#"+lastresult.encode("hex")
# print self.clean("! In loop:"+lastresult)
# finally:
# print "final"
# socket.close()
# print "socket closed"
class manage_lightwave:
def __init__(self):
self.room = "Main\ Bedroom"
self.device = "Screen"
self.lightwave_cmd = "/usr/local/bin/lightwaverf"
def start_screen(self):
cmd = " ".join([self.lightwave_cmd, self.room, self.device, "on", ">cmd.log", "2>&1"])
os.system(cmd)
return(cmd)
def stop_screen(self):
cmd = " ".join([self.lightwave_cmd, self.room, self.device, "off", ">cmd.log", "2>&1"])
os.system(cmd)
return(cmd)
class lakkucast_media:
def __init__(self):
self.top_dir = "/data"
self.top_url = "http://192.168.1.98"
#self.media_dirs = ["media/test/sample1", "media/test/sample2"]
self.media_dirs = ["media/TV-Shows/English/Friends", "media/TV-Shows/English/That 70s Show", "media/TV-Shows/English/Big Bang Theory"]
self.media_data = "/data/webapps/lakku/lakkucast/media.dat"
def random_play(self, num_play):
count_dir = 0
num_dirs = len(self.media_dirs)
while count_dir < num_dirs:
rand_main = randint(0, (len(self.media_dirs)-1))
url_list = []
sel_dir = os.path.join(self.top_dir, self.media_dirs[rand_main])
if os.path.isdir(sel_dir):
count_dir = count_dir + 1
matches = []
for root, dirnames, filenames in os.walk(sel_dir):
for filename in fnmatch.filter(filenames, '*.mp4'):
matches.append(os.path.join(root, filename).replace(self.top_dir,''))
count = 1
loop_count = 1
while count <= num_play:
file_rand = randint(0, (len(matches)-1))
file_name = "".join([self.top_url , matches[file_rand]])
if self.played_before(file_name) == False:
if file_name not in url_list:
url_list.append(file_name)
count = count + 1
loop_count = loop_count + 1
if loop_count == (len(matches)-1):
break
if count < num_play:
continue
else:
fhand = open(self.media_data, 'a+')
for u in url_list:
fhand.write(u+'\n')
fhand.close()
return url_list
def played_before(self, media_name):
if media_name in open(self.media_data).read():
return True
return False
def reset_media_history(self):
fhand = open(self.media_data, 'w')
fhand.truncate()
fhand.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="lakkucast")
parser.add_argument("--play", help="Play x videos ")
parser.add_argument("--stop", help="Stop playing and shutdown", action='store_true')
parser.add_argument("--reset", help="Stop playing", action='store_true')
parser.add_argument("--reset_media_history", help="Reset media history", action='store_true')
args = parser.parse_args()
log_file = "/data/webapps/lakku/lakkucast/lakkucast.log"
log_level = logging.INFO
logging.basicConfig(filename=log_file, level=log_level,
format='%(asctime)s [%(levelname)s] %(message)s')
logging.info("Starting lakkucast.")
if args.play:
num_play = int(args.play) * 2
logging.info("Play count: %s"
% (args.play))
lm = lakkucast_media()
lwrf = manage_lightwave()
logging.info("Sending start command to lwrf")
logging.info(lwrf.start_screen())
lwrf.start_screen()
logging.info("Sleeping after lwrf start")
url_list = lm.random_play(num_play)
time.sleep(20)
if url_list != None:
logging.info("Got %d urls to play"
% (len(url_list)))
for u in url_list:
logging.info("Trying URL: %s"
% (u))
l = lakkucast()
logging.info("Sleeping before main init")
time.sleep(l.sleep_between_media)
l.init_status()
logging.info(l.get_status())
if l.ready_to_play():
logging.info("Playing URL: %s"
% (u))
l.play_url(u)
l.init_status()
logging.info(l.get_status())
while not l.ready_to_play():
time.sleep(l.sleep_between_media)
l.init_status()
logging.info(l.get_status())
time.sleep(l.sleep_between_media)
logging.info("Sending stop command to lwrf")
logging.info(lwrf.stop_screen())
else:
logging.info("No urls returned by player")
l.play_url("http://192.168.1.98/media/test/water.mp4")
time.sleep(l.sleep_between_media)
lwrf = manage_lightwave()
logging.info("Sending stop command to lwrf")
logging.info(lwrf.stop_screen())
if args.stop:
l = lakkucast()
l.init_status()
logging.info("Calling stop")
logging.info(l.get_status())
l.play_url("http://192.168.1.98/media/test/water.mp4")
time.sleep(10)
lwrf = manage_lightwave()
logging.info("Sending stop command to lwrf")
logging.info(lwrf.stop_screen())
if args.reset:
l = lakkucast()
l.init_status()
logging.info("Calling reset")
logging.info(l.get_status())
l.play_url("http://192.168.1.98/media/test/water.mp4")
if args.reset_media_history:
logging.info("Calling Reset media history")
lm = lakkucast_media()
lm.reset_media_history()
|
srirajan/lakkucast
|
lakkucast.py
|
Python
|
apache-2.0
| 21,535 | 0.014442 |
import os
path = os.path.dirname(os.path.realpath(__file__))
sbmlFilePath = os.path.join(path, 'BIOMD0000000155.xml')
with open(sbmlFilePath,'r') as f:
sbmlString = f.read()
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
return True
if module_exists('libsbml'):
import libsbml
sbml = libsbml.readSBMLFromString(sbmlString)
|
biomodels/BIOMD0000000155
|
BIOMD0000000155/model.py
|
Python
|
cc0-1.0
| 427 | 0.009368 |
'''
Created on Oct 29, 2015
@author: yangke
'''
from model.TaintVar import TaintVar
from TraceTrackTest import TraceTrackTest
class Test_objdump_addr:
def test(self):
passed_message="BINUTILS-2.23 'addr[1]' TEST PASSED!"
not_pass_message="ERRORS FOUND IN BINUTILS-2.23 'addr[1]' TEST!"
answer_path='answers/binutils/binutils-2.23/objdump/'
name='binutils-2.23_objdump_addr'
logfile_path="gdb_logs/binutils-2.23/binutils-2.23_objdump_gdb.txt"
c_proj_path="gdb_logs/binutils-2.23/binutils-2.23"
taintVars=[TaintVar("addr",['*'])]
test=TraceTrackTest(answer_path,name,logfile_path,taintVars,passed_message,not_pass_message)
test.set_c_proj_path(c_proj_path)
passed=test.test()
return passed
if __name__ == '__main__':
test=Test_objdump_addr()
test.test()
|
yangke/cluehunter
|
test/Test_objdump_addr.py
|
Python
|
gpl-3.0
| 852 | 0.023474 |
"""
Floater Class: Velocity style controller for floating point values with
a label, entry (validated), and scale
"""
__all__ = ['Floater', 'FloaterWidget', 'FloaterGroup']
from direct.showbase.TkGlobal import *
from Tkinter import *
from Valuator import Valuator, VALUATOR_MINI, VALUATOR_FULL
from direct.task import Task
import math, sys, string, Pmw
FLOATER_WIDTH = 22
FLOATER_HEIGHT = 18
class Floater(Valuator):
def __init__(self, parent = None, **kw):
INITOPT = Pmw.INITOPT
optiondefs = (
('style', VALUATOR_MINI, INITOPT),
)
self.defineoptions(kw, optiondefs)
# Initialize the superclass
Valuator.__init__(self, parent)
self.initialiseoptions(Floater)
def createValuator(self):
self._valuator = self.createcomponent('valuator',
(('floater', 'valuator'),),
None,
FloaterWidget,
(self.interior(),),
command = self.setEntry,
value = self['value'])
self._valuator._widget.bind('<Double-ButtonPress-1>', self.mouseReset)
def packValuator(self):
# Position components
if self._label:
self._label.grid(row=0, column=0, sticky = EW)
self._entry.grid(row=0, column=1, sticky = EW)
self._valuator.grid(row=0, column=2, padx = 2, pady = 2)
self.interior().columnconfigure(0, weight = 1)
class FloaterWidget(Pmw.MegaWidget):
def __init__(self, parent = None, **kw):
#define the megawidget options
INITOPT = Pmw.INITOPT
optiondefs = (
# Appearance
('width', FLOATER_WIDTH, INITOPT),
('height', FLOATER_HEIGHT, INITOPT),
('relief', RAISED, self.setRelief),
('borderwidth', 2, self.setBorderwidth),
('background', 'grey75', self.setBackground),
# Behavior
# Initial value of floater, use self.set to change value
('value', 0.0, INITOPT),
('numDigits', 2, self.setNumDigits),
# Command to execute on floater updates
('command', None, None),
# Extra data to be passed to command function
('commandData', [], None),
# Callback's to execute during mouse interaction
('preCallback', None, None),
('postCallback', None, None),
# Extra data to be passed to callback function, needs to be a list
('callbackData', [], None),
)
self.defineoptions(kw, optiondefs)
# Initialize the superclass
Pmw.MegaWidget.__init__(self, parent)
# Set up some local and instance variables
# Create the components
interior = self.interior()
# Current value
self.value = self['value']
# The canvas
width = self['width']
height = self['height']
self._widget = self.createcomponent('canvas', (), None,
Canvas, (interior,),
width = width,
height = height,
background = self['background'],
highlightthickness = 0,
scrollregion = (-width/2.0,
-height/2.0,
width/2.0,
height/2.0))
self._widget.pack(expand = 1, fill = BOTH)
# The floater icon
self._widget.create_polygon(-width/2.0, 0, -2.0, -height/2.0,
-2.0, height/2.0,
fill = 'grey50',
tags = ('floater',))
self._widget.create_polygon(width/2.0, 0, 2.0, height/2.0,
2.0, -height/2.0,
fill = 'grey50',
tags = ('floater',))
# Add event bindings
self._widget.bind('<ButtonPress-1>', self.mouseDown)
self._widget.bind('<B1-Motion>', self.updateFloaterSF)
self._widget.bind('<ButtonRelease-1>', self.mouseUp)
self._widget.bind('<Enter>', self.highlightWidget)
self._widget.bind('<Leave>', self.restoreWidget)
# Make sure input variables processed
self.initialiseoptions(FloaterWidget)
def set(self, value, fCommand = 1):
"""
self.set(value, fCommand = 1)
Set floater to new value, execute command if fCommand == 1
"""
# Send command if any
if fCommand and (self['command'] != None):
apply(self['command'], [value] + self['commandData'])
# Record value
self.value = value
def updateIndicator(self, value):
# Nothing visible to update on this type of widget
pass
def get(self):
"""
self.get()
Get current floater value
"""
return self.value
## Canvas callback functions
# Floater velocity controller
def mouseDown(self, event):
""" Begin mouse interaction """
# Exectute user redefinable callback function (if any)
self['relief'] = SUNKEN
if self['preCallback']:
apply(self['preCallback'], self['callbackData'])
self.velocitySF = 0.0
self.updateTask = taskMgr.add(self.updateFloaterTask,
'updateFloater')
self.updateTask.lastTime = globalClock.getFrameTime()
def updateFloaterTask(self, state):
"""
Update floaterWidget value based on current scaleFactor
Adjust for time to compensate for fluctuating frame rates
"""
currT = globalClock.getFrameTime()
dt = currT - state.lastTime
self.set(self.value + self.velocitySF * dt)
state.lastTime = currT
return Task.cont
def updateFloaterSF(self, event):
"""
Update velocity scale factor based of mouse distance from origin
"""
x = self._widget.canvasx(event.x)
y = self._widget.canvasy(event.y)
offset = max(0, abs(x) - Valuator.deadband)
if offset == 0:
return 0
sf = math.pow(Valuator.sfBase,
self.minExp + offset/Valuator.sfDist)
if x > 0:
self.velocitySF = sf
else:
self.velocitySF = -sf
def mouseUp(self, event):
taskMgr.remove(self.updateTask)
self.velocitySF = 0.0
# Execute user redefinable callback function (if any)
if self['postCallback']:
apply(self['postCallback'], self['callbackData'])
self['relief'] = RAISED
def setNumDigits(self):
"""
Adjust minimum exponent to use in velocity task based
upon the number of digits to be displayed in the result
"""
self.minExp = math.floor(-self['numDigits']/
math.log10(Valuator.sfBase))
# Methods to modify floater characteristics
def setRelief(self):
self.interior()['relief'] = self['relief']
def setBorderwidth(self):
self.interior()['borderwidth'] = self['borderwidth']
def setBackground(self):
self._widget['background'] = self['background']
def highlightWidget(self, event):
self._widget.itemconfigure('floater', fill = 'black')
def restoreWidget(self, event):
self._widget.itemconfigure('floater', fill = 'grey50')
class FloaterGroup(Pmw.MegaToplevel):
def __init__(self, parent = None, **kw):
# Default group size
DEFAULT_DIM = 1
# Default value depends on *actual* group size, test for user input
DEFAULT_VALUE = [0.0] * kw.get('dim', DEFAULT_DIM)
DEFAULT_LABELS = ['v[%d]' % x for x in range(kw.get('dim', DEFAULT_DIM))]
#define the megawidget options
INITOPT = Pmw.INITOPT
optiondefs = (
('dim', DEFAULT_DIM, INITOPT),
('side', TOP, INITOPT),
('title', 'Floater Group', None),
# A tuple of initial values, one for each floater
('value', DEFAULT_VALUE, INITOPT),
# The command to be executed any time one of the floaters is updated
('command', None, None),
# A tuple of labels, one for each floater
('labels', DEFAULT_LABELS, self._updateLabels),
)
self.defineoptions(kw, optiondefs)
# Initialize the toplevel widget
Pmw.MegaToplevel.__init__(self, parent)
# Create the components
interior = self.interior()
# Get a copy of the initial value (making sure its a list)
self._value = list(self['value'])
# The Menu Bar
self.balloon = Pmw.Balloon()
menubar = self.createcomponent('menubar', (), None,
Pmw.MenuBar, (interior,),
balloon = self.balloon)
menubar.pack(fill=X)
# FloaterGroup Menu
menubar.addmenu('Floater Group', 'Floater Group Operations')
menubar.addmenuitem(
'Floater Group', 'command', 'Reset the Floater Group panel',
label = 'Reset',
command = lambda s = self: s.reset())
menubar.addmenuitem(
'Floater Group', 'command', 'Dismiss Floater Group panel',
label = 'Dismiss', command = self.withdraw)
menubar.addmenu('Help', 'Floater Group Help Operations')
self.toggleBalloonVar = IntVar()
self.toggleBalloonVar.set(0)
menubar.addmenuitem('Help', 'checkbutton',
'Toggle balloon help',
label = 'Balloon Help',
variable = self.toggleBalloonVar,
command = self.toggleBalloon)
self.floaterList = []
for index in range(self['dim']):
# Add a group alias so you can configure the floaters via:
# fg.configure(Valuator_XXX = YYY)
f = self.createcomponent(
'floater%d' % index, (), 'Valuator', Floater,
(interior,), value = self._value[index],
text = self['labels'][index])
# Do this separately so command doesn't get executed during construction
f['command'] = lambda val, s=self, i=index: s._floaterSetAt(i, val)
f.pack(side = self['side'], expand = 1, fill = X)
self.floaterList.append(f)
# Make sure floaters are initialized
self.set(self['value'])
# Make sure input variables processed
self.initialiseoptions(FloaterGroup)
def _updateLabels(self):
if self['labels']:
for index in range(self['dim']):
self.floaterList[index]['text'] = self['labels'][index]
def toggleBalloon(self):
if self.toggleBalloonVar.get():
self.balloon.configure(state = 'balloon')
else:
self.balloon.configure(state = 'none')
def get(self):
return self._value
def getAt(self, index):
return self._value[index]
# This is the command is used to set the groups value
def set(self, value, fCommand = 1):
for i in range(self['dim']):
self._value[i] = value[i]
# Update floater, but don't execute its command
self.floaterList[i].set(value[i], 0)
if fCommand and (self['command'] is not None):
self['command'](self._value)
def setAt(self, index, value):
# Update floater and execute its command
self.floaterList[index].set(value)
# This is the command used by the floater
def _floaterSetAt(self, index, value):
self._value[index] = value
if self['command']:
self['command'](self._value)
def reset(self):
self.set(self['value'])
## SAMPLE CODE
if __name__ == '__main__':
# Initialise Tkinter and Pmw.
root = Toplevel()
root.title('Pmw Floater demonstration')
# Dummy command
def printVal(val):
print val
# Create and pack a Floater megawidget.
mega1 = Floater(root, command = printVal)
mega1.pack(side = 'left', expand = 1, fill = 'x')
"""
# These are things you can set/configure
# Starting value for floater
mega1['value'] = 123.456
mega1['text'] = 'Drive delta X'
# To change the color of the label:
mega1.label['foreground'] = 'Red'
# Max change/update, default is 100
# To have really fine control, for example
# mega1['maxVelocity'] = 0.1
# Number of digits to the right of the decimal point, default = 2
# mega1['numDigits'] = 5
"""
# To create a floater group to set an RGBA value:
group1 = FloaterGroup(root, dim = 4,
title = 'Simple RGBA Panel',
labels = ('R', 'G', 'B', 'A'),
Valuator_min = 0.0,
Valuator_max = 255.0,
Valuator_resolution = 1.0,
command = printVal)
# Uncomment this if you aren't running in IDLE
#root.mainloop()
|
toontownfunserver/Panda3D-1.9.0
|
direct/tkwidgets/Floater.py
|
Python
|
bsd-3-clause
| 13,935 | 0.008396 |
import graphene
from graphene_django import DjangoObjectType
from graphene_django.debug import DjangoDebug
from pontoon.api.util import get_fields
from pontoon.base.models import (
Project as ProjectModel,
Locale as LocaleModel,
ProjectLocale as ProjectLocaleModel
)
class Stats(graphene.AbstractType):
missing_strings = graphene.Int()
complete = graphene.Boolean()
class ProjectLocale(DjangoObjectType, Stats):
class Meta:
model = ProjectLocaleModel
only_fields = (
'total_strings', 'approved_strings', 'translated_strings',
'fuzzy_strings', 'project', 'locale'
)
class Project(DjangoObjectType, Stats):
class Meta:
model = ProjectModel
only_fields = (
'name', 'slug', 'disabled', 'info', 'deadline', 'priority',
'contact', 'total_strings', 'approved_strings',
'translated_strings', 'fuzzy_strings'
)
localizations = graphene.List(ProjectLocale)
@graphene.resolve_only_args
def resolve_localizations(obj):
return obj.project_locale.all()
class Locale(DjangoObjectType, Stats):
class Meta:
model = LocaleModel
only_fields = (
'name', 'code', 'direction', 'script', 'population',
'total_strings', 'approved_strings', 'translated_strings',
'fuzzy_strings'
)
localizations = graphene.List(ProjectLocale, include_disabled=graphene.Boolean(False))
@graphene.resolve_only_args
def resolve_localizations(obj, include_disabled):
qs = obj.project_locale
if include_disabled:
return qs.all()
return qs.filter(project__disabled=False)
class Query(graphene.ObjectType):
debug = graphene.Field(DjangoDebug, name='__debug')
# include_disabled=True will return both active and disabled projects.
projects = graphene.List(Project, include_disabled=graphene.Boolean(False))
project = graphene.Field(Project, slug=graphene.String())
locales = graphene.List(Locale)
locale = graphene.Field(Locale, code=graphene.String())
def resolve_projects(obj, args, context, info):
qs = ProjectModel.objects
fields = get_fields(info)
if 'projects.localizations' in fields:
qs = qs.prefetch_related('project_locale__locale')
if 'projects.localizations.locale.localizations' in fields:
raise Exception('Cyclic queries are forbidden')
if args['include_disabled']:
return qs.all()
return qs.filter(disabled=False)
def resolve_project(obj, args, context, info):
qs = ProjectModel.objects
fields = get_fields(info)
if 'project.localizations' in fields:
qs = qs.prefetch_related('project_locale__locale')
if 'project.localizations.locale.localizations' in fields:
raise Exception('Cyclic queries are forbidden')
return qs.get(slug=args['slug'])
def resolve_locales(obj, args, context, info):
qs = LocaleModel.objects
fields = get_fields(info)
if 'locales.localizations' in fields:
qs = qs.prefetch_related('project_locale__project')
if 'locales.localizations.project.localizations' in fields:
raise Exception('Cyclic queries are forbidden')
return qs.all()
def resolve_locale(obj, args, context, info):
qs = LocaleModel.objects
fields = get_fields(info)
if 'locale.localizations' in fields:
qs = qs.prefetch_related('project_locale__project')
if 'locale.localizations.project.localizations' in fields:
raise Exception('Cyclic queries are forbidden')
return qs.get(code=args['code'])
schema = graphene.Schema(query=Query)
|
mastizada/pontoon
|
pontoon/api/schema.py
|
Python
|
bsd-3-clause
| 3,806 | 0.000263 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.test import TestCase
from ..forms import QuoteForm
class TestQuoteForm(TestCase):
def setUp(self):
pass
def test_validate_emtpy_quote(self):
form = QuoteForm({'message': ''})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': ' '})
self.assertFalse(form.is_valid())
def test_validate_invalid_quote(self):
form = QuoteForm({'message': 'Mensaje invalido'})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': 'mensaje invalido'})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': 'me nsaje invalido'})
self.assertFalse(form.is_valid())
def test_urls_in_quote(self):
form = QuoteForm({'message': 'http://122.33.43.322'})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': 'Me caga http://sabesquemecaga.com'})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': 'http://sabesquemecaga.com'})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': 'http://sabesquemecaga.com/asdfads/'})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': 'Me caga http://www.sabesquemecaga.com'})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': 'Me caga http://www.sabesquemecaga.com/test/12'})
self.assertFalse(form.is_valid())
def test_emails_in_quote(self):
form = QuoteForm({'message': 'Me caga test@test.com'})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': 'Me caga test.this@test.asdfas.com'})
self.assertFalse(form.is_valid())
def test_validate_short_quote(self):
form = QuoteForm({'message': 'Me caga '})
self.assertFalse(form.is_valid())
def test_validate_long_quote(self):
form = QuoteForm({'message': 'Me caga que sea que Este mensaje es demasiado largo y no pase las pruebas de lo que tenemos que probar asdfadfa adsfasdfa. Me caga que sea que Este mensaje es demasiado largo y no pase las pruebas de lo que tenemos que probar.'})
self.assertFalse(form.is_valid())
def test_valid_message(self):
form = QuoteForm({'message': 'Me caga probar esto'})
self.assertTrue(form.is_valid())
|
gabrielsaldana/sqmc
|
sabesqmc/quote/tests/test_forms.py
|
Python
|
agpl-3.0
| 2,384 | 0.001258 |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def main():
setup(
name = 'transloader',
packages=['transloader'],
package_dir = {'transloader':'transloader'},
version = open('VERSION.txt').read().strip(),
author='Mike Thornton',
author_email='six8@devdetails.com',
url='http://github.com/six8/transloader',
download_url='http://github.com/six8/transloader',
keywords=['transloadit'],
license='MIT',
description='A transloadit client',
classifiers = [
"Programming Language :: Python",
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Topic :: Software Development :: Libraries :: Python Modules",
],
long_description=open('README.rst').read(),
install_requires = [
'requests'
]
)
if __name__ == '__main__':
main()
|
six8/transloader
|
setup.py
|
Python
|
mit
| 1,083 | 0.012927 |
# Create a process that won't end on its own
import subprocess
process = subprocess.Popen(['python.exe', '-c', 'while 1: pass'])
# Kill the process using pywin32
import win32api
win32api.TerminateProcess(int(process._handle), -1)
# Kill the process using ctypes
import ctypes
ctypes.windll.kernel32.TerminateProcess(int(process._handle), -1)
# Kill the proces using pywin32 and pid
import win32api
PROCESS_TERMINATE = 1
handle = win32api.OpenProcess(PROCESS_TERMINATE, False, process.pid)
win32api.TerminateProcess(handle, -1)
win32api.CloseHandle(handle)
# Kill the proces using ctypes and pid
import ctypes
PROCESS_TERMINATE = 1
handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, process.pid)
ctypes.windll.kernel32.TerminateProcess(handle, -1)
ctypes.windll.kernel32.CloseHandle(handle)
|
ActiveState/code
|
recipes/Python/347462_Terminating_subprocess/recipe-347462.py
|
Python
|
mit
| 817 | 0.00612 |
# pylint: disable=missing-docstring
import logging
import numpy as np
from scipy import stats
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from edxval.api import get_videos_for_course
from openedx.core.djangoapps.request_cache.middleware import request_cached
from openedx.core.lib.api.view_utils import DeveloperErrorViewMixin, view_auth_classes
from openedx.core.lib.graph_traversals import traverse_pre_order
from xmodule.modulestore.django import modulestore
from .utils import get_bool_param, course_author_access_required
log = logging.getLogger(__name__)
@view_auth_classes()
class CourseQualityView(DeveloperErrorViewMixin, GenericAPIView):
"""
**Use Case**
**Example Requests**
GET /api/courses/v1/quality/{course_id}/
**GET Parameters**
A GET request may include the following parameters.
* all
* sections
* subsections
* units
* videos
* exclude_graded (boolean) - whether to exclude graded subsections in the subsections and units information.
**GET Response Values**
The HTTP 200 response has the following values.
* is_self_paced - whether the course is self-paced.
* sections
* total_number - number of sections in the course.
* total_visible - number of sections visible to learners in the course.
* number_with_highlights - number of sections that have at least one highlight entered.
* highlights_enabled - whether highlights are enabled in the course.
* subsections
* total_visible - number of subsections visible to learners in the course.
* num_with_one_block_type - number of visible subsections containing only one type of block.
* num_block_types - statistics for number of block types across all visible subsections.
* min
* max
* mean
* median
* mode
* units
* total_visible - number of units visible to learners in the course.
* num_blocks - statistics for number of block across all visible units.
* min
* max
* mean
* median
* mode
* videos
* total_number - number of video blocks in the course.
* num_with_val_id - number of video blocks that include video pipeline IDs.
* num_mobile_encoded - number of videos encoded through the video pipeline.
* durations - statistics for video duration across all videos encoded through the video pipeline.
* min
* max
* mean
* median
* mode
"""
@course_author_access_required
def get(self, request, course_key):
"""
Returns validation information for the given course.
"""
all_requested = get_bool_param(request, 'all', False)
store = modulestore()
with store.bulk_operations(course_key):
course = store.get_course(course_key, depth=self._required_course_depth(request, all_requested))
response = dict(
is_self_paced=course.self_paced,
)
if get_bool_param(request, 'sections', all_requested):
response.update(
sections=self._sections_quality(course)
)
if get_bool_param(request, 'subsections', all_requested):
response.update(
subsections=self._subsections_quality(course, request)
)
if get_bool_param(request, 'units', all_requested):
response.update(
units=self._units_quality(course, request)
)
if get_bool_param(request, 'videos', all_requested):
response.update(
videos=self._videos_quality(course)
)
return Response(response)
def _required_course_depth(self, request, all_requested):
if get_bool_param(request, 'units', all_requested):
# The num_blocks metric for "units" requires retrieving all blocks in the graph.
return None
elif get_bool_param(request, 'subsections', all_requested):
# The num_block_types metric for "subsections" requires retrieving all blocks in the graph.
return None
elif get_bool_param(request, 'sections', all_requested):
return 1
else:
return 0
def _sections_quality(self, course):
sections, visible_sections = self._get_sections(course)
sections_with_highlights = [s for s in visible_sections if s.highlights]
return dict(
total_number=len(sections),
total_visible=len(visible_sections),
number_with_highlights=len(sections_with_highlights),
highlights_enabled=course.highlights_enabled_for_messaging,
)
def _subsections_quality(self, course, request):
subsection_unit_dict = self._get_subsections_and_units(course, request)
num_block_types_per_subsection_dict = {}
for subsection_key, unit_dict in subsection_unit_dict.iteritems():
leaf_block_types_in_subsection = (
unit_info['leaf_block_types']
for unit_info in unit_dict.itervalues()
)
num_block_types_per_subsection_dict[subsection_key] = len(set().union(*leaf_block_types_in_subsection))
return dict(
total_visible=len(num_block_types_per_subsection_dict),
num_with_one_block_type=list(num_block_types_per_subsection_dict.itervalues()).count(1),
num_block_types=self._stats_dict(list(num_block_types_per_subsection_dict.itervalues())),
)
def _units_quality(self, course, request):
subsection_unit_dict = self._get_subsections_and_units(course, request)
num_leaf_blocks_per_unit = [
unit_info['num_leaf_blocks']
for unit_dict in subsection_unit_dict.itervalues()
for unit_info in unit_dict.itervalues()
]
return dict(
total_visible=len(num_leaf_blocks_per_unit),
num_blocks=self._stats_dict(num_leaf_blocks_per_unit),
)
def _videos_quality(self, course):
video_blocks_in_course = modulestore().get_items(course.id, qualifiers={'category': 'video'})
videos_in_val = list(get_videos_for_course(course.id))
video_durations = [video['duration'] for video in videos_in_val]
return dict(
total_number=len(video_blocks_in_course),
num_mobile_encoded=len(videos_in_val),
num_with_val_id=len([v for v in video_blocks_in_course if v.edx_video_id]),
durations=self._stats_dict(video_durations),
)
@request_cached
def _get_subsections_and_units(self, course, request):
"""
Returns {subsection_key: {unit_key: {num_leaf_blocks: <>, leaf_block_types: set(<>) }}}
for all visible subsections and units.
"""
_, visible_sections = self._get_sections(course)
subsection_dict = {}
for section in visible_sections:
visible_subsections = self._get_visible_children(section)
if get_bool_param(request, 'exclude_graded', False):
visible_subsections = [s for s in visible_subsections if not s.graded]
for subsection in visible_subsections:
unit_dict = {}
visible_units = self._get_visible_children(subsection)
for unit in visible_units:
leaf_blocks = self._get_leaf_blocks(unit)
unit_dict[unit.location] = dict(
num_leaf_blocks=len(leaf_blocks),
leaf_block_types=set(block.location.block_type for block in leaf_blocks),
)
subsection_dict[subsection.location] = unit_dict
return subsection_dict
@request_cached
def _get_sections(self, course):
return self._get_all_children(course)
def _get_all_children(self, parent):
store = modulestore()
children = [store.get_item(child_usage_key) for child_usage_key in self._get_children(parent)]
visible_children = [
c for c in children
if not c.visible_to_staff_only and not c.hide_from_toc
]
return children, visible_children
def _get_visible_children(self, parent):
_, visible_chidren = self._get_all_children(parent)
return visible_chidren
def _get_children(self, parent):
if not hasattr(parent, 'children'):
return []
else:
return parent.children
def _get_leaf_blocks(self, unit):
def leaf_filter(block):
return (
block.location.block_type not in ('chapter', 'sequential', 'vertical') and
len(self._get_children(block)) == 0
)
return [
block for block in
traverse_pre_order(unit, self._get_visible_children, leaf_filter)
]
def _stats_dict(self, data):
if not data:
return dict(
min=None,
max=None,
mean=None,
median=None,
mode=None,
)
else:
return dict(
min=min(data),
max=max(data),
mean=np.around(np.mean(data)),
median=np.around(np.median(data)),
mode=stats.mode(data, axis=None)[0][0],
)
|
gsehub/edx-platform
|
cms/djangoapps/contentstore/api/views/course_quality.py
|
Python
|
agpl-3.0
| 9,779 | 0.002761 |
def extractFinebymetranslationsWordpressCom(item):
'''
Parser for 'finebymetranslations.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Death Progress Bar', 'Death Progress Bar', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
fake-name/ReadableWebProxy
|
WebMirror/management/rss_parser_funcs/feed_parse_extractFinebymetranslationsWordpressCom.py
|
Python
|
bsd-3-clause
| 666 | 0.028529 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# iflytek.py ---
#
# Filename: iflytek.py
# Description:
# Author: Werther Zhang
# Maintainer:
# Created: Thu Sep 14 09:01:20 2017 (+0800)
#
# Change Log:
#
#
import time
from ctypes import *
from io import BytesIO
import wave
import platform
import logging
import os
import contextlib
logging.basicConfig(level=logging.DEBUG)
BASEPATH=os.path.split(os.path.realpath(__file__))[0]
def not_none_return(obj, defobj):
if obj:
return obj
else:
return defobj
class iflytekTTS():
def __init__(self, appid=None, voice_name=None, speed=None, volume=None, pitch=None):
self.__appid = not_none_return(appid, '59b4d5d4')
self.__voice_name = not_none_return(voice_name, 'xiaowanzi')
self.__speed = not_none_return(speed, 50)
self.__volume = not_none_return(volume, 50)
self.__pitch = not_none_return(pitch, 50)
self.__cur = cdll.LoadLibrary(os.path.join(BASEPATH, 'iflytek/libmsc.so'))
self.__iflytek_init()
def __save_file(self, raw_data, _tmpFile = '/tmp/test.wav'):
if os.path.exists(_tmpFile) :
return
tmpFile = _tmpFile + '.tmp'
with contextlib.closing(wave.open(tmpFile , 'w')) as f:
f.setparams((1, 2, 16000, 262720, 'NONE', 'not compressed'))
f.writeframesraw(raw_data)
os.rename(tmpFile, _tmpFile)
def __iflytek_init(self):
MSPLogin = self.__cur.MSPLogin
ret = MSPLogin(None,None,'appid = {}, work_dir = .'.format(self.__appid))
if ret != 0:
logging.error("MSPLogin failed, error code: {}".format(ret))
return False
return True
def get_tts_audio(self, src_text, filename, language='zh', options=None):
fname = os.path.join('/tmp/', filename + '.' + 'wav')
QTTSSessionBegin = self.__cur.QTTSSessionBegin
QTTSTextPut = self.__cur.QTTSTextPut
QTTSAudioGet = self.__cur.QTTSAudioGet
QTTSAudioGet.restype = c_void_p
QTTSSessionEnd = self.__cur.QTTSSessionEnd
ret_c = c_int(0)
ret = 0
session_begin_params="voice_name = {}, text_encoding = utf8, sample_rate = 16000, speed = {}, volume = {}, pitch = {}, rdn = 2".format(self.__voice_name, self.__speed, self.__volume, self.__pitch)
sessionID = QTTSSessionBegin(session_begin_params, byref(ret_c))
if ret_c.value == 10111: # 没有初始化
if self.__iflytek_init():
return self.get_tts_audio(src_text, filename)
if ret_c.value != 0:
logging.error("QTTSSessionBegin failed, error code: {}".format(ret_c.value))
return
ret = QTTSTextPut(sessionID, src_text, len(src_text), None)
if ret != 0:
logging.error("QTTSTextPut failed, error code:{}".format(ret))
QTTSSessionEnd(sessionID, "TextPutError")
return
logging.info("正在合成 [{}]...".format(src_text))
audio_len = c_uint(0)
synth_status = c_int(0)
f = BytesIO()
while True:
p = QTTSAudioGet(sessionID, byref(audio_len), byref(synth_status), byref(ret_c))
if ret_c.value != 0:
logging.error("QTTSAudioGet failed, error code: {}".format(ret_c))
QTTSSessionEnd(sessionID, "AudioGetError")
break
if p != None:
buf = (c_char * audio_len.value).from_address(p)
f.write(buf)
if synth_status.value == 2:
self.__save_file(f.getvalue(), fname)
break
time.sleep(0.5)
logging.info('合成完成!')
ret = QTTSSessionEnd(sessionID, "Normal")
if ret != 0:
logging.error("QTTSSessionEnd failed, error code:{}".format(ret))
return ('wav', fname)
if __name__ == '__main__':
tts = iflytekTTS()
def md5sum(contents):
import hashlib
hash = hashlib.md5()
hash.update(contents)
return hash.hexdigest()
import sys
basename = md5sum(sys.argv[1])
t, f = tts.get_tts_audio(sys.argv[1], basename, 'zh');
def mplayer(f):
import commands
st, output = commands.getstatusoutput('mplayer -really-quiet -noconsolecontrols -volume 82 {}'.format(f))
mplayer(f)
import os
print f
basename = md5sum(sys.argv[1][:-1])
t, f = tts.get_tts_audio(sys.argv[1][:-1], basename, 'zh');
print f
#os.remove(f)
|
pengzhangdev/slackbot
|
slackbot/plugins/component/ttsdriver/iflytek.py
|
Python
|
mit
| 4,519 | 0.005567 |
from __future__ import with_statement
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from flask import current_app
config.set_main_option('sqlalchemy.url',
current_app.config.get('SQLALCHEMY_DATABASE_URI'))
target_metadata = current_app.extensions['migrate'].db.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(url=url,
transaction_per_migration=True)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
engine = engine_from_config(config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool)
connection = engine.connect()
context.configure(connection=connection,
target_metadata=target_metadata,
transaction_per_migration=True)
try:
with context.begin_transaction():
context.run_migrations()
finally:
connection.close()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
|
cuducos/findaconf
|
migrations/env.py
|
Python
|
mit
| 2,277 | 0.000878 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-09-17 19:11
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('travel', '0004_auto_20160319_0055'),
]
operations = [
migrations.RemoveField(
model_name='post',
name='category',
),
migrations.RemoveField(
model_name='post',
name='post',
),
migrations.RemoveField(
model_name='post',
name='post_en',
),
migrations.RemoveField(
model_name='post',
name='post_ru',
),
migrations.RemoveField(
model_name='tag',
name='category',
),
migrations.DeleteModel(
name='Category',
),
]
|
avaika/avaikame
|
project/travel/migrations/0005_auto_20160917_2211.py
|
Python
|
gpl-3.0
| 868 | 0 |
"""
This module collects helper functions and classes that "span" multiple levels
of MVC. In other words, these functions/classes introduce controlled coupling
for convenience's sake.
"""
from django.http import (
Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect,
)
from django.template import loader
from django.urls import NoReverseMatch, reverse
from django.utils.functional import Promise
def render(request, template_name, context=None, content_type=None, status=None, using=None):
"""
Return a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
"""
content = loader.render_to_string(template_name, context, request, using=using)
return HttpResponse(content, content_type, status)
def redirect(to, *args, permanent=False, **kwargs):
"""
Return an HttpResponseRedirect to the appropriate URL for the arguments
passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urls.reverse()` will be used
to reverse-resolve the name.
* A URL, which will be used as-is for the redirect location.
Issues a temporary redirect by default; pass permanent=True to issue a
permanent redirect.
"""
redirect_class = HttpResponsePermanentRedirect if permanent else HttpResponseRedirect
return redirect_class(resolve_url(to, *args, **kwargs))
def _get_queryset(klass):
"""
Return a QuerySet or a Manager.
Duck typing in action: any class with a `get()` method (for
get_object_or_404) or a `filter()` method (for get_list_or_404) might do
the job.
"""
# If it is a model class or anything else with ._default_manager
if hasattr(klass, '_default_manager'):
return klass._default_manager.all()
return klass
def get_object_or_404(klass, *args, **kwargs):
"""
Use get() to return an object, or raise a Http404 exception if the object
does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the get() query.
Like with QuerySet.get(), MultipleObjectsReturned is raised if more than
one object is found.
"""
queryset = _get_queryset(klass)
if not hasattr(queryset, 'get'):
klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
raise ValueError(
"First argument to get_object_or_404() must be a Model, Manager, "
"or QuerySet, not '%s'." % klass__name
)
try:
return queryset.get(*args, **kwargs)
except queryset.model.DoesNotExist:
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
def get_list_or_404(klass, *args, **kwargs):
"""
Use filter() to return a list of objects, or raise a Http404 exception if
the list is empty.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the filter() query.
"""
queryset = _get_queryset(klass)
if not hasattr(queryset, 'filter'):
klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
raise ValueError(
"First argument to get_list_or_404() must be a Model, Manager, or "
"QuerySet, not '%s'." % klass__name
)
obj_list = list(queryset.filter(*args, **kwargs))
if not obj_list:
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
return obj_list
def resolve_url(to, *args, **kwargs):
"""
Return a URL appropriate for the arguments passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urls.reverse()` will be used
to reverse-resolve the name.
* A URL, which will be returned as-is.
"""
# If it's a model, use get_absolute_url()
if hasattr(to, 'get_absolute_url'):
return to.get_absolute_url()
if isinstance(to, Promise):
# Expand the lazy instance, as it can cause issues when it is passed
# further to some Python functions like urlparse.
to = str(to)
if isinstance(to, str):
# Handle relative URLs
if to.startswith(('./', '../')):
return to
# Next try a reverse URL resolution.
try:
return reverse(to, args=args, kwargs=kwargs)
except NoReverseMatch:
# If this is a callable, re-raise.
if callable(to):
raise
# If this doesn't "feel" like a URL, re-raise.
if '/' not in to and '.' not in to:
raise
# Finally, fall back and assume it's a URL
return to
|
georgemarshall/django
|
django/shortcuts.py
|
Python
|
bsd-3-clause
| 4,896 | 0.00143 |
# Copyright (c) 2014 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import mock
from sahara.plugins import base as base_plugins
from sahara.service import ops
from sahara.tests.unit import base
class FakeCluster(object):
id = 'id'
status = "Some_status"
name = "Fake_cluster"
class FakeNodeGroup(object):
id = 'id'
count = 2
instances = [1, 2]
class FakePlugin(mock.Mock):
node_groups = [FakeNodeGroup()]
def update_infra(self, cluster):
TestOPS.SEQUENCE.append('update_infra')
def configure_cluster(self, cluster):
TestOPS.SEQUENCE.append('configure_cluster')
def start_cluster(self, cluster):
TestOPS.SEQUENCE.append('start_cluster')
def on_terminate_cluster(self, cluster):
TestOPS.SEQUENCE.append('on_terminate_cluster')
def decommission_nodes(self, cluster, instances_to_delete):
TestOPS.SEQUENCE.append('decommission_nodes')
def scale_cluster(self, cluster, node_group_id_map):
TestOPS.SEQUENCE.append('plugin.scale_cluster')
def cluster_destroy(self, ctx, cluster):
TestOPS.SEQUENCE.append('cluster_destroy')
class FakeINFRA(object):
def create_cluster(self, cluster):
TestOPS.SEQUENCE.append('create_cluster')
def scale_cluster(self, cluster, node_group_id_map):
TestOPS.SEQUENCE.append('INFRA.scale_cluster')
return True
def shutdown_cluster(self, cluster):
TestOPS.SEQUENCE.append('shutdown_cluster')
def rollback_cluster(self, cluster, reason):
TestOPS.SEQUENCE.append('rollback_cluster')
class TestOPS(base.SaharaWithDbTestCase):
SEQUENCE = []
@mock.patch('sahara.utils.general.change_cluster_status_description',
return_value=FakeCluster())
@mock.patch('sahara.service.ops._update_sahara_info')
@mock.patch('sahara.service.ops._prepare_provisioning',
return_value=(mock.Mock(), mock.Mock(), FakePlugin()))
@mock.patch('sahara.utils.general.change_cluster_status')
@mock.patch('sahara.conductor.API.cluster_get')
@mock.patch('sahara.service.ops.CONF')
@mock.patch('sahara.service.trusts.create_trust_for_cluster')
@mock.patch('sahara.conductor.API.job_execution_get_all')
@mock.patch('sahara.service.edp.job_manager.run_job')
def test_provision_cluster(self, p_run_job, p_job_exec, p_create_trust,
p_conf, p_cluster_get, p_change_status,
p_prep_provisioning, p_update_sahara_info,
p_change_cluster_status_desc):
del self.SEQUENCE[:]
ops.INFRA = FakeINFRA()
ops._provision_cluster('123')
# checking that order of calls is right
self.assertEqual(['update_infra', 'create_cluster',
'configure_cluster', 'start_cluster'], self.SEQUENCE,
'Order of calls is wrong')
@mock.patch('sahara.service.ops._prepare_provisioning',
return_value=(mock.Mock(), mock.Mock(), FakePlugin()))
@mock.patch('sahara.utils.general.change_cluster_status',
return_value=FakePlugin())
@mock.patch('sahara.utils.general.get_instances')
def test_provision_scaled_cluster(self, p_get_instances, p_change_status,
p_prep_provisioning):
del self.SEQUENCE[:]
ops.INFRA = FakeINFRA()
ops._provision_scaled_cluster('123', {'id': 1})
# checking that order of calls is right
self.assertEqual(['decommission_nodes', 'INFRA.scale_cluster',
'plugin.scale_cluster'], self.SEQUENCE,
'Order of calls is wrong')
@mock.patch('sahara.service.ops.CONF')
@mock.patch('sahara.service.trusts.delete_trust_from_cluster')
@mock.patch('sahara.context.ctx')
def test_terminate_cluster(self, p_ctx, p_delete_trust, p_conf):
del self.SEQUENCE[:]
base_plugins.PLUGINS = FakePlugin()
base_plugins.PLUGINS.get_plugin.return_value = FakePlugin()
ops.INFRA = FakeINFRA()
ops.conductor = FakePlugin()
ops.terminate_cluster('123')
# checking that order of calls is right
self.assertEqual(['on_terminate_cluster', 'shutdown_cluster',
'cluster_destroy'], self.SEQUENCE,
'Order of calls is wrong')
@mock.patch('sahara.utils.general.change_cluster_status_description')
@mock.patch('sahara.service.ops._prepare_provisioning')
@mock.patch('sahara.utils.general.change_cluster_status')
@mock.patch('sahara.service.ops._rollback_cluster')
@mock.patch('sahara.conductor.API.cluster_get')
def test_ops_error_hadler_success_rollback(
self, p_cluster_get, p_rollback_cluster, p_change_cluster_status,
p__prepare_provisioning, p_change_cluster_status_desc):
# Test scenario: failed scaling -> success_rollback
fake_cluster = FakeCluster()
p_change_cluster_status_desc.return_value = FakeCluster()
p_rollback_cluster.return_value = True
p_cluster_get.return_value = fake_cluster
p__prepare_provisioning.side_effect = ValueError('error1')
expected = [
mock.call(fake_cluster, 'Active',
'Scaling cluster failed for the following '
'reason(s): error1')
]
ops._provision_scaled_cluster(fake_cluster.id, {'id': 1})
self.assertEqual(expected, p_change_cluster_status.call_args_list)
@mock.patch('sahara.utils.general.change_cluster_status_description')
@mock.patch('sahara.service.ops._prepare_provisioning')
@mock.patch('sahara.utils.general.change_cluster_status')
@mock.patch('sahara.service.ops._rollback_cluster')
@mock.patch('sahara.conductor.API.cluster_get')
def test_ops_error_hadler_failed_rollback(
self, p_cluster_get, p_rollback_cluster, p_change_cluster_status,
p__prepare_provisioning, p_change_cluster_status_desc):
# Test scenario: failed scaling -> failed_rollback
fake_cluster = FakeCluster()
p_change_cluster_status_desc.return_value = FakeCluster()
p__prepare_provisioning.side_effect = ValueError('error1')
p_rollback_cluster.side_effect = ValueError('error2')
p_cluster_get.return_value = fake_cluster
expected = [
mock.call(
fake_cluster, 'Error', 'Scaling cluster failed for the '
'following reason(s): error1, error2')
]
ops._provision_scaled_cluster(fake_cluster.id, {'id': 1})
self.assertEqual(expected, p_change_cluster_status.call_args_list)
|
esikachev/scenario
|
sahara/tests/unit/service/test_ops.py
|
Python
|
apache-2.0
| 7,257 | 0 |
"""
WSGI config for vcert project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "vcert.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "vcert.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
managai/myCert
|
vcert/wsgi.py
|
Python
|
mpl-2.0
| 1,416 | 0.000706 |
import random
from test import *
from branch import *
def test(rm, fn):
name = 'test_blx_reg_a1_%s' % tn()
cleanup = asm_wrap(name, 'r0')
print ' adr %s, %s' % (rm, fn)
if fn.startswith('thumb'):
print ' orr %s, #1' % (rm)
print '%s_tinsn:' % name
print ' blx %s' % (rm)
cleanup()
def iter_cases():
fun = 'thumb_fun_b thumb_fun_f arm_fun_b arm_fun_f'.split()
while True:
yield random.choice(T32REGS), random.choice(fun)
branch_helpers('b')
print ' .arm'
tests(test, iter_cases(), 30)
branch_helpers('f')
|
Samsung/ADBI
|
arch/arm/tests/blx_reg_a1.py
|
Python
|
apache-2.0
| 580 | 0.008621 |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import unittest
from unittest import mock
import telegram
import airflow
from airflow.models import Connection
from airflow.providers.telegram.hooks.telegram import TelegramHook
from airflow.utils import db
TELEGRAM_TOKEN = "dummy token"
class TestTelegramHook(unittest.TestCase):
def setUp(self):
db.merge_conn(
Connection(
conn_id='telegram-webhook-without-token',
conn_type='http',
)
)
db.merge_conn(
Connection(
conn_id='telegram_default',
conn_type='http',
password=TELEGRAM_TOKEN,
)
)
db.merge_conn(
Connection(
conn_id='telegram-webhook-with-chat_id',
conn_type='http',
password=TELEGRAM_TOKEN,
host="-420913222",
)
)
def test_should_raise_exception_if_both_connection_or_token_is_not_provided(self):
with self.assertRaises(airflow.exceptions.AirflowException) as e:
TelegramHook()
self.assertEqual("Cannot get token: No valid Telegram connection supplied.", str(e.exception))
def test_should_raise_exception_if_conn_id_doesnt_exist(self):
with self.assertRaises(airflow.exceptions.AirflowNotFoundException) as e:
TelegramHook(telegram_conn_id='telegram-webhook-non-existent')
self.assertEqual("The conn_id `telegram-webhook-non-existent` isn't defined", str(e.exception))
def test_should_raise_exception_if_conn_id_doesnt_contain_token(self):
with self.assertRaises(airflow.exceptions.AirflowException) as e:
TelegramHook(telegram_conn_id='telegram-webhook-without-token')
self.assertEqual("Missing token(password) in Telegram connection", str(e.exception))
@mock.patch('airflow.providers.telegram.hooks.telegram.TelegramHook.get_conn')
def test_should_raise_exception_if_chat_id_is_not_provided_anywhere(self, mock_get_conn):
with self.assertRaises(airflow.exceptions.AirflowException) as e:
hook = TelegramHook(telegram_conn_id='telegram_default')
hook.send_message({"text": "test telegram message"})
self.assertEqual("'chat_id' must be provided for telegram message", str(e.exception))
@mock.patch('airflow.providers.telegram.hooks.telegram.TelegramHook.get_conn')
def test_should_raise_exception_if_message_text_is_not_provided(self, mock_get_conn):
with self.assertRaises(airflow.exceptions.AirflowException) as e:
hook = TelegramHook(telegram_conn_id='telegram_default')
hook.send_message({"chat_id": -420913222})
self.assertEqual("'text' must be provided for telegram message", str(e.exception))
@mock.patch('airflow.providers.telegram.hooks.telegram.TelegramHook.get_conn')
def test_should_send_message_if_all_parameters_are_correctly_provided(self, mock_get_conn):
mock_get_conn.return_value = mock.Mock(password="some_token")
hook = TelegramHook(telegram_conn_id='telegram_default')
hook.send_message({"chat_id": -420913222, "text": "test telegram message"})
mock_get_conn.return_value.send_message.return_value = "OK."
mock_get_conn.assert_called_once()
mock_get_conn.return_value.send_message.assert_called_once_with(
**{
'chat_id': -420913222,
'parse_mode': 'HTML',
'disable_web_page_preview': True,
'text': 'test telegram message',
}
)
@mock.patch('airflow.providers.telegram.hooks.telegram.TelegramHook.get_conn')
def test_should_send_message_if_chat_id_is_provided_through_constructor(self, mock_get_conn):
mock_get_conn.return_value = mock.Mock(password="some_token")
hook = TelegramHook(telegram_conn_id='telegram_default', chat_id=-420913222)
hook.send_message({"text": "test telegram message"})
mock_get_conn.return_value.send_message.return_value = "OK."
mock_get_conn.assert_called_once()
mock_get_conn.return_value.send_message.assert_called_once_with(
**{
'chat_id': -420913222,
'parse_mode': 'HTML',
'disable_web_page_preview': True,
'text': 'test telegram message',
}
)
@mock.patch('airflow.providers.telegram.hooks.telegram.TelegramHook.get_conn')
def test_should_send_message_if_chat_id_is_provided_in_connection(self, mock_get_conn):
mock_get_conn.return_value = mock.Mock(password="some_token")
hook = TelegramHook(telegram_conn_id='telegram-webhook-with-chat_id')
hook.send_message({"text": "test telegram message"})
mock_get_conn.return_value.send_message.return_value = "OK."
mock_get_conn.assert_called_once()
mock_get_conn.return_value.send_message.assert_called_once_with(
**{
'chat_id': "-420913222",
'parse_mode': 'HTML',
'disable_web_page_preview': True,
'text': 'test telegram message',
}
)
@mock.patch('airflow.providers.telegram.hooks.telegram.TelegramHook.get_conn')
def test_should_retry_when_any_telegram_error_is_encountered(self, mock_get_conn):
excepted_retry_count = 5
mock_get_conn.return_value = mock.Mock(password="some_token")
def side_effect(*args, **kwargs):
raise telegram.error.TelegramError("cosmic rays caused bit flips")
mock_get_conn.return_value.send_message.side_effect = side_effect
with self.assertRaises(Exception) as e:
hook = TelegramHook(telegram_conn_id='telegram-webhook-with-chat_id')
hook.send_message({"text": "test telegram message"})
self.assertTrue("RetryError" in str(e.exception))
self.assertTrue("state=finished raised TelegramError" in str(e.exception))
mock_get_conn.assert_called_once()
mock_get_conn.return_value.send_message.assert_called_with(
**{
'chat_id': "-420913222",
'parse_mode': 'HTML',
'disable_web_page_preview': True,
'text': 'test telegram message',
}
)
self.assertEqual(excepted_retry_count, mock_get_conn.return_value.send_message.call_count)
@mock.patch('airflow.providers.telegram.hooks.telegram.TelegramHook.get_conn')
def test_should_send_message_if_token_is_provided(self, mock_get_conn):
mock_get_conn.return_value = mock.Mock(password="some_token")
hook = TelegramHook(token=TELEGRAM_TOKEN, chat_id=-420913222)
hook.send_message({"text": "test telegram message"})
mock_get_conn.return_value.send_message.return_value = "OK."
mock_get_conn.assert_called_once()
mock_get_conn.return_value.send_message.assert_called_once_with(
**{
'chat_id': -420913222,
'parse_mode': 'HTML',
'disable_web_page_preview': True,
'text': 'test telegram message',
}
)
|
airbnb/airflow
|
tests/providers/telegram/hooks/test_telegram.py
|
Python
|
apache-2.0
| 7,973 | 0.003136 |
# -----------------
# lambdas
# -----------------
a = lambda: 3
#? int()
a()
x = []
a = lambda x: x
#? int()
a(0)
#? float()
(lambda x: x)(3.0)
arg_l = lambda x, y: y, x
#? float()
arg_l[0]('', 1.0)
#? list()
arg_l[1]
arg_l = lambda x, y: (y, x)
args = 1,""
result = arg_l(*args)
#? tuple()
result
#? str()
result[0]
#? int()
result[1]
def with_lambda(callable_lambda, *args, **kwargs):
return callable_lambda(1, *args, **kwargs)
#? int()
with_lambda(arg_l, 1.0)[1]
#? float()
with_lambda(arg_l, 1.0)[0]
#? float()
with_lambda(arg_l, y=1.0)[0]
#? int()
with_lambda(lambda x: x)
#? float()
with_lambda(lambda x, y: y, y=1.0)
arg_func = lambda *args, **kwargs: (args[0], kwargs['a'])
#? int()
arg_func(1, 2, a='', b=10)[0]
#? list()
arg_func(1, 2, a=[], b=10)[1]
# magic method
a = lambda: 3
#? ['__closure__']
a.__closure__
class C():
def __init__(self, foo=1.0):
self.a = lambda: 1
self.foo = foo
def ret(self):
return lambda: self.foo
def with_param(self):
return lambda x: x + self.a()
lambd = lambda self: self.foo
#? int()
C().a()
#? str()
C('foo').ret()()
index = C().with_param()(1)
#? float()
['', 1, 1.0][index]
#? float()
C().lambd()
#? int()
C(1).lambd()
def xy(param):
def ret(a, b):
return a + b
return lambda b: ret(param, b)
#? int()
xy(1)(2)
# -----------------
# lambda param (#379)
# -----------------
class Test(object):
def __init__(self, pred=lambda a, b: a):
self.a = 1
#? int()
self.a
#? float()
pred(1.0, 2)
# -----------------
# test_nocond in grammar (happens in list comprehensions with `if`)
# -----------------
# Doesn't need to do anything yet. It should just not raise an error. These
# nocond lambdas make no sense at all.
#? int()
[a for a in [1,2] if lambda: 3][0]
|
snakeleon/YouCompleteMe-x64
|
third_party/ycmd/third_party/jedi_deps/jedi/test/completion/lambdas.py
|
Python
|
gpl-3.0
| 1,833 | 0.022368 |
##
# Copyright (c) 2015-2017 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
from twext.enterprise.dal.record import fromTable
from twext.enterprise.jobs.workitem import WorkItem
from twisted.internet.defer import inlineCallbacks
from txdav.caldav.datastore.scheduling.imip.token import iMIPTokenRecord
from txdav.caldav.datastore.scheduling.work import allScheduleWork
from txdav.common.datastore.podding.migration.sync_metadata import CalendarMigrationRecord, \
CalendarObjectMigrationRecord, AttachmentMigrationRecord
from txdav.common.datastore.sql_directory import DelegateRecord, \
DelegateGroupsRecord, ExternalDelegateGroupsRecord
from txdav.common.datastore.sql_tables import schema, _HOME_STATUS_DISABLED
class HomeCleanupWork(WorkItem, fromTable(schema.HOME_CLEANUP_WORK)):
"""
Work item to clean up any previously "external" homes on the pod to which data was migrated to. Those
old homes will now be marked as disabled and need to be silently removed without any side effects
(i.e., no implicit scheduling, no sharing cancels, etc).
"""
group = "ownerUID"
notBeforeDelay = 300 # 5 minutes
@inlineCallbacks
def doWork(self):
"""
Delete all the corresponding homes.
"""
oldhome = yield self.transaction.calendarHomeWithUID(self.ownerUID, status=_HOME_STATUS_DISABLED)
if oldhome is not None:
yield oldhome.purgeAll()
oldnotifications = yield self.transaction.notificationsWithUID(self.ownerUID, status=_HOME_STATUS_DISABLED)
if oldnotifications is not None:
yield oldnotifications.purge()
class MigratedHomeCleanupWork(WorkItem, fromTable(schema.MIGRATED_HOME_CLEANUP_WORK)):
"""
Work item to clean up the old home data left behind after migration, as well
as other unwanted items like iMIP tokens, delegates etc. The old homes will
now be marked as disabled and need to be silently removed without any side
effects (i.e., no implicit scheduling, no sharing cancels, etc).
"""
group = "ownerUID"
notBeforeDelay = 300 # 5 minutes
@inlineCallbacks
def doWork(self):
"""
Delete all the corresponding homes, then the ancillary data.
"""
oldhome = yield self.transaction.calendarHomeWithUID(self.ownerUID, status=_HOME_STATUS_DISABLED)
if oldhome is not None:
# Work items - we need to clean these up before the home goes away because we have an "on delete cascade" on the WorkItem
# table, and if that ran it would leave orphaned Job rows set to a pause state and those would remain for ever in the table.
for workType in allScheduleWork:
items = yield workType.query(self.transaction, workType.homeResourceID == oldhome.id())
for item in items:
yield item.remove()
yield oldhome.purgeAll()
oldnotifications = yield self.transaction.notificationsWithUID(self.ownerUID, status=_HOME_STATUS_DISABLED)
if oldnotifications is not None:
yield oldnotifications.purge()
# These are things that reference the home id or the user UID but don't get removed via a cascade
# iMIP tokens
cuaddr = "urn:x-uid:{}".format(self.ownerUID)
yield iMIPTokenRecord.deletesome(
self.transaction,
iMIPTokenRecord.organizer == cuaddr,
)
# Delegators - individual and group
yield DelegateRecord.deletesome(self.transaction, DelegateRecord.delegator == self.ownerUID)
yield DelegateGroupsRecord.deletesome(self.transaction, DelegateGroupsRecord.delegator == self.ownerUID)
yield ExternalDelegateGroupsRecord.deletesome(self.transaction, ExternalDelegateGroupsRecord.delegator == self.ownerUID)
class MigrationCleanupWork(WorkItem, fromTable(schema.MIGRATION_CLEANUP_WORK)):
group = "homeResourceID"
notBeforeDelay = 300 # 5 minutes
@inlineCallbacks
def doWork(self):
"""
Delete all the corresponding migration records.
"""
yield CalendarMigrationRecord.deletesome(
self.transaction,
CalendarMigrationRecord.calendarHomeResourceID == self.homeResourceID,
)
yield CalendarObjectMigrationRecord.deletesome(
self.transaction,
CalendarObjectMigrationRecord.calendarHomeResourceID == self.homeResourceID,
)
yield AttachmentMigrationRecord.deletesome(
self.transaction,
AttachmentMigrationRecord.calendarHomeResourceID == self.homeResourceID,
)
|
macosforge/ccs-calendarserver
|
txdav/common/datastore/podding/migration/work.py
|
Python
|
apache-2.0
| 5,171 | 0.003674 |
#!/usr/bin/env python
#
# ___INFO__MARK_BEGIN__
#######################################################################################
# Copyright 2016-2021 Univa Corporation (acquired and owned by Altair Engineering 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.
#######################################################################################
# ___INFO__MARK_END__
#
import tempfile
import types
from .utils import needs_uge
from .utils import generate_random_string
from .utils import create_config_file
from .utils import load_values
from uge.api.qconf_api import QconfApi
from uge.config.config_manager import ConfigManager
from uge.log.log_manager import LogManager
from uge.exceptions.object_not_found import ObjectNotFound
from uge.exceptions.object_already_exists import ObjectAlreadyExists
create_config_file()
API = QconfApi()
PE_NAME = '%s.q' % generate_random_string(6)
CONFIG_MANAGER = ConfigManager.get_instance()
LOG_MANAGER = LogManager.get_instance()
VALUES_DICT = load_values('test_values.json')
print(VALUES_DICT)
@needs_uge
def test_object_not_found():
try:
pe = API.get_pe('__non_existent_pe__')
assert (False)
except ObjectNotFound as ex:
# ok
pass
def test_generate_pe():
pe = API.generate_pe(PE_NAME)
assert (pe.data['pe_name'] == PE_NAME)
def test_add_pe():
try:
pel = API.list_pes()
except ObjectNotFound as ex:
# no pes defined
pel = []
pe = API.add_pe(name=PE_NAME)
assert (pe.data['pe_name'] == PE_NAME)
pel2 = API.list_pes()
assert (len(pel2) == len(pel) + 1)
assert (pel2.count(PE_NAME) == 1)
def test_list_pes():
pel = API.list_pes()
assert (pel is not None)
def test_object_already_exists():
try:
pe = API.add_pe(name=PE_NAME)
assert (False)
except ObjectAlreadyExists as ex:
# ok
pass
def test_get_pe():
pe = API.get_pe(PE_NAME)
assert (pe.data['pe_name'] == PE_NAME)
def test_generate_pe_from_json():
pe = API.get_pe(PE_NAME)
json = pe.to_json()
pe2 = API.generate_object(json)
assert (pe2.__class__.__name__ == pe.__class__.__name__)
for key in list(pe.data.keys()):
v = pe.data[key]
v2 = pe2.data[key]
if type(v) == list:
assert (len(v) == len(v2))
for s in v:
assert (v2.count(s) == 1)
elif type(v) == dict:
for key in list(v.keys()):
assert (str(v[key]) == str(v2[key]))
else:
assert (str(v) == str(v2))
def test_modify_pe():
pe = API.get_pe(PE_NAME)
slots = pe.data['slots']
pe = API.modify_pe(name=PE_NAME, data={'slots': slots + 1})
slots2 = pe.data['slots']
assert (slots2 == slots + 1)
def test_get_acls():
pel = API.list_pes()
pes = API.get_pes()
for pe in pes:
print("#############################################")
print(pe.to_uge())
assert (pe.data['pe_name'] in pel)
def test_write_pes():
try:
tdir = tempfile.mkdtemp()
print("*************************** " + tdir)
pe_names = VALUES_DICT['pe_names']
pes = API.get_pes()
for pe in pes:
print("Before #############################################")
print(pe.to_uge())
new_pes = []
for name in pe_names:
npe = API.generate_pe(name=name)
new_pes.append(npe)
API.mk_pes_dir(tdir)
API.write_pes(new_pes, tdir)
API.add_pes_from_dir(tdir)
API.modify_pes_from_dir(tdir)
pes = API.get_pes()
for pe in pes:
print("After #############################################")
print(pe.to_uge())
pes = API.list_pes()
for name in pe_names:
assert (name in pes)
print("pe found: " + name)
finally:
API.delete_pes_from_dir(tdir)
API.rm_pes_dir(tdir)
def test_add_pes():
try:
new_pes = []
pe_names = VALUES_DICT['pe_names']
for name in pe_names:
npe = API.generate_pe(name=name)
new_pes.append(npe)
# print all pes currently in the cluster
pes = API.get_pes()
for pe in pes:
print("Before #############################################")
print(pe.to_uge())
# add pes
API.add_pes(new_pes)
API.modify_pes(new_pes)
# print all pes currently in the cluster
pes = API.get_pes()
for pe in pes:
print("After #############################################")
print(pe.to_uge())
# check that cals have been added
pes = API.list_pes()
for name in pe_names:
assert (name in pes)
print("pe found: " + name)
finally:
API.delete_pes(new_pes)
def test_delete_pe():
pel = API.list_pes()
API.delete_pe(PE_NAME)
try:
pel2 = API.list_pes()
except ObjectNotFound as ex:
# no pes defined
pel2 = []
assert (len(pel2) == len(pel) - 1)
assert (pel2.count(PE_NAME) == 0)
|
gridengine/config-api
|
test/test_parallel_environment.py
|
Python
|
apache-2.0
| 5,641 | 0.000709 |
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.nix_vector_routing', cpp_namespace='::ns3')
return root_module
def register_types(module):
root_module = module.get_root()
## address.h (module 'network'): ns3::Address [class]
module.add_class('Address', import_from_module='ns.network')
## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration]
module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network')
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class]
module.add_class('AttributeConstructionList', import_from_module='ns.core')
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct]
module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList'])
## buffer.h (module 'network'): ns3::Buffer [class]
module.add_class('Buffer', import_from_module='ns.network')
## buffer.h (module 'network'): ns3::Buffer::Iterator [class]
module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer'])
## packet.h (module 'network'): ns3::ByteTagIterator [class]
module.add_class('ByteTagIterator', import_from_module='ns.network')
## packet.h (module 'network'): ns3::ByteTagIterator::Item [class]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList [class]
module.add_class('ByteTagList', import_from_module='ns.network')
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class]
module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator'])
## callback.h (module 'core'): ns3::CallbackBase [class]
module.add_class('CallbackBase', import_from_module='ns.core')
## event-id.h (module 'core'): ns3::EventId [class]
module.add_class('EventId', import_from_module='ns.core')
## hash.h (module 'core'): ns3::Hasher [class]
module.add_class('Hasher', import_from_module='ns.core')
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class]
module.add_class('Inet6SocketAddress', import_from_module='ns.network')
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class]
root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address'])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class]
module.add_class('InetSocketAddress', import_from_module='ns.network')
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class]
root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address'])
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
module.add_class('Ipv4Address', import_from_module='ns.network')
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class]
module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet')
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration]
module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet')
## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class]
module.add_class('Ipv4Mask', import_from_module='ns.network')
## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper [class]
module.add_class('Ipv4RoutingHelper', allow_subclassing=True, import_from_module='ns.internet')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
module.add_class('Ipv6Address', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class]
module.add_class('Ipv6Prefix', import_from_module='ns.network')
## mac48-address.h (module 'network'): ns3::Mac48Address [class]
module.add_class('Mac48Address', import_from_module='ns.network')
## mac48-address.h (module 'network'): ns3::Mac48Address [class]
root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address'])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class]
module.add_class('NetDeviceContainer', import_from_module='ns.network')
## node-container.h (module 'network'): ns3::NodeContainer [class]
module.add_class('NodeContainer', import_from_module='ns.network')
## node-list.h (module 'network'): ns3::NodeList [class]
module.add_class('NodeList', import_from_module='ns.network')
## object-base.h (module 'core'): ns3::ObjectBase [class]
module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core')
## object.h (module 'core'): ns3::ObjectDeleter [struct]
module.add_class('ObjectDeleter', import_from_module='ns.core')
## object-factory.h (module 'core'): ns3::ObjectFactory [class]
module.add_class('ObjectFactory', import_from_module='ns.core')
## packet-metadata.h (module 'network'): ns3::PacketMetadata [class]
module.add_class('PacketMetadata', import_from_module='ns.network')
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata'])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration]
module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network')
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class]
module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata'])
## packet.h (module 'network'): ns3::PacketTagIterator [class]
module.add_class('PacketTagIterator', import_from_module='ns.network')
## packet.h (module 'network'): ns3::PacketTagIterator::Item [class]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator'])
## packet-tag-list.h (module 'network'): ns3::PacketTagList [class]
module.add_class('PacketTagList', import_from_module='ns.network')
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct]
module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList'])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData_e [enumeration]
module.add_enum('TagData_e', ['MAX_SIZE'], outer_class=root_module['ns3::PacketTagList::TagData'], import_from_module='ns.network')
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simulator.h (module 'core'): ns3::Simulator [class]
module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core')
## tag.h (module 'network'): ns3::Tag [class]
module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase'])
## tag-buffer.h (module 'network'): ns3::TagBuffer [class]
module.add_class('TagBuffer', import_from_module='ns.network')
## nstime.h (module 'core'): ns3::TimeWithUnit [class]
module.add_class('TimeWithUnit', import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId [class]
module.add_class('TypeId', import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration]
module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct]
module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId'])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct]
module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId'])
## empty.h (module 'core'): ns3::empty [class]
module.add_class('empty', import_from_module='ns.core')
## int64x64-double.h (module 'core'): ns3::int64x64_t [class]
module.add_class('int64x64_t', import_from_module='ns.core')
## int64x64-double.h (module 'core'): ns3::int64x64_t::impl_type [enumeration]
module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core')
## 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')
## ipv4-nix-vector-helper.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorHelper [class]
module.add_class('Ipv4NixVectorHelper', parent=root_module['ns3::Ipv4RoutingHelper'])
## 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', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core')
## nstime.h (module 'core'): ns3::Time [class]
root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t'])
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class]
module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
## trailer.h (module 'network'): ns3::Trailer [class]
module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk'])
## 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'])
## channel.h (module 'network'): ns3::Channel [class]
module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object'])
## 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> >'])
## 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-address.h (module 'network'): ns3::Ipv4MaskChecker [class]
module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class]
module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute [class]
module.add_class('Ipv4MulticastRoute', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >'])
## ipv4-route.h (module 'internet'): ns3::Ipv4Route [class]
module.add_class('Ipv4Route', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >'])
## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol [class]
module.add_class('Ipv4RoutingProtocol', import_from_module='ns.internet', parent=root_module['ns3::Object'])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class]
module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class]
module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class]
module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class]
module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class]
module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class]
module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## net-device.h (module 'network'): ns3::NetDevice [class]
module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object'])
## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration]
module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network')
## nix-vector.h (module 'network'): ns3::NixVector [class]
module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
## node.h (module 'network'): ns3::Node [class]
module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object'])
## 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'])
## bridge-channel.h (module 'bridge'): ns3::BridgeChannel [class]
module.add_class('BridgeChannel', import_from_module='ns.bridge', parent=root_module['ns3::Channel'])
## bridge-net-device.h (module 'bridge'): ns3::BridgeNetDevice [class]
module.add_class('BridgeNetDevice', import_from_module='ns.bridge', parent=root_module['ns3::NetDevice'])
## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting [class]
module.add_class('Ipv4ListRouting', import_from_module='ns.internet', parent=root_module['ns3::Ipv4RoutingProtocol'])
## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorRouting [class]
module.add_class('Ipv4NixVectorRouting', parent=root_module['ns3::Ipv4RoutingProtocol'])
module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type=u'map')
typehandlers.add_type_alias(u'std::map< ns3::Ipv4Address, ns3::Ptr< ns3::NixVector >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::NixVector > > > >', u'ns3::NixMap_t')
typehandlers.add_type_alias(u'std::map< ns3::Ipv4Address, ns3::Ptr< ns3::NixVector >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::NixVector > > > >*', u'ns3::NixMap_t*')
typehandlers.add_type_alias(u'std::map< ns3::Ipv4Address, ns3::Ptr< ns3::NixVector >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::NixVector > > > >&', u'ns3::NixMap_t&')
typehandlers.add_type_alias(u'std::map< ns3::Ipv4Address, ns3::Ptr< ns3::Ipv4Route >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::Ipv4Route > > > >', u'ns3::Ipv4RouteMap_t')
typehandlers.add_type_alias(u'std::map< ns3::Ipv4Address, ns3::Ptr< ns3::Ipv4Route >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::Ipv4Route > > > >*', u'ns3::Ipv4RouteMap_t*')
typehandlers.add_type_alias(u'std::map< ns3::Ipv4Address, ns3::Ptr< ns3::Ipv4Route >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::Ipv4Route > > > >&', u'ns3::Ipv4RouteMap_t&')
## Register a nested module for the namespace FatalImpl
nested_module = module.add_cpp_namespace('FatalImpl')
register_types_ns3_FatalImpl(nested_module)
## Register a nested module for the namespace Hash
nested_module = module.add_cpp_namespace('Hash')
register_types_ns3_Hash(nested_module)
## Register a nested module for the namespace TracedValueCallback
nested_module = module.add_cpp_namespace('TracedValueCallback')
register_types_ns3_TracedValueCallback(nested_module)
def register_types_ns3_FatalImpl(module):
root_module = module.get_root()
def register_types_ns3_Hash(module):
root_module = module.get_root()
## hash-function.h (module 'core'): ns3::Hash::Implementation [class]
module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >'])
typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash32Function_ptr')
typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash32Function_ptr*')
typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash32Function_ptr&')
typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash64Function_ptr')
typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash64Function_ptr*')
typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash64Function_ptr&')
## Register a nested module for the namespace Function
nested_module = module.add_cpp_namespace('Function')
register_types_ns3_Hash_Function(nested_module)
def register_types_ns3_Hash_Function(module):
root_module = module.get_root()
## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class]
module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation'])
## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class]
module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation'])
## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class]
module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation'])
## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class]
module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation'])
def register_types_ns3_TracedValueCallback(module):
root_module = module.get_root()
typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *', u'ns3::TracedValueCallback::Time')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) **', u'ns3::TracedValueCallback::Time*')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *&', u'ns3::TracedValueCallback::Time&')
def register_methods(root_module):
register_Ns3Address_methods(root_module, root_module['ns3::Address'])
register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList'])
register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item'])
register_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_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address'])
register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress'])
register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask'])
register_Ns3Ipv4RoutingHelper_methods(root_module, root_module['ns3::Ipv4RoutingHelper'])
register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address'])
register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix'])
register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address'])
register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer'])
register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer'])
register_Ns3NodeList_methods(root_module, root_module['ns3::NodeList'])
register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase'])
register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter'])
register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory'])
register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata'])
register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item'])
register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator'])
register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator'])
register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item'])
register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList'])
register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData'])
register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >'])
register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator'])
register_Ns3Tag_methods(root_module, root_module['ns3::Tag'])
register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer'])
register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit'])
register_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_Ns3Ipv4NixVectorHelper_methods(root_module, root_module['ns3::Ipv4NixVectorHelper'])
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_Ns3Channel_methods(root_module, root_module['ns3::Channel'])
register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue'])
register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl'])
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_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker'])
register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue'])
register_Ns3Ipv4MulticastRoute_methods(root_module, root_module['ns3::Ipv4MulticastRoute'])
register_Ns3Ipv4Route_methods(root_module, root_module['ns3::Ipv4Route'])
register_Ns3Ipv4RoutingProtocol_methods(root_module, root_module['ns3::Ipv4RoutingProtocol'])
register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker'])
register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue'])
register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker'])
register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue'])
register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker'])
register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue'])
register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice'])
register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector'])
register_Ns3Node_methods(root_module, root_module['ns3::Node'])
register_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_Ns3BridgeChannel_methods(root_module, root_module['ns3::BridgeChannel'])
register_Ns3BridgeNetDevice_methods(root_module, root_module['ns3::BridgeNetDevice'])
register_Ns3Ipv4ListRouting_methods(root_module, root_module['ns3::Ipv4ListRouting'])
register_Ns3Ipv4NixVectorRouting_methods(root_module, root_module['ns3::Ipv4NixVectorRouting'])
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'): void ns3::Buffer::AddAtEnd(uint32_t end) [member function]
cls.add_method('AddAtEnd',
'void',
[param('uint32_t', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::Buffer const &', 'o')])
## buffer.h (module 'network'): void ns3::Buffer::AddAtStart(uint32_t start) [member function]
cls.add_method('AddAtStart',
'void',
[param('uint32_t', 'start')])
## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function]
cls.add_method('Begin',
'ns3::Buffer::Iterator',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function]
cls.add_method('CopyData',
'void',
[param('std::ostream *', 'os'), param('uint32_t', 'size')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function]
cls.add_method('CopyData',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')],
is_const=True)
## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function]
cls.add_method('CreateFragment',
'ns3::Buffer',
[param('uint32_t', 'start'), param('uint32_t', 'length')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function]
cls.add_method('End',
'ns3::Buffer::Iterator',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function]
cls.add_method('PeekData',
'uint8_t const *',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'start')])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3BufferIterator_methods(root_module, cls):
## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')])
## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor]
cls.add_constructor([])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function]
cls.add_method('CalculateIpChecksum',
'uint16_t',
[param('uint16_t', 'size')])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function]
cls.add_method('CalculateIpChecksum',
'uint16_t',
[param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function]
cls.add_method('GetDistanceFrom',
'uint32_t',
[param('ns3::Buffer::Iterator const &', 'o')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function]
cls.add_method('IsEnd',
'bool',
[],
is_const=True)
## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function]
cls.add_method('IsStart',
'bool',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function]
cls.add_method('Next',
'void',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function]
cls.add_method('Next',
'void',
[param('uint32_t', 'delta')])
## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function]
cls.add_method('PeekU8',
'uint8_t',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function]
cls.add_method('Prev',
'void',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function]
cls.add_method('Prev',
'void',
[param('uint32_t', 'delta')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function]
cls.add_method('ReadLsbtohU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function]
cls.add_method('ReadLsbtohU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function]
cls.add_method('ReadLsbtohU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function]
cls.add_method('ReadNtohU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function]
cls.add_method('ReadNtohU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function]
cls.add_method('ReadNtohU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function]
cls.add_method('Write',
'void',
[param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function]
cls.add_method('WriteHtolsbU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function]
cls.add_method('WriteHtolsbU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function]
cls.add_method('WriteHtolsbU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function]
cls.add_method('WriteHtonU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function]
cls.add_method('WriteHtonU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function]
cls.add_method('WriteHtonU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'data'), param('uint32_t', 'len')])
return
def register_Ns3ByteTagIterator_methods(root_module, cls):
## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')])
## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function]
cls.add_method('Next',
'ns3::ByteTagIterator::Item',
[])
return
def register_Ns3ByteTagIteratorItem_methods(root_module, cls):
## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')])
## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function]
cls.add_method('GetEnd',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function]
cls.add_method('GetStart',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function]
cls.add_method('GetTag',
'void',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
return
def register_Ns3ByteTagList_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor]
cls.add_constructor([])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList const &', 'o')])
## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function]
cls.add_method('Add',
'ns3::TagBuffer',
[param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function]
cls.add_method('Add',
'void',
[param('ns3::ByteTagList const &', 'o')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t appendOffset) [member function]
cls.add_method('AddAtEnd',
'void',
[param('int32_t', 'appendOffset')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t prependOffset) [member function]
cls.add_method('AddAtStart',
'void',
[param('int32_t', 'prependOffset')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Adjust(int32_t adjustment) [member function]
cls.add_method('Adjust',
'void',
[param('int32_t', 'adjustment')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function]
cls.add_method('Begin',
'ns3::ByteTagList::Iterator',
[param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')],
is_const=True)
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function]
cls.add_method('RemoveAll',
'void',
[])
return
def register_Ns3ByteTagListIterator_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')])
## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function]
cls.add_method('GetOffsetStart',
'uint32_t',
[],
is_const=True)
## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function]
cls.add_method('Next',
'ns3::ByteTagList::Iterator::Item',
[])
return
def register_Ns3ByteTagListIteratorItem_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor]
cls.add_constructor([param('ns3::TagBuffer', 'buf')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable]
cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable]
cls.add_instance_attribute('end', 'int32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable]
cls.add_instance_attribute('size', 'uint32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable]
cls.add_instance_attribute('start', 'int32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3CallbackBase_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')])
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function]
cls.add_method('GetImpl',
'ns3::Ptr< ns3::CallbackImplBase >',
[],
is_const=True)
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')],
visibility='protected')
return
def register_Ns3EventId_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('==')
## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EventId const &', 'arg0')])
## event-id.h (module 'core'): ns3::EventId::EventId() [constructor]
cls.add_constructor([])
## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')])
## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_const=True)
## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function]
cls.add_method('GetTs',
'uint64_t',
[],
is_const=True)
## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function]
cls.add_method('GetUid',
'uint32_t',
[],
is_const=True)
## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function]
cls.add_method('IsExpired',
'bool',
[],
is_const=True)
## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function]
cls.add_method('IsRunning',
'bool',
[],
is_const=True)
## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function]
cls.add_method('PeekEventImpl',
'ns3::EventImpl *',
[],
is_const=True)
return
def register_Ns3Hasher_methods(root_module, cls):
## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hasher const &', 'arg0')])
## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor]
cls.add_constructor([])
## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')])
## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')])
## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('std::string const', 's')])
## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')])
## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('std::string const', 's')])
## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function]
cls.add_method('clear',
'ns3::Hasher &',
[])
return
def register_Ns3Inet6SocketAddress_methods(root_module, cls):
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Inet6SocketAddress const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Inet6SocketAddress const &', 'arg0')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6, uint16_t port) [constructor]
cls.add_constructor([param('ns3::Ipv6Address', 'ipv6'), param('uint16_t', 'port')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6) [constructor]
cls.add_constructor([param('ns3::Ipv6Address', 'ipv6')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(uint16_t port) [constructor]
cls.add_constructor([param('uint16_t', 'port')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6, uint16_t port) [constructor]
cls.add_constructor([param('char const *', 'ipv6'), param('uint16_t', 'port')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6) [constructor]
cls.add_constructor([param('char const *', 'ipv6')])
## inet6-socket-address.h (module 'network'): static ns3::Inet6SocketAddress ns3::Inet6SocketAddress::ConvertFrom(ns3::Address const & addr) [member function]
cls.add_method('ConvertFrom',
'ns3::Inet6SocketAddress',
[param('ns3::Address const &', 'addr')],
is_static=True)
## inet6-socket-address.h (module 'network'): ns3::Ipv6Address ns3::Inet6SocketAddress::GetIpv6() const [member function]
cls.add_method('GetIpv6',
'ns3::Ipv6Address',
[],
is_const=True)
## inet6-socket-address.h (module 'network'): uint16_t ns3::Inet6SocketAddress::GetPort() const [member function]
cls.add_method('GetPort',
'uint16_t',
[],
is_const=True)
## inet6-socket-address.h (module 'network'): static bool ns3::Inet6SocketAddress::IsMatchingType(ns3::Address const & addr) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'addr')],
is_static=True)
## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetIpv6(ns3::Ipv6Address ipv6) [member function]
cls.add_method('SetIpv6',
'void',
[param('ns3::Ipv6Address', 'ipv6')])
## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetPort(uint16_t port) [member function]
cls.add_method('SetPort',
'void',
[param('uint16_t', 'port')])
return
def register_Ns3InetSocketAddress_methods(root_module, cls):
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::InetSocketAddress const & arg0) [copy constructor]
cls.add_constructor([param('ns3::InetSocketAddress const &', 'arg0')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4, uint16_t port) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'ipv4'), param('uint16_t', 'port')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'ipv4')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(uint16_t port) [constructor]
cls.add_constructor([param('uint16_t', 'port')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4, uint16_t port) [constructor]
cls.add_constructor([param('char const *', 'ipv4'), param('uint16_t', 'port')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4) [constructor]
cls.add_constructor([param('char const *', 'ipv4')])
## inet-socket-address.h (module 'network'): static ns3::InetSocketAddress ns3::InetSocketAddress::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::InetSocketAddress',
[param('ns3::Address const &', 'address')],
is_static=True)
## inet-socket-address.h (module 'network'): ns3::Ipv4Address ns3::InetSocketAddress::GetIpv4() const [member function]
cls.add_method('GetIpv4',
'ns3::Ipv4Address',
[],
is_const=True)
## inet-socket-address.h (module 'network'): uint16_t ns3::InetSocketAddress::GetPort() const [member function]
cls.add_method('GetPort',
'uint16_t',
[],
is_const=True)
## inet-socket-address.h (module 'network'): 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_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_Ns3Ipv4RoutingHelper_methods(root_module, cls):
## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper::Ipv4RoutingHelper() [constructor]
cls.add_constructor([])
## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper::Ipv4RoutingHelper(ns3::Ipv4RoutingHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4RoutingHelper const &', 'arg0')])
## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper * ns3::Ipv4RoutingHelper::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ipv4RoutingHelper *',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4-routing-helper.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4RoutingHelper::Create(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::Ipv4RoutingProtocol >',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheAllAt(ns3::Time printTime, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function]
cls.add_method('PrintNeighborCacheAllAt',
'void',
[param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_static=True)
## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheAllEvery(ns3::Time printInterval, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function]
cls.add_method('PrintNeighborCacheAllEvery',
'void',
[param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_static=True)
## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheAt(ns3::Time printTime, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function]
cls.add_method('PrintNeighborCacheAt',
'void',
[param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_static=True)
## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheEvery(ns3::Time printInterval, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function]
cls.add_method('PrintNeighborCacheEvery',
'void',
[param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_static=True)
## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableAllAt(ns3::Time printTime, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function]
cls.add_method('PrintRoutingTableAllAt',
'void',
[param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_static=True)
## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableAllEvery(ns3::Time printInterval, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function]
cls.add_method('PrintRoutingTableAllEvery',
'void',
[param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_static=True)
## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableAt(ns3::Time printTime, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function]
cls.add_method('PrintRoutingTableAt',
'void',
[param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_static=True)
## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableEvery(ns3::Time printInterval, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function]
cls.add_method('PrintRoutingTableEvery',
'void',
[param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_static=True)
return
def register_Ns3Ipv6Address_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor]
cls.add_constructor([param('char const *', 'address')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor]
cls.add_constructor([param('uint8_t *', 'address')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor]
cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function]
cls.add_method('CombinePrefix',
'ns3::Ipv6Address',
[param('ns3::Ipv6Prefix const &', 'prefix')])
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Ipv6Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function]
cls.add_method('Deserialize',
'ns3::Ipv6Address',
[param('uint8_t const *', 'buf')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function]
cls.add_method('GetAllHostsMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function]
cls.add_method('GetAllNodesMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function]
cls.add_method('GetAllRoutersMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function]
cls.add_method('GetAny',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function]
cls.add_method('GetBytes',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function]
cls.add_method('GetIpv4MappedAddress',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function]
cls.add_method('IsAllHostsMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function]
cls.add_method('IsAllNodesMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function]
cls.add_method('IsAllRoutersMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function]
cls.add_method('IsAny',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function]
cls.add_method('IsDocumentation',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv6Address const &', 'other')],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() const [member function]
cls.add_method('IsIpv4MappedAddress',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function]
cls.add_method('IsLinkLocal',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function]
cls.add_method('IsLinkLocalMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function]
cls.add_method('IsLocalhost',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function]
cls.add_method('IsSolicitedMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function]
cls.add_method('MakeAutoconfiguredAddress',
'ns3::Ipv6Address',
[param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function]
cls.add_method('MakeAutoconfiguredAddress',
'ns3::Ipv6Address',
[param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function]
cls.add_method('MakeAutoconfiguredAddress',
'ns3::Ipv6Address',
[param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function]
cls.add_method('MakeAutoconfiguredLinkLocalAddress',
'ns3::Ipv6Address',
[param('ns3::Mac16Address', 'mac')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function]
cls.add_method('MakeAutoconfiguredLinkLocalAddress',
'ns3::Ipv6Address',
[param('ns3::Mac48Address', 'mac')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function]
cls.add_method('MakeAutoconfiguredLinkLocalAddress',
'ns3::Ipv6Address',
[param('ns3::Mac64Address', 'mac')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function]
cls.add_method('MakeIpv4MappedAddress',
'ns3::Ipv6Address',
[param('ns3::Ipv4Address', 'addr')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function]
cls.add_method('MakeSolicitedAddress',
'ns3::Ipv6Address',
[param('ns3::Ipv6Address', 'addr')],
is_static=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function]
cls.add_method('Serialize',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function]
cls.add_method('Set',
'void',
[param('char const *', 'address')])
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function]
cls.add_method('Set',
'void',
[param('uint8_t *', 'address')])
return
def register_Ns3Ipv6Prefix_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor]
cls.add_constructor([param('uint8_t *', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor]
cls.add_constructor([param('char const *', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor]
cls.add_constructor([param('uint8_t', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')])
## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function]
cls.add_method('GetBytes',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function]
cls.add_method('GetPrefixLength',
'uint8_t',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv6Prefix const &', 'other')],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function]
cls.add_method('IsMatch',
'bool',
[param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
return
def register_Ns3Mac48Address_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')])
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor]
cls.add_constructor([])
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor]
cls.add_constructor([param('char const *', 'str')])
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function]
cls.add_method('Allocate',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Mac48Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function]
cls.add_method('CopyFrom',
'void',
[param('uint8_t const *', 'buffer')])
## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function]
cls.add_method('CopyTo',
'void',
[param('uint8_t *', 'buffer')],
is_const=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function]
cls.add_method('GetMulticast',
'ns3::Mac48Address',
[param('ns3::Ipv4Address', 'address')],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function]
cls.add_method('GetMulticast',
'ns3::Mac48Address',
[param('ns3::Ipv6Address', 'address')],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function]
cls.add_method('GetMulticast6Prefix',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function]
cls.add_method('GetMulticastPrefix',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True)
## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function]
cls.add_method('IsGroup',
'bool',
[],
is_const=True)
## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
return
def register_Ns3NetDeviceContainer_methods(root_module, cls):
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor]
cls.add_constructor([])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor]
cls.add_constructor([param('std::string', 'devName')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor]
cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::NetDeviceContainer', 'other')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'deviceName')])
## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >',
[],
is_const=True)
## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >',
[],
is_const=True)
## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_const=True)
## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
return
def register_Ns3NodeContainer_methods(root_module, cls):
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor]
cls.add_constructor([])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor]
cls.add_constructor([param('std::string', 'nodeName')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::NodeContainer', 'other')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'nodeName')])
## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_const=True)
## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function]
cls.add_method('Create',
'void',
[param('uint32_t', 'n')])
## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function]
cls.add_method('Create',
'void',
[param('uint32_t', 'n'), param('uint32_t', 'systemId')])
## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_const=True)
## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::Node >',
[param('uint32_t', 'i')],
is_const=True)
## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function]
cls.add_method('GetGlobal',
'ns3::NodeContainer',
[],
is_static=True)
## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
return
def register_Ns3NodeList_methods(root_module, cls):
## node-list.h (module 'network'): ns3::NodeList::NodeList() [constructor]
cls.add_constructor([])
## node-list.h (module 'network'): ns3::NodeList::NodeList(ns3::NodeList const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NodeList const &', 'arg0')])
## node-list.h (module 'network'): static uint32_t ns3::NodeList::Add(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('Add',
'uint32_t',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_static=True)
## node-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeList::Begin() [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_static=True)
## node-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeList::End() [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_static=True)
## node-list.h (module 'network'): static uint32_t ns3::NodeList::GetNNodes() [member function]
cls.add_method('GetNNodes',
'uint32_t',
[],
is_static=True)
## node-list.h (module 'network'): static ns3::Ptr<ns3::Node> ns3::NodeList::GetNode(uint32_t n) [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[param('uint32_t', 'n')],
is_static=True)
return
def register_Ns3ObjectBase_methods(root_module, cls):
## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor]
cls.add_constructor([])
## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')])
## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function]
cls.add_method('GetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'value')],
is_const=True)
## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & value) const [member function]
cls.add_method('GetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'value')],
is_const=True)
## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceConnect',
'bool',
[param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceConnectWithoutContext',
'bool',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceDisconnect',
'bool',
[param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceDisconnectWithoutContext',
'bool',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function]
cls.add_method('ConstructSelf',
'void',
[param('ns3::AttributeConstructionList const &', 'attributes')],
visibility='protected')
## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function]
cls.add_method('NotifyConstructionCompleted',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ObjectDeleter_methods(root_module, cls):
## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor]
cls.add_constructor([])
## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')])
## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function]
cls.add_method('Delete',
'void',
[param('ns3::Object *', 'object')],
is_static=True)
return
def register_Ns3ObjectFactory_methods(root_module, cls):
cls.add_output_stream_operator()
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')])
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor]
cls.add_constructor([param('std::string', 'typeId')])
## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::Object >',
[],
is_const=True)
## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('ns3::TypeId', 'tid')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('char const *', 'tid')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('std::string', 'tid')])
return
def register_Ns3PacketMetadata_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor]
cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata const &', 'o')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::PacketMetadata const &', 'o')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function]
cls.add_method('AddHeader',
'void',
[param('ns3::Header const &', 'header'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function]
cls.add_method('AddPaddingAtEnd',
'void',
[param('uint32_t', 'end')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function]
cls.add_method('AddTrailer',
'void',
[param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function]
cls.add_method('BeginItem',
'ns3::PacketMetadata::ItemIterator',
[param('ns3::Buffer', 'buffer')],
is_const=True)
## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function]
cls.add_method('CreateFragment',
'ns3::PacketMetadata',
[param('uint32_t', 'start'), param('uint32_t', 'end')],
is_const=True)
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function]
cls.add_method('Enable',
'void',
[],
is_static=True)
## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function]
cls.add_method('EnableChecking',
'void',
[],
is_static=True)
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function]
cls.add_method('GetUid',
'uint64_t',
[],
is_const=True)
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'end')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'start')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function]
cls.add_method('RemoveHeader',
'void',
[param('ns3::Header const &', 'header'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function]
cls.add_method('RemoveTrailer',
'void',
[param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3PacketMetadataItem_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor]
cls.add_constructor([])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable]
cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable]
cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable]
cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable]
cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable]
cls.add_instance_attribute('isFragment', 'bool', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3PacketMetadataItemIterator_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor]
cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')])
## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketMetadata::Item',
[])
return
def register_Ns3PacketTagIterator_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')])
## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketTagIterator::Item',
[])
return
def register_Ns3PacketTagIteratorItem_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')])
## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function]
cls.add_method('GetTag',
'void',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
return
def register_Ns3PacketTagList_methods(root_module, cls):
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor]
cls.add_constructor([])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketTagList const &', 'o')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function]
cls.add_method('Add',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function]
cls.add_method('Head',
'ns3::PacketTagList::TagData const *',
[],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function]
cls.add_method('Peek',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function]
cls.add_method('Remove',
'bool',
[param('ns3::Tag &', 'tag')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function]
cls.add_method('RemoveAll',
'void',
[])
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function]
cls.add_method('Replace',
'bool',
[param('ns3::Tag &', 'tag')])
return
def register_Ns3PacketTagListTagData_methods(root_module, cls):
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor]
cls.add_constructor([])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable]
cls.add_instance_attribute('count', 'uint32_t', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable]
cls.add_instance_attribute('data', 'uint8_t [ 21 ]', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable]
cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3Simulator_methods(root_module, cls):
## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Simulator const &', 'arg0')])
## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function]
cls.add_method('Cancel',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function]
cls.add_method('Destroy',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function]
cls.add_method('GetDelayLeft',
'ns3::Time',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function]
cls.add_method('GetImplementation',
'ns3::Ptr< ns3::SimulatorImpl >',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function]
cls.add_method('GetMaximumSimulationTime',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function]
cls.add_method('IsExpired',
'bool',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function]
cls.add_method('IsFinished',
'bool',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function]
cls.add_method('Now',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function]
cls.add_method('Remove',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function]
cls.add_method('SetImplementation',
'void',
[param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function]
cls.add_method('SetScheduler',
'void',
[param('ns3::ObjectFactory', 'schedulerFactory')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function]
cls.add_method('Stop',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & delay) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time const &', 'delay')],
is_static=True)
return
def register_Ns3Tag_methods(root_module, cls):
## tag.h (module 'network'): ns3::Tag::Tag() [constructor]
cls.add_constructor([])
## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Tag const &', 'arg0')])
## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_virtual=True)
## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3TagBuffer_methods(root_module, cls):
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')])
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor]
cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function]
cls.add_method('CopyFrom',
'void',
[param('ns3::TagBuffer', 'o')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function]
cls.add_method('ReadDouble',
'double',
[])
## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function]
cls.add_method('TrimAtEnd',
'void',
[param('uint32_t', 'trim')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function]
cls.add_method('WriteDouble',
'void',
[param('double', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'v')])
return
def register_Ns3TimeWithUnit_methods(root_module, cls):
cls.add_output_stream_operator()
## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::TimeWithUnit const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimeWithUnit const &', 'arg0')])
## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::Time const time, ns3::Time::Unit const unit) [constructor]
cls.add_constructor([param('ns3::Time const', 'time'), param('ns3::Time::Unit const', 'unit')])
return
def register_Ns3TypeId_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor]
cls.add_constructor([param('char const *', 'name')])
## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor]
cls.add_constructor([param('ns3::TypeId const &', 'o')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('AddAttribute',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('AddAttribute',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function]
cls.add_method('AddTraceSource',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')],
deprecated=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor, std::string callback) [member function]
cls.add_method('AddTraceSource',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor'), param('std::string', 'callback')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function]
cls.add_method('GetAttribute',
'ns3::TypeId::AttributeInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function]
cls.add_method('GetAttributeFullName',
'std::string',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function]
cls.add_method('GetAttributeN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function]
cls.add_method('GetConstructor',
'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function]
cls.add_method('GetGroupName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function]
cls.add_method('GetHash',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function]
cls.add_method('GetName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function]
cls.add_method('GetParent',
'ns3::TypeId',
[],
is_const=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function]
cls.add_method('GetRegistered',
'ns3::TypeId',
[param('uint32_t', 'i')],
is_static=True)
## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function]
cls.add_method('GetRegisteredN',
'uint32_t',
[],
is_static=True)
## type-id.h (module 'core'): std::size_t ns3::TypeId::GetSize() const [member function]
cls.add_method('GetSize',
'std::size_t',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function]
cls.add_method('GetTraceSource',
'ns3::TypeId::TraceSourceInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function]
cls.add_method('GetTraceSourceN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function]
cls.add_method('GetUid',
'uint16_t',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function]
cls.add_method('HasConstructor',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function]
cls.add_method('HasParent',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function]
cls.add_method('HideFromDocumentation',
'ns3::TypeId',
[])
## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function]
cls.add_method('IsChildOf',
'bool',
[param('ns3::TypeId', 'other')],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function]
cls.add_method('LookupAttributeByName',
'bool',
[param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)],
is_const=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function]
cls.add_method('LookupByHash',
'ns3::TypeId',
[param('uint32_t', 'hash')],
is_static=True)
## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function]
cls.add_method('LookupByHashFailSafe',
'bool',
[param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')],
is_static=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function]
cls.add_method('LookupByName',
'ns3::TypeId',
[param('std::string', 'name')],
is_static=True)
## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function]
cls.add_method('LookupTraceSourceByName',
'ns3::Ptr< ns3::TraceSourceAccessor const >',
[param('std::string', 'name')],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function]
cls.add_method('MustHideFromDocumentation',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function]
cls.add_method('SetAttributeInitialValue',
'bool',
[param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function]
cls.add_method('SetGroupName',
'ns3::TypeId',
[param('std::string', 'groupName')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function]
cls.add_method('SetParent',
'ns3::TypeId',
[param('ns3::TypeId', 'tid')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetSize(std::size_t size) [member function]
cls.add_method('SetSize',
'ns3::TypeId',
[param('std::size_t', 'size')])
## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function]
cls.add_method('SetUid',
'void',
[param('uint16_t', 'tid')])
return
def register_Ns3TypeIdAttributeInformation_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable]
cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable]
cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable]
cls.add_instance_attribute('flags', 'uint32_t', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable]
cls.add_instance_attribute('help', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable]
cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable]
cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False)
return
def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable]
cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::callback [variable]
cls.add_instance_attribute('callback', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable]
cls.add_instance_attribute('help', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
return
def register_Ns3Empty_methods(root_module, cls):
## empty.h (module 'core'): ns3::empty::empty() [constructor]
cls.add_constructor([])
## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor]
cls.add_constructor([param('ns3::empty const &', 'arg0')])
return
def register_Ns3Int64x64_t_methods(root_module, cls):
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right'))
cls.add_unary_numeric_operator('-')
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', u'right'))
cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', u'right'))
cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', u'right'))
cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', u'right'))
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>=')
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor]
cls.add_constructor([])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor]
cls.add_constructor([param('double', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long double v) [constructor]
cls.add_constructor([param('long double', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor]
cls.add_constructor([param('long int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor]
cls.add_constructor([param('long long int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor]
cls.add_constructor([param('unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor]
cls.add_constructor([param('long unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor]
cls.add_constructor([param('long long unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor]
cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'o')])
## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function]
cls.add_method('GetDouble',
'double',
[],
is_const=True)
## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function]
cls.add_method('GetHigh',
'int64_t',
[],
is_const=True)
## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function]
cls.add_method('GetLow',
'uint64_t',
[],
is_const=True)
## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function]
cls.add_method('Invert',
'ns3::int64x64_t',
[param('uint64_t', 'v')],
is_static=True)
## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function]
cls.add_method('MulByInvert',
'void',
[param('ns3::int64x64_t const &', 'o')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::implementation [variable]
cls.add_static_attribute('implementation', 'ns3::int64x64_t::impl_type const', is_const=True)
return
def register_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_Ns3Ipv4NixVectorHelper_methods(root_module, cls):
## ipv4-nix-vector-helper.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorHelper::Ipv4NixVectorHelper() [constructor]
cls.add_constructor([])
## ipv4-nix-vector-helper.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorHelper::Ipv4NixVectorHelper(ns3::Ipv4NixVectorHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4NixVectorHelper const &', 'arg0')])
## ipv4-nix-vector-helper.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorHelper * ns3::Ipv4NixVectorHelper::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ipv4NixVectorHelper *',
[],
is_const=True, is_virtual=True)
## ipv4-nix-vector-helper.h (module 'nix-vector-routing'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4NixVectorHelper::Create(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::Ipv4RoutingProtocol >',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True, is_virtual=True)
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('int64_t const &', u'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', u'right'))
cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', u'right'))
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>=')
## nstime.h (module 'core'): ns3::Time::Time() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor]
cls.add_constructor([param('ns3::Time const &', 'o')])
## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor]
cls.add_constructor([param('double', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor]
cls.add_constructor([param('long int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor]
cls.add_constructor([param('long long int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor]
cls.add_constructor([param('unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor]
cls.add_constructor([param('long unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor]
cls.add_constructor([param('long long unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & v) [constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor]
cls.add_constructor([param('std::string const &', 's')])
## nstime.h (module 'core'): ns3::TimeWithUnit ns3::Time::As(ns3::Time::Unit const unit) const [member function]
cls.add_method('As',
'ns3::TimeWithUnit',
[param('ns3::Time::Unit const', 'unit')],
is_const=True)
## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function]
cls.add_method('Compare',
'int',
[param('ns3::Time const &', 'o')],
is_const=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function]
cls.add_method('From',
'ns3::Time',
[param('ns3::int64x64_t const &', 'value')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value, ns3::Time::Unit unit) [member function]
cls.add_method('From',
'ns3::Time',
[param('ns3::int64x64_t const &', 'value'), param('ns3::Time::Unit', 'unit')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit unit) [member function]
cls.add_method('FromDouble',
'ns3::Time',
[param('double', 'value'), param('ns3::Time::Unit', 'unit')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit unit) [member function]
cls.add_method('FromInteger',
'ns3::Time',
[param('uint64_t', 'value'), param('ns3::Time::Unit', 'unit')],
is_static=True)
## nstime.h (module 'core'): double ns3::Time::GetDays() const [member function]
cls.add_method('GetDays',
'double',
[],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function]
cls.add_method('GetDouble',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function]
cls.add_method('GetFemtoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::GetHours() const [member function]
cls.add_method('GetHours',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function]
cls.add_method('GetInteger',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function]
cls.add_method('GetMicroSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function]
cls.add_method('GetMilliSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::GetMinutes() const [member function]
cls.add_method('GetMinutes',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function]
cls.add_method('GetNanoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function]
cls.add_method('GetPicoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function]
cls.add_method('GetResolution',
'ns3::Time::Unit',
[],
is_static=True)
## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function]
cls.add_method('GetSeconds',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function]
cls.add_method('GetTimeStep',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::GetYears() const [member function]
cls.add_method('GetYears',
'double',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function]
cls.add_method('IsNegative',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function]
cls.add_method('IsPositive',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function]
cls.add_method('IsStrictlyNegative',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function]
cls.add_method('IsStrictlyPositive',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function]
cls.add_method('IsZero',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function]
cls.add_method('Max',
'ns3::Time',
[],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function]
cls.add_method('Min',
'ns3::Time',
[],
is_static=True)
## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function]
cls.add_method('SetResolution',
'void',
[param('ns3::Time::Unit', 'resolution')],
is_static=True)
## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function]
cls.add_method('StaticInit',
'bool',
[],
is_static=True)
## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit unit) const [member function]
cls.add_method('To',
'ns3::int64x64_t',
[param('ns3::Time::Unit', 'unit')],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit unit) const [member function]
cls.add_method('ToDouble',
'double',
[param('ns3::Time::Unit', 'unit')],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit unit) const [member function]
cls.add_method('ToInteger',
'int64_t',
[param('ns3::Time::Unit', 'unit')],
is_const=True)
return
def register_Ns3TraceSourceAccessor_methods(root_module, cls):
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')])
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor]
cls.add_constructor([])
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function]
cls.add_method('Connect',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function]
cls.add_method('ConnectWithoutContext',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function]
cls.add_method('Disconnect',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function]
cls.add_method('DisconnectWithoutContext',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_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'): std::string ns3::CallbackImplBase::GetTypeid() const [member function]
cls.add_method('GetTypeid',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## callback.h (module 'core'): static std::string ns3::CallbackImplBase::Demangle(std::string const & mangled) [member function]
cls.add_method('Demangle',
'std::string',
[param('std::string const &', 'mangled')],
is_static=True, visibility='protected')
return
def register_Ns3CallbackValue_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor]
cls.add_constructor([param('ns3::CallbackBase const &', 'base')])
## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function]
cls.add_method('Set',
'void',
[param('ns3::CallbackBase', 'base')])
return
def register_Ns3Channel_methods(root_module, cls):
## channel.h (module 'network'): ns3::Channel::Channel(ns3::Channel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Channel const &', 'arg0')])
## channel.h (module 'network'): ns3::Channel::Channel() [constructor]
cls.add_constructor([])
## channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Channel::GetDevice(uint32_t i) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## channel.h (module 'network'): uint32_t ns3::Channel::GetId() const [member function]
cls.add_method('GetId',
'uint32_t',
[],
is_const=True)
## channel.h (module 'network'): uint32_t ns3::Channel::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## channel.h (module 'network'): static ns3::TypeId ns3::Channel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3EmptyAttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, visibility='private', is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
visibility='private', is_virtual=True)
## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, visibility='private', is_virtual=True)
return
def register_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_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_Ns3Ipv4MaskChecker_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')])
return
def register_Ns3Ipv4MaskValue_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor]
cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')])
## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv4Mask',
[],
is_const=True)
## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv4Mask const &', 'value')])
return
def register_Ns3Ipv4MulticastRoute_methods(root_module, cls):
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute(ns3::Ipv4MulticastRoute const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MulticastRoute const &', 'arg0')])
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute() [constructor]
cls.add_constructor([])
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetGroup() const [member function]
cls.add_method('GetGroup',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetOrigin() const [member function]
cls.add_method('GetOrigin',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): std::map<unsigned int, unsigned int, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, unsigned int> > > ns3::Ipv4MulticastRoute::GetOutputTtlMap() const [member function]
cls.add_method('GetOutputTtlMap',
'std::map< unsigned int, unsigned int >',
[],
is_const=True)
## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetParent() const [member function]
cls.add_method('GetParent',
'uint32_t',
[],
is_const=True)
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetGroup(ns3::Ipv4Address const group) [member function]
cls.add_method('SetGroup',
'void',
[param('ns3::Ipv4Address const', 'group')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOrigin(ns3::Ipv4Address const origin) [member function]
cls.add_method('SetOrigin',
'void',
[param('ns3::Ipv4Address const', 'origin')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOutputTtl(uint32_t oif, uint32_t ttl) [member function]
cls.add_method('SetOutputTtl',
'void',
[param('uint32_t', 'oif'), param('uint32_t', 'ttl')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetParent(uint32_t iif) [member function]
cls.add_method('SetParent',
'void',
[param('uint32_t', 'iif')])
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_INTERFACES [variable]
cls.add_static_attribute('MAX_INTERFACES', 'uint32_t const', is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_TTL [variable]
cls.add_static_attribute('MAX_TTL', 'uint32_t const', is_const=True)
return
def register_Ns3Ipv4Route_methods(root_module, cls):
cls.add_output_stream_operator()
## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route(ns3::Ipv4Route const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Route const &', 'arg0')])
## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route() [constructor]
cls.add_constructor([])
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetDestination() const [member function]
cls.add_method('GetDestination',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetGateway() const [member function]
cls.add_method('GetGateway',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Route::GetOutputDevice() const [member function]
cls.add_method('GetOutputDevice',
'ns3::Ptr< ns3::NetDevice >',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetSource() const [member function]
cls.add_method('GetSource',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetDestination(ns3::Ipv4Address dest) [member function]
cls.add_method('SetDestination',
'void',
[param('ns3::Ipv4Address', 'dest')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetGateway(ns3::Ipv4Address gw) [member function]
cls.add_method('SetGateway',
'void',
[param('ns3::Ipv4Address', 'gw')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetOutputDevice(ns3::Ptr<ns3::NetDevice> outputDevice) [member function]
cls.add_method('SetOutputDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'outputDevice')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetSource(ns3::Ipv4Address src) [member function]
cls.add_method('SetSource',
'void',
[param('ns3::Ipv4Address', 'src')])
return
def register_Ns3Ipv4RoutingProtocol_methods(root_module, cls):
## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol() [constructor]
cls.add_constructor([])
## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol(ns3::Ipv4RoutingProtocol const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4RoutingProtocol const &', 'arg0')])
## ipv4-routing-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4RoutingProtocol::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyAddAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceDown',
'void',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceUp',
'void',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyRemoveAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function]
cls.add_method('PrintRoutingTable',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): bool ns3::Ipv4RoutingProtocol::RouteInput(ns3::Ptr<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_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_Ns3Mac48AddressChecker_methods(root_module, cls):
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor]
cls.add_constructor([])
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')])
return
def register_Ns3Mac48AddressValue_methods(root_module, cls):
## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue() [constructor]
cls.add_constructor([])
## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')])
## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor]
cls.add_constructor([param('ns3::Mac48Address const &', 'value')])
## mac48-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac48AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## mac48-address.h (module 'network'): bool ns3::Mac48AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## mac48-address.h (module 'network'): ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Mac48Address',
[],
is_const=True)
## mac48-address.h (module 'network'): std::string ns3::Mac48AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## mac48-address.h (module 'network'): void ns3::Mac48AddressValue::Set(ns3::Mac48Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Mac48Address const &', 'value')])
return
def register_Ns3NetDevice_methods(root_module, cls):
## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor]
cls.add_constructor([])
## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDevice const &', 'arg0')])
## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function]
cls.add_method('AddLinkChangeCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Send',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('SendFrom',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_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_Ns3Node_methods(root_module, cls):
## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Node const &', 'arg0')])
## node.h (module 'network'): ns3::Node::Node() [constructor]
cls.add_constructor([])
## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor]
cls.add_constructor([param('uint32_t', 'systemId')])
## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function]
cls.add_method('AddApplication',
'uint32_t',
[param('ns3::Ptr< ns3::Application >', 'application')])
## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('AddDevice',
'uint32_t',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function]
cls.add_method('ChecksumEnabled',
'bool',
[],
is_static=True)
## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function]
cls.add_method('GetApplication',
'ns3::Ptr< ns3::Application >',
[param('uint32_t', 'index')],
is_const=True)
## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'index')],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function]
cls.add_method('GetId',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function]
cls.add_method('GetNApplications',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function]
cls.add_method('RegisterDeviceAdditionListener',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')])
## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function]
cls.add_method('RegisterProtocolHandler',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')])
## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function]
cls.add_method('UnregisterDeviceAdditionListener',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')])
## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function]
cls.add_method('UnregisterProtocolHandler',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')])
## node.h (module 'network'): void ns3::Node::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## node.h (module 'network'): void ns3::Node::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_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'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function]
cls.add_method('PeekHeader',
'uint32_t',
[param('ns3::Header &', 'header')],
is_const=True)
## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function]
cls.add_method('PeekPacketTag',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function]
cls.add_method('PeekTrailer',
'uint32_t',
[param('ns3::Trailer &', 'trailer')])
## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function]
cls.add_method('PrintByteTags',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function]
cls.add_method('PrintPacketTags',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function]
cls.add_method('RemoveAllByteTags',
'void',
[])
## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function]
cls.add_method('RemoveAllPacketTags',
'void',
[])
## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function]
cls.add_method('RemoveHeader',
'uint32_t',
[param('ns3::Header &', 'header')])
## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function]
cls.add_method('RemovePacketTag',
'bool',
[param('ns3::Tag &', 'tag')])
## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function]
cls.add_method('RemoveTrailer',
'uint32_t',
[param('ns3::Trailer &', 'trailer')])
## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function]
cls.add_method('ReplacePacketTag',
'bool',
[param('ns3::Tag &', 'tag')])
## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> nixVector) [member function]
cls.add_method('SetNixVector',
'void',
[param('ns3::Ptr< ns3::NixVector >', 'nixVector')])
## packet.h (module 'network'): std::string ns3::Packet::ToString() const [member function]
cls.add_method('ToString',
'std::string',
[],
is_const=True)
return
def register_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_Ns3BridgeChannel_methods(root_module, cls):
## bridge-channel.h (module 'bridge'): static ns3::TypeId ns3::BridgeChannel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## bridge-channel.h (module 'bridge'): ns3::BridgeChannel::BridgeChannel() [constructor]
cls.add_constructor([])
## bridge-channel.h (module 'bridge'): void ns3::BridgeChannel::AddChannel(ns3::Ptr<ns3::Channel> bridgedChannel) [member function]
cls.add_method('AddChannel',
'void',
[param('ns3::Ptr< ns3::Channel >', 'bridgedChannel')])
## bridge-channel.h (module 'bridge'): uint32_t ns3::BridgeChannel::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True, is_virtual=True)
## bridge-channel.h (module 'bridge'): ns3::Ptr<ns3::NetDevice> ns3::BridgeChannel::GetDevice(uint32_t i) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_const=True, is_virtual=True)
return
def register_Ns3BridgeNetDevice_methods(root_module, cls):
## bridge-net-device.h (module 'bridge'): ns3::BridgeNetDevice::BridgeNetDevice() [constructor]
cls.add_constructor([])
## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::AddBridgePort(ns3::Ptr<ns3::NetDevice> bridgePort) [member function]
cls.add_method('AddBridgePort',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'bridgePort')])
## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::AddLinkChangeCallback(ns3::Callback<void,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function]
cls.add_method('AddLinkChangeCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_virtual=True)
## bridge-net-device.h (module 'bridge'): ns3::Address ns3::BridgeNetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## bridge-net-device.h (module 'bridge'): ns3::Ptr<ns3::NetDevice> ns3::BridgeNetDevice::GetBridgePort(uint32_t n) const [member function]
cls.add_method('GetBridgePort',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'n')],
is_const=True)
## bridge-net-device.h (module 'bridge'): ns3::Address ns3::BridgeNetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## bridge-net-device.h (module 'bridge'): ns3::Ptr<ns3::Channel> ns3::BridgeNetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_const=True, is_virtual=True)
## bridge-net-device.h (module 'bridge'): uint32_t ns3::BridgeNetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_const=True, is_virtual=True)
## bridge-net-device.h (module 'bridge'): uint16_t ns3::BridgeNetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_const=True, is_virtual=True)
## bridge-net-device.h (module 'bridge'): ns3::Address ns3::BridgeNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_const=True, is_virtual=True)
## bridge-net-device.h (module 'bridge'): ns3::Address ns3::BridgeNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_const=True, is_virtual=True)
## bridge-net-device.h (module 'bridge'): uint32_t ns3::BridgeNetDevice::GetNBridgePorts() const [member function]
cls.add_method('GetNBridgePorts',
'uint32_t',
[],
is_const=True)
## bridge-net-device.h (module 'bridge'): ns3::Ptr<ns3::Node> ns3::BridgeNetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True, is_virtual=True)
## bridge-net-device.h (module 'bridge'): static ns3::TypeId ns3::BridgeNetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_const=True, is_virtual=True)
## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True, is_virtual=True)
## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_const=True, is_virtual=True)
## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True, is_virtual=True)
## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_const=True, is_virtual=True)
## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_const=True, is_virtual=True)
## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Send',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('SendFrom',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_virtual=True)
## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_virtual=True)
## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_virtual=True)
## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_virtual=True)
## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_const=True, is_virtual=True)
## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::ForwardBroadcast(ns3::Ptr<ns3::NetDevice> incomingPort, ns3::Ptr<const ns3::Packet> packet, uint16_t protocol, ns3::Mac48Address src, ns3::Mac48Address dst) [member function]
cls.add_method('ForwardBroadcast',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'incomingPort'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'src'), param('ns3::Mac48Address', 'dst')],
visibility='protected')
## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::ForwardUnicast(ns3::Ptr<ns3::NetDevice> incomingPort, ns3::Ptr<const ns3::Packet> packet, uint16_t protocol, ns3::Mac48Address src, ns3::Mac48Address dst) [member function]
cls.add_method('ForwardUnicast',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'incomingPort'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'src'), param('ns3::Mac48Address', 'dst')],
visibility='protected')
## bridge-net-device.h (module 'bridge'): ns3::Ptr<ns3::NetDevice> ns3::BridgeNetDevice::GetLearnedState(ns3::Mac48Address source) [member function]
cls.add_method('GetLearnedState',
'ns3::Ptr< ns3::NetDevice >',
[param('ns3::Mac48Address', 'source')],
visibility='protected')
## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::Learn(ns3::Mac48Address source, ns3::Ptr<ns3::NetDevice> port) [member function]
cls.add_method('Learn',
'void',
[param('ns3::Mac48Address', 'source'), param('ns3::Ptr< ns3::NetDevice >', 'port')],
visibility='protected')
## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::ReceiveFromDevice(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> packet, uint16_t protocol, ns3::Address const & source, ns3::Address const & destination, ns3::NetDevice::PacketType packetType) [member function]
cls.add_method('ReceiveFromDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'destination'), param('ns3::NetDevice::PacketType', 'packetType')],
visibility='protected')
return
def register_Ns3Ipv4ListRouting_methods(root_module, cls):
## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting::Ipv4ListRouting(ns3::Ipv4ListRouting const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4ListRouting const &', 'arg0')])
## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting::Ipv4ListRouting() [constructor]
cls.add_constructor([])
## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::AddRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol, int16_t priority) [member function]
cls.add_method('AddRoutingProtocol',
'void',
[param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol'), param('int16_t', 'priority')],
is_virtual=True)
## ipv4-list-routing.h (module 'internet'): uint32_t ns3::Ipv4ListRouting::GetNRoutingProtocols() const [member function]
cls.add_method('GetNRoutingProtocols',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ipv4-list-routing.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4ListRouting::GetRoutingProtocol(uint32_t index, int16_t & priority) const [member function]
cls.add_method('GetRoutingProtocol',
'ns3::Ptr< ns3::Ipv4RoutingProtocol >',
[param('uint32_t', 'index'), param('int16_t &', 'priority', direction=2)],
is_const=True, is_virtual=True)
## ipv4-list-routing.h (module 'internet'): static ns3::TypeId ns3::Ipv4ListRouting::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyAddAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_virtual=True)
## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyInterfaceDown(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceDown',
'void',
[param('uint32_t', 'interface')],
is_virtual=True)
## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyInterfaceUp(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceUp',
'void',
[param('uint32_t', 'interface')],
is_virtual=True)
## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyRemoveAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_virtual=True)
## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function]
cls.add_method('PrintRoutingTable',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_const=True, is_virtual=True)
## ipv4-list-routing.h (module 'internet'): bool ns3::Ipv4ListRouting::RouteInput(ns3::Ptr<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_virtual=True)
## ipv4-list-routing.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4ListRouting::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function]
cls.add_method('RouteOutput',
'ns3::Ptr< ns3::Ipv4Route >',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')],
is_virtual=True)
## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function]
cls.add_method('SetIpv4',
'void',
[param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')],
is_virtual=True)
## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3Ipv4NixVectorRouting_methods(root_module, cls):
## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorRouting::Ipv4NixVectorRouting(ns3::Ipv4NixVectorRouting const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4NixVectorRouting const &', 'arg0')])
## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorRouting::Ipv4NixVectorRouting() [constructor]
cls.add_constructor([])
## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::FlushGlobalNixRoutingCache() const [member function]
cls.add_method('FlushGlobalNixRoutingCache',
'void',
[],
is_const=True)
## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): static ns3::TypeId ns3::Ipv4NixVectorRouting::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyAddAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
visibility='private', is_virtual=True)
## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::NotifyInterfaceDown(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceDown',
'void',
[param('uint32_t', 'interface')],
visibility='private', is_virtual=True)
## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::NotifyInterfaceUp(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceUp',
'void',
[param('uint32_t', 'interface')],
visibility='private', is_virtual=True)
## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyRemoveAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
visibility='private', is_virtual=True)
## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function]
cls.add_method('PrintRoutingTable',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_const=True, visibility='private', is_virtual=True)
## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): bool ns3::Ipv4NixVectorRouting::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')],
visibility='private', is_virtual=True)
## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4NixVectorRouting::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')],
visibility='private', is_virtual=True)
## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function]
cls.add_method('SetIpv4',
'void',
[param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')],
visibility='private', is_virtual=True)
return
def register_Ns3HashImplementation_methods(root_module, cls):
## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Implementation const &', 'arg0')])
## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation() [constructor]
cls.add_constructor([])
## hash-function.h (module 'core'): uint32_t ns3::Hash::Implementation::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_pure_virtual=True, is_virtual=True)
## hash-function.h (module 'core'): uint64_t ns3::Hash::Implementation::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-function.h (module 'core'): void ns3::Hash::Implementation::clear() [member function]
cls.add_method('clear',
'void',
[],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3HashFunctionFnv1a_methods(root_module, cls):
## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a(ns3::Hash::Function::Fnv1a const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')])
## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a() [constructor]
cls.add_constructor([])
## hash-fnv.h (module 'core'): uint32_t ns3::Hash::Function::Fnv1a::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-fnv.h (module 'core'): uint64_t ns3::Hash::Function::Fnv1a::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-fnv.h (module 'core'): void ns3::Hash::Function::Fnv1a::clear() [member function]
cls.add_method('clear',
'void',
[],
is_virtual=True)
return
def register_Ns3HashFunctionHash32_methods(root_module, cls):
## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Function::Hash32 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Function::Hash32 const &', 'arg0')])
## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Hash32Function_ptr hp) [constructor]
cls.add_constructor([param('ns3::Hash::Hash32Function_ptr', 'hp')])
## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash32::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-function.h (module 'core'): void ns3::Hash::Function::Hash32::clear() [member function]
cls.add_method('clear',
'void',
[],
is_virtual=True)
return
def register_Ns3HashFunctionHash64_methods(root_module, cls):
## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Function::Hash64 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Function::Hash64 const &', 'arg0')])
## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Hash64Function_ptr hp) [constructor]
cls.add_constructor([param('ns3::Hash::Hash64Function_ptr', 'hp')])
## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash64::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-function.h (module 'core'): void ns3::Hash::Function::Hash64::clear() [member function]
cls.add_method('clear',
'void',
[],
is_virtual=True)
return
def register_Ns3HashFunctionMurmur3_methods(root_module, cls):
## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3(ns3::Hash::Function::Murmur3 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')])
## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor]
cls.add_constructor([])
## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function]
cls.add_method('clear',
'void',
[],
is_virtual=True)
return
def register_functions(root_module):
module = root_module
register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module)
register_functions_ns3_Hash(module.get_submodule('Hash'), root_module)
register_functions_ns3_TracedValueCallback(module.get_submodule('TracedValueCallback'), root_module)
return
def register_functions_ns3_FatalImpl(module, root_module):
return
def register_functions_ns3_Hash(module, root_module):
register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module)
return
def register_functions_ns3_Hash_Function(module, root_module):
return
def register_functions_ns3_TracedValueCallback(module, root_module):
return
def main():
out = FileCodeSink(sys.stdout)
root_module = module_init()
register_types(root_module)
register_methods(root_module)
register_functions(root_module)
root_module.generate(out)
if __name__ == '__main__':
main()
|
mohittahiliani/tcp-eval-suite-ns3
|
src/nix-vector-routing/bindings/modulegen__gcc_LP64.py
|
Python
|
gpl-2.0
| 373,845 | 0.015033 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.