repo_name stringlengths 5 100 | ref stringlengths 12 67 | path stringlengths 4 244 | copies stringlengths 1 8 | content stringlengths 0 1.05M ⌀ |
|---|---|---|---|---|
tutorgen/HPIT-python-client | refs/heads/master | tests/hpitclient/test_message_sender_mixin.py | 1 | import sure
import httpretty
import json
import pytest
from mock import *
from hpitclient.message_sender_mixin import MessageSenderMixin
from hpitclient.exceptions import InvalidMessageNameException
from hpitclient.exceptions import ResponseDispatchError
from hpitclient.exceptions import InvalidParametersError
def send_callback():
print("test callback")
@httpretty.activate
def test_send():
"""
MessageSenderMixin._send() Test plan:
-ensure events named transaction raise error
-ensure callback is set on success
-ensure that a response is received
"""
test_payload = {"item":"shoe"}
httpretty.register_uri(httpretty.POST,"https://www.hpit-project.org/message",
body='{"message_id":"4"}',
)
subject = MessageSenderMixin()
subject.send.when.called_with("transaction",test_payload,None).should.throw(InvalidMessageNameException)
response = subject.send("test_event",test_payload,send_callback)
subject.response_callbacks["4"].should.equal(globals()["send_callback"])
response.should.equal({"message_id":"4"})
@httpretty.activate
def test_send_transaction():
"""
MessageSenderMixin._send_transaction() Test plan:
-ensure callback is set on success
-ensure that a response is received
"""
test_payload = {"item":"shoe"}
httpretty.register_uri(httpretty.POST,"https://www.hpit-project.org/message",
body='{"message_id":"4"}',
)
subject = MessageSenderMixin()
response = subject.send("test_event",test_payload,send_callback)
subject.response_callbacks["4"].should.equal(globals()["send_callback"])
response.should.equal({"message_id":"4"})
@httpretty.activate
def test_poll_responses():
"""
MessageSenderMixin._poll_responses() Test plan:
-Ensure False returned if pre_poll_responses hook returns false
-Ensure False returned if post_poll_responses hook returns false
-Ensure a collection of responses returned on success
"""
httpretty.register_uri(httpretty.GET,"https://www.hpit-project.org/response/list",
body='{"responses":"4"}',
)
def returnFalse():
return False
def returnTrue():
return True
test_message_sender_mixin = MessageSenderMixin()
setattr(test_message_sender_mixin,"pre_poll_responses",returnFalse)
setattr(test_message_sender_mixin,"post_poll_responses",returnTrue)
test_message_sender_mixin._poll_responses().should.equal(False)
setattr(test_message_sender_mixin,"pre_poll_responses",returnTrue)
setattr(test_message_sender_mixin,"post_poll_responses",returnTrue)
test_message_sender_mixin._poll_responses().should.equal({})
test_message_sender_mixin.outstanding_responses["4"] = 1
setattr(test_message_sender_mixin,"pre_poll_responses",returnTrue)
setattr(test_message_sender_mixin,"post_poll_responses",returnFalse)
test_message_sender_mixin._poll_responses().should.equal(False)
setattr(test_message_sender_mixin,"pre_poll_responses",returnTrue)
setattr(test_message_sender_mixin,"post_poll_responses",returnTrue)
test_message_sender_mixin._poll_responses().should.equal("4")
def test_dispatch_responses():
"""
MessageSenderMixin._dispatch_responses() Test plan:
-Ensure False returned if pre_dispatch_responses hook returns false
-Ensure False returned if post_dispatch_responses hook returns false
-Catch invalid response from hpit on [message][id]
-Catch invaled response from hpit on [response]
-Catch no callback exception
-Catch not callable error
-Ensure true returned on completions
"""
bad_response = [{"bad_response": "boo"}]
bad_response2 = [{"message":{"message_id":"4"}}]
good_response = [{"message": {"message_id":"4"},"response":{"data":"2"}}]
def returnFalse():
return False
def returnTrue():
return True
def callback1(payload):
return True
test_message_sender_mixin = MessageSenderMixin()
test_message_sender_mixin.send_log_entry = MagicMock()
test_message_sender_mixin.outstanding_responses["4"] = 1
test_message_sender_mixin.response_callbacks["4"] = callback1
setattr(test_message_sender_mixin,"pre_dispatch_responses",returnFalse)
setattr(test_message_sender_mixin,"post_dispatch_responses",returnTrue)
test_message_sender_mixin._dispatch_responses(good_response).should.equal(False)
setattr(test_message_sender_mixin,"pre_dispatch_responses",returnTrue)
setattr(test_message_sender_mixin,"post_dispatch_responses",returnFalse)
test_message_sender_mixin._dispatch_responses(good_response).should.equal(False)
setattr(test_message_sender_mixin,"pre_dispatch_responses",returnTrue)
setattr(test_message_sender_mixin,"post_dispatch_responses",returnTrue)
test_message_sender_mixin._dispatch_responses(bad_response)
test_message_sender_mixin.send_log_entry.assert_called_once_with('Invalid response from HPIT. No message id supplied in response.')
test_message_sender_mixin.send_log_entry.reset_mock()
test_message_sender_mixin._dispatch_responses(bad_response2)
test_message_sender_mixin.send_log_entry.assert_called_once_with('Invalid response from HPIT. No response payload supplied.')
del test_message_sender_mixin.response_callbacks["4"]
test_message_sender_mixin.send_log_entry.reset_mock()
test_message_sender_mixin._dispatch_responses(good_response)
test_message_sender_mixin.send_log_entry.assert_called_once_with('No callback registered for message id: 4')
test_message_sender_mixin.response_callbacks["4"] = 5
test_message_sender_mixin.send_log_entry.reset_mock()
test_message_sender_mixin._dispatch_responses(good_response)
test_message_sender_mixin.send_log_entry.assert_called_once_with("Callback registered for transcation id: 4 is not a callable.")
test_message_sender_mixin.outstanding_responses["4"] = 1
test_message_sender_mixin.response_callbacks["4"] = callback1
test_message_sender_mixin._dispatch_responses(good_response).should.equal(True)
test_message_sender_mixin.outstanding_responses.should.be.empty
@httpretty.activate
def test_get_message_owner():
subject = MessageSenderMixin()
subject.send_log_entry = MagicMock()
httpretty.register_uri(httpretty.GET,
"https://www.hpit-project.org/message-owner/thing",
body='{"owner":"4"}',
content_type="application/json"
)
subject.get_message_owner.when.called_with(None).should.throw(InvalidParametersError)
subject.get_message_owner.when.called_with([]).should.throw(InvalidParametersError)
subject.get_message_owner.when.called_with({}).should.throw(InvalidParametersError)
subject.get_message_owner.when.called_with("").should.throw(InvalidParametersError)
subject.get_message_owner.when.called_with(['thing']).should.throw(InvalidParametersError)
subject.get_message_owner.when.called_with({'thing': 1}).should.throw(InvalidParametersError)
subject.get_message_owner('thing').should.equal('4')
@httpretty.activate
def test_share_resource():
subject = MessageSenderMixin()
subject.send_log_entry = MagicMock()
httpretty.register_uri(httpretty.POST,"https://www.hpit-project.org/share-resource",
body='OK',
)
subject.share_resource.when.called_with(None, None).should.throw(InvalidParametersError)
subject.share_resource.when.called_with('', None).should.throw(InvalidParametersError)
subject.share_resource.when.called_with([], None).should.throw(InvalidParametersError)
subject.share_resource.when.called_with({}, None).should.throw(InvalidParametersError)
subject.share_resource.when.called_with('thing', None).should.throw(InvalidParametersError)
subject.share_resource.when.called_with('thing', '').should.throw(InvalidParametersError)
subject.share_resource.when.called_with('thing', []).should.throw(InvalidParametersError)
subject.share_resource('thing', '4').should.equal(True)
subject.share_resource('thing', ['4', '5', '6']).should.equal(True)
|
jtrobec/pants | refs/heads/master | tests/python/pants_test/base/test_fingerprint_strategy.py | 33 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.base.fingerprint_strategy import DefaultFingerprintStrategy
from pants_test.base_test import BaseTest
class FingerprintStrategyTest(BaseTest):
def test_subclass_equality(self):
class FPStrategyA(DefaultFingerprintStrategy): pass
class FPStrategyB(DefaultFingerprintStrategy): pass
self.assertNotEqual(FPStrategyA(), DefaultFingerprintStrategy())
self.assertNotEqual(FPStrategyA(), FPStrategyB())
self.assertEqual(FPStrategyA(), FPStrategyA())
self.assertNotEqual(hash(FPStrategyA()), hash(DefaultFingerprintStrategy()))
self.assertNotEqual(hash(FPStrategyA()), hash(FPStrategyB()))
self.assertEqual(hash(FPStrategyA()), hash(FPStrategyA()))
|
ferabra/edx-platform | refs/heads/master | common/lib/calc/calc/functions.py | 279 | """
Provide the mathematical functions that numpy doesn't.
Specifically, the secant/cosecant/cotangents and their inverses and
hyperbolic counterparts
"""
import numpy
# Normal Trig
def sec(arg):
"""
Secant
"""
return 1 / numpy.cos(arg)
def csc(arg):
"""
Cosecant
"""
return 1 / numpy.sin(arg)
def cot(arg):
"""
Cotangent
"""
return 1 / numpy.tan(arg)
# Inverse Trig
# http://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Relationships_among_the_inverse_trigonometric_functions
def arcsec(val):
"""
Inverse secant
"""
return numpy.arccos(1. / val)
def arccsc(val):
"""
Inverse cosecant
"""
return numpy.arcsin(1. / val)
def arccot(val):
"""
Inverse cotangent
"""
if numpy.real(val) < 0:
return -numpy.pi / 2 - numpy.arctan(val)
else:
return numpy.pi / 2 - numpy.arctan(val)
# Hyperbolic Trig
def sech(arg):
"""
Hyperbolic secant
"""
return 1 / numpy.cosh(arg)
def csch(arg):
"""
Hyperbolic cosecant
"""
return 1 / numpy.sinh(arg)
def coth(arg):
"""
Hyperbolic cotangent
"""
return 1 / numpy.tanh(arg)
# And their inverses
def arcsech(val):
"""
Inverse hyperbolic secant
"""
return numpy.arccosh(1. / val)
def arccsch(val):
"""
Inverse hyperbolic cosecant
"""
return numpy.arcsinh(1. / val)
def arccoth(val):
"""
Inverse hyperbolic cotangent
"""
return numpy.arctanh(1. / val)
|
vladmm/intellij-community | refs/heads/master | python/testData/codeInsight/smartEnter/py891_after.py | 83 | class Foo:
def __init__(self):
<caret> |
erinspace/rivannastreamwatch_api | refs/heads/master | reports/admin.py | 469 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
# Register your models here.
|
amyvmiwei/kbengine | refs/heads/master | kbe/res/scripts/common/Lib/test/test_codecmaps_cn.py | 16 | #
# test_codecmaps_cn.py
# Codec mapping tests for PRC encodings
#
from test import support
from test import multibytecodec_support
import unittest
class TestGB2312Map(multibytecodec_support.TestBase_Mapping,
unittest.TestCase):
encoding = 'gb2312'
mapfileurl = 'http://people.freebsd.org/~perky/i18n/EUC-CN.TXT'
class TestGBKMap(multibytecodec_support.TestBase_Mapping,
unittest.TestCase):
encoding = 'gbk'
mapfileurl = 'http://www.unicode.org/Public/MAPPINGS/VENDORS/' \
'MICSFT/WINDOWS/CP936.TXT'
class TestGB18030Map(multibytecodec_support.TestBase_Mapping,
unittest.TestCase):
encoding = 'gb18030'
mapfileurl = 'http://source.icu-project.org/repos/icu/data/' \
'trunk/charset/data/xml/gb-18030-2000.xml'
def test_main():
support.run_unittest(__name__)
if __name__ == "__main__":
test_main()
|
agentr13/python-phonenumbers | refs/heads/dev | python/phonenumbers/data/region_PT.py | 6 | """Auto-generated file, do not edit by hand. PT metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_PT = PhoneMetadata(id='PT', country_code=351, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='[2-46-9]\\d{8}', possible_number_pattern='\\d{9}'),
fixed_line=PhoneNumberDesc(national_number_pattern='2(?:[12]\\d|[35][1-689]|4[1-59]|6[1-35689]|7[1-9]|8[1-69]|9[1256])\\d{6}', possible_number_pattern='\\d{9}', example_number='212345678'),
mobile=PhoneNumberDesc(national_number_pattern='9(?:[1236]\\d{2}|480)\\d{5}', possible_number_pattern='\\d{9}', example_number='912345678'),
toll_free=PhoneNumberDesc(national_number_pattern='80[02]\\d{6}', possible_number_pattern='\\d{9}', example_number='800123456'),
premium_rate=PhoneNumberDesc(national_number_pattern='6(?:0[178]|4[68])\\d{6}|76(?:0[1-57]|1[2-47]|2[237])\\d{5}', possible_number_pattern='\\d{9}', example_number='760123456'),
shared_cost=PhoneNumberDesc(national_number_pattern='80(?:8\\d|9[1579])\\d{5}', possible_number_pattern='\\d{9}', example_number='808123456'),
personal_number=PhoneNumberDesc(national_number_pattern='884[0-4689]\\d{5}', possible_number_pattern='\\d{9}', example_number='884123456'),
voip=PhoneNumberDesc(national_number_pattern='30\\d{7}', possible_number_pattern='\\d{9}', example_number='301234567'),
pager=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
uan=PhoneNumberDesc(national_number_pattern='7(?:0(?:7\\d|8[17]))\\d{5}', possible_number_pattern='\\d{9}', example_number='707123456'),
voicemail=PhoneNumberDesc(national_number_pattern='600\\d{6}', possible_number_pattern='\\d{9}', example_number='600110000'),
no_international_dialling=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
number_format=[NumberFormat(pattern='(2\\d)(\\d{3})(\\d{4})', format='\\1 \\2 \\3', leading_digits_pattern=['2[12]']),
NumberFormat(pattern='([2-46-9]\\d{2})(\\d{3})(\\d{3})', format='\\1 \\2 \\3', leading_digits_pattern=['2[3-9]|[346-9]'])],
mobile_number_portable_region=True)
|
fredg02/crazyflie-clients-python | refs/heads/develop | src/cfclient/ui/dialogs/logconfigdialogue.py | 1 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# || ____ _ __
# +------+ / __ )(_) /_______________ _____ ___
# | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
# +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
#
# Copyright (C) 2011-2013 Bitcraze AB
#
# Crazyflie Nano Quadcopter Client
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
This dialogue is used to configure different log configurations that is used to
enable logging of data from the Crazyflie. These can then be used in different
views in the UI.
"""
import logging
import cfclient
from PyQt4 import Qt, QtGui, uic
from PyQt4.QtCore import * # noqa
from PyQt4.QtGui import * # noqa
from PyQt4.Qt import * # noqa
from cflib.crazyflie.log import LogConfig
__author__ = 'Bitcraze AB'
__all__ = ['LogConfigDialogue']
logger = logging.getLogger(__name__)
(logconfig_widget_class, connect_widget_base_class) = (
uic.loadUiType(cfclient.module_path + '/ui/dialogs/logconfigdialogue.ui'))
NAME_FIELD = 0
ID_FIELD = 1
PTYPE_FIELD = 2
CTYPE_FIELD = 3
class LogConfigDialogue(QtGui.QWidget, logconfig_widget_class):
def __init__(self, helper, *args):
super(LogConfigDialogue, self).__init__(*args)
self.setupUi(self)
self.helper = helper
self.logTree.setHeaderLabels(['Name', 'ID', 'Unpack', 'Storage'])
self.varTree.setHeaderLabels(['Name', 'ID', 'Unpack', 'Storage'])
self.addButton.clicked.connect(lambda: self.moveNode(self.logTree,
self.varTree))
self.removeButton.clicked.connect(lambda: self.moveNode(self.varTree,
self.logTree))
self.cancelButton.clicked.connect(self.close)
self.loadButton.clicked.connect(self.loadConfig)
self.saveButton.clicked.connect(self.saveConfig)
self.loggingPeriod.textChanged.connect(self.periodChanged)
self.packetSize.setMaximum(30)
self.currentSize = 0
self.packetSize.setValue(0)
self.period = 0
def decodeSize(self, s):
size = 0
if ("16" in s):
size = 2
if ("float" in s):
size = 4
if ("8" in s):
size = 1
if ("FP16" in s):
size = 2
if ("32" in s):
size = 4
return size
def sortTrees(self):
self.varTree.invisibleRootItem().sortChildren(NAME_FIELD,
Qt.AscendingOrder)
for node in self.getNodeChildren(self.varTree.invisibleRootItem()):
node.sortChildren(NAME_FIELD, Qt.AscendingOrder)
self.logTree.invisibleRootItem().sortChildren(NAME_FIELD,
Qt.AscendingOrder)
for node in self.getNodeChildren(self.logTree.invisibleRootItem()):
node.sortChildren(NAME_FIELD, Qt.AscendingOrder)
def getNodeChildren(self, treeNode):
children = []
for i in range(treeNode.childCount()):
children.append(treeNode.child(i))
return children
def updatePacketSizeBar(self):
self.currentSize = 0
for node in self.getNodeChildren(self.varTree.invisibleRootItem()):
for leaf in self.getNodeChildren(node):
self.currentSize = (self.currentSize +
self.decodeSize(leaf.text(CTYPE_FIELD)))
self.packetSize.setValue(self.currentSize)
def addNewVar(self, logTreeItem, target):
parentName = logTreeItem.parent().text(NAME_FIELD)
varParent = target.findItems(parentName, Qt.MatchExactly, NAME_FIELD)
item = logTreeItem.clone()
if (len(varParent) == 0):
newParent = QtGui.QTreeWidgetItem()
newParent.setData(0, Qt.DisplayRole, parentName)
newParent.addChild(item)
target.addTopLevelItem(newParent)
target.expandItem(newParent)
else:
parent = varParent[0]
parent.addChild(item)
def moveNodeItem(self, source, target, item):
if (item.parent() is None):
children = self.getNodeChildren(item)
for c in children:
self.addNewVar(c, target)
source.takeTopLevelItem(source.indexOfTopLevelItem(item))
elif (item.parent().childCount() > 1):
self.addNewVar(item, target)
item.parent().removeChild(item)
else:
self.addNewVar(item, target)
# item.parent().removeChild(item)
source.takeTopLevelItem(source.indexOfTopLevelItem(item.parent()))
self.updatePacketSizeBar()
self.sortTrees()
self.checkAndEnableSaveButton()
def checkAndEnableSaveButton(self):
if (self.currentSize > 0 and self.period > 0):
self.saveButton.setEnabled(True)
else:
self.saveButton.setEnabled(False)
def moveNode(self, source, target):
self.moveNodeItem(source, target, source.currentItem())
def moveNodeByName(self, source, target, parentName, itemName):
parents = source.findItems(parentName, Qt.MatchExactly, NAME_FIELD)
node = None
if (len(parents) > 0):
parent = parents[0]
for n in range(parent.childCount()):
if (parent.child(n).text(NAME_FIELD) == itemName):
node = parent.child(n)
break
if (node is not None):
self.moveNodeItem(source, target, node)
return True
return False
def showEvent(self, event):
self.updateToc()
self.populateDropDown()
toc = self.helper.cf.log.toc
if (len(list(toc.toc.keys())) > 0):
self.configNameCombo.setEnabled(True)
else:
self.configNameCombo.setEnabled(False)
def resetTrees(self):
self.varTree.clear()
self.updateToc()
def periodChanged(self, value):
try:
self.period = int(value)
self.checkAndEnableSaveButton()
except:
self.period = 0
def showErrorPopup(self, caption, message):
self.box = QMessageBox()
self.box.setWindowTitle(caption)
self.box.setText(message)
# self.box.setButtonText(1, "Ok")
self.box.setWindowFlags(Qt.Dialog | Qt.MSWindowsFixedSizeDialogHint)
self.box.show()
def updateToc(self):
self.logTree.clear()
toc = self.helper.cf.log.toc
for group in list(toc.toc.keys()):
groupItem = QtGui.QTreeWidgetItem()
groupItem.setData(NAME_FIELD, Qt.DisplayRole, group)
for param in list(toc.toc[group].keys()):
item = QtGui.QTreeWidgetItem()
item.setData(NAME_FIELD, Qt.DisplayRole, param)
item.setData(ID_FIELD, Qt.DisplayRole,
toc.toc[group][param].ident)
item.setData(PTYPE_FIELD, Qt.DisplayRole,
toc.toc[group][param].pytype)
item.setData(CTYPE_FIELD, Qt.DisplayRole,
toc.toc[group][param].ctype)
groupItem.addChild(item)
self.logTree.addTopLevelItem(groupItem)
self.logTree.expandItem(groupItem)
self.sortTrees()
def populateDropDown(self):
self.configNameCombo.clear()
toc = self.helper.logConfigReader.getLogConfigs()
for d in toc:
self.configNameCombo.addItem(d.name)
if (len(toc) > 0):
self.loadButton.setEnabled(True)
def loadConfig(self):
cText = self.configNameCombo.currentText()
config = None
for d in self.helper.logConfigReader.getLogConfigs():
if (d.name == cText):
config = d
if (config is None):
logger.warning("Could not load config")
else:
self.resetTrees()
self.loggingPeriod.setText("%d" % config.period_in_ms)
self.period = config.period_in_ms
for v in config.variables:
if (v.is_toc_variable()):
parts = v.name.split(".")
varParent = parts[0]
varName = parts[1]
if self.moveNodeByName(
self.logTree, self.varTree, varParent,
varName) is False:
logger.warning("Could not find node %s.%s!!",
varParent, varName)
else:
logger.warning("Error: Mem vars not supported!")
def saveConfig(self):
updatedConfig = self.createConfigFromSelection()
try:
self.helper.logConfigReader.saveLogConfigFile(updatedConfig)
self.close()
except Exception as e:
self.showErrorPopup("Error when saving file", "Error: %s" % e)
self.helper.cf.log.add_config(updatedConfig)
def createConfigFromSelection(self):
logconfig = LogConfig(str(self.configNameCombo.currentText()),
self.period)
for node in self.getNodeChildren(self.varTree.invisibleRootItem()):
parentName = node.text(NAME_FIELD)
for leaf in self.getNodeChildren(node):
varName = leaf.text(NAME_FIELD)
varType = str(leaf.text(CTYPE_FIELD))
completeName = "%s.%s" % (parentName, varName)
logconfig.add_variable(completeName, varType)
return logconfig
|
gaste/dwasp | refs/heads/master | tests/asp/weakConstraints/2-still_live-3-1.asp.gringo.test.py | 4 | input = """
1 2 0 0
1 3 0 0
1 4 0 0
1 5 0 0
1 6 0 0
1 7 0 0
1 8 0 0
1 9 0 0
1 10 0 0
1 11 0 0
1 12 0 0
1 13 0 0
1 14 0 0
1 15 0 0
1 16 0 0
2 17 3 0 3 18 19 20
1 21 1 0 17
1 1 2 1 22 21
2 23 3 0 3 18 22 20
1 24 1 0 23
1 1 2 1 19 24
2 25 3 0 3 18 22 19
1 26 1 0 25
1 1 2 1 20 26
2 27 3 0 3 22 19 20
1 28 1 0 27
1 1 2 1 18 28
2 29 3 0 2 22 19 20
1 30 1 0 29
1 1 2 1 30 18
2 31 3 0 2 18 19 20
1 32 1 0 31
1 1 2 1 32 22
2 33 3 0 2 18 22 20
1 34 1 0 33
1 1 2 1 34 19
2 35 3 0 2 18 22 19
1 36 1 0 35
1 1 2 1 36 20
1 37 1 0 18
1 37 1 0 19
1 38 1 0 22
1 38 1 0 20
1 39 1 0 37
1 40 1 0 39
1 41 1 0 18
1 42 1 0 41
1 43 2 0 40 42
1 44 1 0 18
1 44 1 0 19
1 45 1 0 22
1 45 1 0 20
1 46 1 0 44
1 47 1 0 46
1 48 1 0 19
1 49 1 0 18
1 50 2 1 49 48
1 51 2 0 47 50
1 52 1 0 18
1 52 1 0 19
1 53 1 0 22
1 53 1 0 20
1 54 1 0 52
1 55 1 0 54
1 56 1 0 18
1 56 1 0 19
1 57 2 1 56 58
1 59 2 0 55 57
1 60 1 0 18
1 60 1 0 19
1 61 1 0 22
1 61 1 0 20
1 62 1 0 61
1 63 1 0 60
1 64 2 1 63 62
1 65 1 0 22
1 66 1 0 65
1 67 2 0 64 66
1 68 1 0 18
1 68 1 0 19
1 69 1 0 22
1 69 1 0 20
1 70 1 0 69
1 71 1 0 68
1 72 2 1 71 70
1 73 1 0 20
1 74 1 0 22
1 75 2 1 74 73
1 76 2 0 72 75
1 77 1 0 18
1 77 1 0 19
1 78 1 0 22
1 78 1 0 20
1 79 1 0 78
1 80 1 0 77
1 81 2 1 80 79
1 82 1 0 22
1 82 1 0 20
1 83 2 1 82 84
1 85 2 0 81 83
1 67 2 0 43 22
1 51 2 0 43 19
1 76 2 0 43 20
1 43 2 0 51 18
1 67 2 0 51 22
1 76 2 0 51 20
1 51 2 0 59 19
1 76 2 0 59 20
1 43 2 0 67 18
1 51 2 0 67 19
1 76 2 0 67 20
1 43 2 0 76 18
1 67 2 0 76 22
1 51 2 0 76 19
1 51 2 0 85 19
1 76 2 0 85 20
1 1 2 1 43 18
1 1 2 1 67 22
1 1 2 1 51 19
1 1 2 1 76 20
3 4 18 22 19 20 0 0
1 86 0 0
1 87 0 0
1 88 0 0
1 89 0 0
1 90 0 0
1 91 0 0
1 92 0 0
1 93 0 0
1 94 0 0
1 95 0 0
1 96 0 0
1 97 0 0
6 0 16 4 18 22 19 20 86 87 88 89 90 91 92 93 94 95 96 97 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
0
2 value(0)
5 value(1)
6 value(2)
7 value(3)
4 size(2)
3 step(1)
8 step(-1)
9 diff(1,0)
10 diff(-1,0)
11 diff(0,1)
12 diff(0,-1)
13 diff(1,1)
14 diff(-1,1)
15 diff(1,-1)
16 diff(-1,-1)
18 lives(1,1)
22 lives(2,1)
19 lives(1,2)
20 lives(2,2)
43 reached(1,1)
51 reached(1,2)
59 reached(1,3)
67 reached(2,1)
76 reached(2,2)
85 reached(2,3)
0
B+
0
B-
1
0
1
"""
output = """
COST 12@1
"""
|
Arc-Team/android_kernel_htc_msm8660 | refs/heads/cm-11.0 | tools/perf/scripts/python/netdev-times.py | 11271 | # Display a process of packets and processed time.
# It helps us to investigate networking or network device.
#
# options
# tx: show only tx chart
# rx: show only rx chart
# dev=: show only thing related to specified device
# debug: work with debug mode. It shows buffer status.
import os
import sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from perf_trace_context import *
from Core import *
from Util import *
all_event_list = []; # insert all tracepoint event related with this script
irq_dic = {}; # key is cpu and value is a list which stacks irqs
# which raise NET_RX softirq
net_rx_dic = {}; # key is cpu and value include time of NET_RX softirq-entry
# and a list which stacks receive
receive_hunk_list = []; # a list which include a sequence of receive events
rx_skb_list = []; # received packet list for matching
# skb_copy_datagram_iovec
buffer_budget = 65536; # the budget of rx_skb_list, tx_queue_list and
# tx_xmit_list
of_count_rx_skb_list = 0; # overflow count
tx_queue_list = []; # list of packets which pass through dev_queue_xmit
of_count_tx_queue_list = 0; # overflow count
tx_xmit_list = []; # list of packets which pass through dev_hard_start_xmit
of_count_tx_xmit_list = 0; # overflow count
tx_free_list = []; # list of packets which is freed
# options
show_tx = 0;
show_rx = 0;
dev = 0; # store a name of device specified by option "dev="
debug = 0;
# indices of event_info tuple
EINFO_IDX_NAME= 0
EINFO_IDX_CONTEXT=1
EINFO_IDX_CPU= 2
EINFO_IDX_TIME= 3
EINFO_IDX_PID= 4
EINFO_IDX_COMM= 5
# Calculate a time interval(msec) from src(nsec) to dst(nsec)
def diff_msec(src, dst):
return (dst - src) / 1000000.0
# Display a process of transmitting a packet
def print_transmit(hunk):
if dev != 0 and hunk['dev'].find(dev) < 0:
return
print "%7s %5d %6d.%06dsec %12.3fmsec %12.3fmsec" % \
(hunk['dev'], hunk['len'],
nsecs_secs(hunk['queue_t']),
nsecs_nsecs(hunk['queue_t'])/1000,
diff_msec(hunk['queue_t'], hunk['xmit_t']),
diff_msec(hunk['xmit_t'], hunk['free_t']))
# Format for displaying rx packet processing
PF_IRQ_ENTRY= " irq_entry(+%.3fmsec irq=%d:%s)"
PF_SOFT_ENTRY=" softirq_entry(+%.3fmsec)"
PF_NAPI_POLL= " napi_poll_exit(+%.3fmsec %s)"
PF_JOINT= " |"
PF_WJOINT= " | |"
PF_NET_RECV= " |---netif_receive_skb(+%.3fmsec skb=%x len=%d)"
PF_NET_RX= " |---netif_rx(+%.3fmsec skb=%x)"
PF_CPY_DGRAM= " | skb_copy_datagram_iovec(+%.3fmsec %d:%s)"
PF_KFREE_SKB= " | kfree_skb(+%.3fmsec location=%x)"
PF_CONS_SKB= " | consume_skb(+%.3fmsec)"
# Display a process of received packets and interrputs associated with
# a NET_RX softirq
def print_receive(hunk):
show_hunk = 0
irq_list = hunk['irq_list']
cpu = irq_list[0]['cpu']
base_t = irq_list[0]['irq_ent_t']
# check if this hunk should be showed
if dev != 0:
for i in range(len(irq_list)):
if irq_list[i]['name'].find(dev) >= 0:
show_hunk = 1
break
else:
show_hunk = 1
if show_hunk == 0:
return
print "%d.%06dsec cpu=%d" % \
(nsecs_secs(base_t), nsecs_nsecs(base_t)/1000, cpu)
for i in range(len(irq_list)):
print PF_IRQ_ENTRY % \
(diff_msec(base_t, irq_list[i]['irq_ent_t']),
irq_list[i]['irq'], irq_list[i]['name'])
print PF_JOINT
irq_event_list = irq_list[i]['event_list']
for j in range(len(irq_event_list)):
irq_event = irq_event_list[j]
if irq_event['event'] == 'netif_rx':
print PF_NET_RX % \
(diff_msec(base_t, irq_event['time']),
irq_event['skbaddr'])
print PF_JOINT
print PF_SOFT_ENTRY % \
diff_msec(base_t, hunk['sirq_ent_t'])
print PF_JOINT
event_list = hunk['event_list']
for i in range(len(event_list)):
event = event_list[i]
if event['event_name'] == 'napi_poll':
print PF_NAPI_POLL % \
(diff_msec(base_t, event['event_t']), event['dev'])
if i == len(event_list) - 1:
print ""
else:
print PF_JOINT
else:
print PF_NET_RECV % \
(diff_msec(base_t, event['event_t']), event['skbaddr'],
event['len'])
if 'comm' in event.keys():
print PF_WJOINT
print PF_CPY_DGRAM % \
(diff_msec(base_t, event['comm_t']),
event['pid'], event['comm'])
elif 'handle' in event.keys():
print PF_WJOINT
if event['handle'] == "kfree_skb":
print PF_KFREE_SKB % \
(diff_msec(base_t,
event['comm_t']),
event['location'])
elif event['handle'] == "consume_skb":
print PF_CONS_SKB % \
diff_msec(base_t,
event['comm_t'])
print PF_JOINT
def trace_begin():
global show_tx
global show_rx
global dev
global debug
for i in range(len(sys.argv)):
if i == 0:
continue
arg = sys.argv[i]
if arg == 'tx':
show_tx = 1
elif arg =='rx':
show_rx = 1
elif arg.find('dev=',0, 4) >= 0:
dev = arg[4:]
elif arg == 'debug':
debug = 1
if show_tx == 0 and show_rx == 0:
show_tx = 1
show_rx = 1
def trace_end():
# order all events in time
all_event_list.sort(lambda a,b :cmp(a[EINFO_IDX_TIME],
b[EINFO_IDX_TIME]))
# process all events
for i in range(len(all_event_list)):
event_info = all_event_list[i]
name = event_info[EINFO_IDX_NAME]
if name == 'irq__softirq_exit':
handle_irq_softirq_exit(event_info)
elif name == 'irq__softirq_entry':
handle_irq_softirq_entry(event_info)
elif name == 'irq__softirq_raise':
handle_irq_softirq_raise(event_info)
elif name == 'irq__irq_handler_entry':
handle_irq_handler_entry(event_info)
elif name == 'irq__irq_handler_exit':
handle_irq_handler_exit(event_info)
elif name == 'napi__napi_poll':
handle_napi_poll(event_info)
elif name == 'net__netif_receive_skb':
handle_netif_receive_skb(event_info)
elif name == 'net__netif_rx':
handle_netif_rx(event_info)
elif name == 'skb__skb_copy_datagram_iovec':
handle_skb_copy_datagram_iovec(event_info)
elif name == 'net__net_dev_queue':
handle_net_dev_queue(event_info)
elif name == 'net__net_dev_xmit':
handle_net_dev_xmit(event_info)
elif name == 'skb__kfree_skb':
handle_kfree_skb(event_info)
elif name == 'skb__consume_skb':
handle_consume_skb(event_info)
# display receive hunks
if show_rx:
for i in range(len(receive_hunk_list)):
print_receive(receive_hunk_list[i])
# display transmit hunks
if show_tx:
print " dev len Qdisc " \
" netdevice free"
for i in range(len(tx_free_list)):
print_transmit(tx_free_list[i])
if debug:
print "debug buffer status"
print "----------------------------"
print "xmit Qdisc:remain:%d overflow:%d" % \
(len(tx_queue_list), of_count_tx_queue_list)
print "xmit netdevice:remain:%d overflow:%d" % \
(len(tx_xmit_list), of_count_tx_xmit_list)
print "receive:remain:%d overflow:%d" % \
(len(rx_skb_list), of_count_rx_skb_list)
# called from perf, when it finds a correspoinding event
def irq__softirq_entry(name, context, cpu, sec, nsec, pid, comm, vec):
if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX":
return
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec)
all_event_list.append(event_info)
def irq__softirq_exit(name, context, cpu, sec, nsec, pid, comm, vec):
if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX":
return
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec)
all_event_list.append(event_info)
def irq__softirq_raise(name, context, cpu, sec, nsec, pid, comm, vec):
if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX":
return
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec)
all_event_list.append(event_info)
def irq__irq_handler_entry(name, context, cpu, sec, nsec, pid, comm,
irq, irq_name):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
irq, irq_name)
all_event_list.append(event_info)
def irq__irq_handler_exit(name, context, cpu, sec, nsec, pid, comm, irq, ret):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, irq, ret)
all_event_list.append(event_info)
def napi__napi_poll(name, context, cpu, sec, nsec, pid, comm, napi, dev_name):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
napi, dev_name)
all_event_list.append(event_info)
def net__netif_receive_skb(name, context, cpu, sec, nsec, pid, comm, skbaddr,
skblen, dev_name):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr, skblen, dev_name)
all_event_list.append(event_info)
def net__netif_rx(name, context, cpu, sec, nsec, pid, comm, skbaddr,
skblen, dev_name):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr, skblen, dev_name)
all_event_list.append(event_info)
def net__net_dev_queue(name, context, cpu, sec, nsec, pid, comm,
skbaddr, skblen, dev_name):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr, skblen, dev_name)
all_event_list.append(event_info)
def net__net_dev_xmit(name, context, cpu, sec, nsec, pid, comm,
skbaddr, skblen, rc, dev_name):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr, skblen, rc ,dev_name)
all_event_list.append(event_info)
def skb__kfree_skb(name, context, cpu, sec, nsec, pid, comm,
skbaddr, protocol, location):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr, protocol, location)
all_event_list.append(event_info)
def skb__consume_skb(name, context, cpu, sec, nsec, pid, comm, skbaddr):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr)
all_event_list.append(event_info)
def skb__skb_copy_datagram_iovec(name, context, cpu, sec, nsec, pid, comm,
skbaddr, skblen):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr, skblen)
all_event_list.append(event_info)
def handle_irq_handler_entry(event_info):
(name, context, cpu, time, pid, comm, irq, irq_name) = event_info
if cpu not in irq_dic.keys():
irq_dic[cpu] = []
irq_record = {'irq':irq, 'name':irq_name, 'cpu':cpu, 'irq_ent_t':time}
irq_dic[cpu].append(irq_record)
def handle_irq_handler_exit(event_info):
(name, context, cpu, time, pid, comm, irq, ret) = event_info
if cpu not in irq_dic.keys():
return
irq_record = irq_dic[cpu].pop()
if irq != irq_record['irq']:
return
irq_record.update({'irq_ext_t':time})
# if an irq doesn't include NET_RX softirq, drop.
if 'event_list' in irq_record.keys():
irq_dic[cpu].append(irq_record)
def handle_irq_softirq_raise(event_info):
(name, context, cpu, time, pid, comm, vec) = event_info
if cpu not in irq_dic.keys() \
or len(irq_dic[cpu]) == 0:
return
irq_record = irq_dic[cpu].pop()
if 'event_list' in irq_record.keys():
irq_event_list = irq_record['event_list']
else:
irq_event_list = []
irq_event_list.append({'time':time, 'event':'sirq_raise'})
irq_record.update({'event_list':irq_event_list})
irq_dic[cpu].append(irq_record)
def handle_irq_softirq_entry(event_info):
(name, context, cpu, time, pid, comm, vec) = event_info
net_rx_dic[cpu] = {'sirq_ent_t':time, 'event_list':[]}
def handle_irq_softirq_exit(event_info):
(name, context, cpu, time, pid, comm, vec) = event_info
irq_list = []
event_list = 0
if cpu in irq_dic.keys():
irq_list = irq_dic[cpu]
del irq_dic[cpu]
if cpu in net_rx_dic.keys():
sirq_ent_t = net_rx_dic[cpu]['sirq_ent_t']
event_list = net_rx_dic[cpu]['event_list']
del net_rx_dic[cpu]
if irq_list == [] or event_list == 0:
return
rec_data = {'sirq_ent_t':sirq_ent_t, 'sirq_ext_t':time,
'irq_list':irq_list, 'event_list':event_list}
# merge information realted to a NET_RX softirq
receive_hunk_list.append(rec_data)
def handle_napi_poll(event_info):
(name, context, cpu, time, pid, comm, napi, dev_name) = event_info
if cpu in net_rx_dic.keys():
event_list = net_rx_dic[cpu]['event_list']
rec_data = {'event_name':'napi_poll',
'dev':dev_name, 'event_t':time}
event_list.append(rec_data)
def handle_netif_rx(event_info):
(name, context, cpu, time, pid, comm,
skbaddr, skblen, dev_name) = event_info
if cpu not in irq_dic.keys() \
or len(irq_dic[cpu]) == 0:
return
irq_record = irq_dic[cpu].pop()
if 'event_list' in irq_record.keys():
irq_event_list = irq_record['event_list']
else:
irq_event_list = []
irq_event_list.append({'time':time, 'event':'netif_rx',
'skbaddr':skbaddr, 'skblen':skblen, 'dev_name':dev_name})
irq_record.update({'event_list':irq_event_list})
irq_dic[cpu].append(irq_record)
def handle_netif_receive_skb(event_info):
global of_count_rx_skb_list
(name, context, cpu, time, pid, comm,
skbaddr, skblen, dev_name) = event_info
if cpu in net_rx_dic.keys():
rec_data = {'event_name':'netif_receive_skb',
'event_t':time, 'skbaddr':skbaddr, 'len':skblen}
event_list = net_rx_dic[cpu]['event_list']
event_list.append(rec_data)
rx_skb_list.insert(0, rec_data)
if len(rx_skb_list) > buffer_budget:
rx_skb_list.pop()
of_count_rx_skb_list += 1
def handle_net_dev_queue(event_info):
global of_count_tx_queue_list
(name, context, cpu, time, pid, comm,
skbaddr, skblen, dev_name) = event_info
skb = {'dev':dev_name, 'skbaddr':skbaddr, 'len':skblen, 'queue_t':time}
tx_queue_list.insert(0, skb)
if len(tx_queue_list) > buffer_budget:
tx_queue_list.pop()
of_count_tx_queue_list += 1
def handle_net_dev_xmit(event_info):
global of_count_tx_xmit_list
(name, context, cpu, time, pid, comm,
skbaddr, skblen, rc, dev_name) = event_info
if rc == 0: # NETDEV_TX_OK
for i in range(len(tx_queue_list)):
skb = tx_queue_list[i]
if skb['skbaddr'] == skbaddr:
skb['xmit_t'] = time
tx_xmit_list.insert(0, skb)
del tx_queue_list[i]
if len(tx_xmit_list) > buffer_budget:
tx_xmit_list.pop()
of_count_tx_xmit_list += 1
return
def handle_kfree_skb(event_info):
(name, context, cpu, time, pid, comm,
skbaddr, protocol, location) = event_info
for i in range(len(tx_queue_list)):
skb = tx_queue_list[i]
if skb['skbaddr'] == skbaddr:
del tx_queue_list[i]
return
for i in range(len(tx_xmit_list)):
skb = tx_xmit_list[i]
if skb['skbaddr'] == skbaddr:
skb['free_t'] = time
tx_free_list.append(skb)
del tx_xmit_list[i]
return
for i in range(len(rx_skb_list)):
rec_data = rx_skb_list[i]
if rec_data['skbaddr'] == skbaddr:
rec_data.update({'handle':"kfree_skb",
'comm':comm, 'pid':pid, 'comm_t':time})
del rx_skb_list[i]
return
def handle_consume_skb(event_info):
(name, context, cpu, time, pid, comm, skbaddr) = event_info
for i in range(len(tx_xmit_list)):
skb = tx_xmit_list[i]
if skb['skbaddr'] == skbaddr:
skb['free_t'] = time
tx_free_list.append(skb)
del tx_xmit_list[i]
return
def handle_skb_copy_datagram_iovec(event_info):
(name, context, cpu, time, pid, comm, skbaddr, skblen) = event_info
for i in range(len(rx_skb_list)):
rec_data = rx_skb_list[i]
if skbaddr == rec_data['skbaddr']:
rec_data.update({'handle':"skb_copy_datagram_iovec",
'comm':comm, 'pid':pid, 'comm_t':time})
del rx_skb_list[i]
return
|
whoflungpoop/badbot | refs/heads/master | plugins/tag.py | 2 | # -*- coding: utf-8 -*-
import math
import random
import re
import threading
from util import hook
def sanitize(s):
return re.sub(r'[\x00-\x1f]', '', s)
# @hook.command
# def munge(inp, munge_count=0):
# reps = 0
# for n in xrange(len(inp)):
# rep = character_replacements.get(inp[n])
# if rep:
# inp = inp[:n] + rep.decode('utf8') + inp[n + 1:]
# reps += 1
# if reps == munge_count:
# break
# return inp
@hook.command
def munge(inp, munge_count=0):
return inp
class PaginatingWinnower(object):
def __init__(self):
self.lock = threading.Lock()
self.last_input = []
self.recent = set()
def winnow(self, inputs, limit=400, ordered=False):
"remove random elements from the list until it's short enough"
with self.lock:
# try to remove elements that were *not* removed recently
inputs_sorted = sorted(inputs)
if inputs_sorted == self.last_input:
same_input = True
else:
same_input = False
self.last_input = inputs_sorted
self.recent.clear()
combiner = lambda l: u', '.join(l)
suffix = ''
while len(combiner(inputs)) >= limit:
if same_input and any(inp in self.recent for inp in inputs):
if ordered:
for inp in self.recent:
if inp in inputs:
inputs.remove(inp)
else:
inputs.remove(
random.choice([inp for inp in inputs if inp in self.recent]))
else:
if ordered:
inputs.pop()
else:
inputs.pop(random.randint(0, len(inputs) - 1))
suffix = ' ...'
self.recent.update(inputs)
return combiner(inputs) + suffix
winnow = PaginatingWinnower().winnow
def add_tag(db, chan, nick, subject):
match = db.execute('select * from tag where lower(nick)=lower(?) and'
' chan=? and lower(subject)=lower(?)',
(nick, chan, subject)).fetchall()
if match:
return 'already tagged'
db.execute('replace into tag(chan, subject, nick) values(?,?,?)',
(chan, subject, nick))
db.commit()
return 'tag added'
def delete_tag(db, chan, nick, del_tag):
count = db.execute('delete from tag where lower(nick)=lower(?) and'
' chan=? and lower(subject)=lower(?)',
(nick, chan, del_tag)).rowcount
db.commit()
if count:
return 'deleted'
else:
return 'tag not found'
def get_tag_counts_by_chan(db, chan):
tags = db.execute("select subject, count(*) from tag where chan=?"
" group by lower(subject)"
" order by lower(subject)", (chan,)).fetchall()
tags.sort(key=lambda x: x[1], reverse=True)
if not tags:
return 'no tags in %s' % chan
return winnow(['%s (%d)' % row for row in tags], ordered=True)
def get_tags_by_nick(db, chan, nick):
tags = db.execute("select subject from tag where lower(nick)=lower(?)"
" and chan=?"
" order by lower(subject)", (nick, chan)).fetchall()
if tags:
return 'tags for "%s": ' % munge(nick, 1) + winnow([
tag[0] for tag in tags])
else:
return ''
def get_nicks_by_tagset(db, chan, tagset):
nicks = None
for tag in tagset.split('&'):
tag = tag.strip()
current_nicks = db.execute("select nick from tag where " +
"lower(subject)=lower(?)"
" and chan=?", (tag, chan)).fetchall()
if not current_nicks:
return "tag '%s' not found" % tag
if nicks is None:
nicks = set(current_nicks)
else:
nicks.intersection_update(current_nicks)
nicks = [munge(x[0], 1) for x in sorted(nicks)]
if not nicks:
return 'no nicks found with tags "%s"' % tagset
return 'nicks tagged "%s": ' % tagset + winnow(nicks)
@hook.command
def tag(inp, chan='', db=None):
'.tag <nick> <tag> -- marks <nick> as <tag> {related: .untag, .tags, .tagged, .is}'
db.execute('create table if not exists tag(chan, subject, nick)')
add = re.match(r'(\S+) (.+)', inp)
if add:
nick, subject = add.groups()
if nick.lower() == 'list':
return 'tag syntax has changed. try .tags or .tagged instead'
elif nick.lower() == 'del':
return 'tag syntax has changed. try ".untag %s" instead' % subject
return add_tag(db, chan, sanitize(nick), sanitize(subject))
else:
tags = get_tags_by_nick(db, chan, inp)
if tags:
return tags
else:
return tag.__doc__
@hook.command
def untag(inp, chan='', db=None):
'.untag <nick> <tag> -- unmarks <nick> as <tag> {related: .tag, .tags, .tagged, .is}'
delete = re.match(r'(\S+) (.+)$', inp)
if delete:
nick, del_tag = delete.groups()
return delete_tag(db, chan, nick, del_tag)
else:
return untag.__doc__
@hook.command
def tags(inp, chan='', db=None):
'.tags <nick>/list -- get list of tags for <nick>, or a list of tags {related: .tag, .untag, .tagged, .is}'
if inp == 'list':
return get_tag_counts_by_chan(db, chan)
tags = get_tags_by_nick(db, chan, inp)
if tags:
return tags
else:
return get_nicks_by_tagset(db, chan, inp)
@hook.command
def tagged(inp, chan='', db=None):
'.tagged <tag> [& tag...] -- get nicks marked as <tag> (separate multiple tags with &) {related: .tag, .untag, .tags, .is}'
return get_nicks_by_tagset(db, chan, inp)
@hook.command('is')
def is_tagged(inp, chan='', db=None):
'.is <nick> <tag> -- checks if <nick> has been marked as <tag> {related: .tag, .untag, .tags, .tagged}'
args = re.match(r'(\S+) (.+)$', inp)
if args:
nick, tag = args.groups()
found = db.execute("select 1 from tag"
" where lower(nick)=lower(?)"
" and lower(subject)=lower(?)"
" and chan=?", (nick, tag, chan)).fetchone()
if found:
return 'yes'
else:
return 'no'
else:
return is_tagged.__doc__
def distance(lat1, lon1, lat2, lon2):
deg_to_rad = math.pi / 180
lat1 *= deg_to_rad
lat2 *= deg_to_rad
lon1 *= deg_to_rad
lon2 *= deg_to_rad
R = 6371 # km
d = math.acos(math.sin(lat1) * math.sin(lat2) +
math.cos(lat1) * math.cos(lat2) *
math.cos(lon2 - lon1)) * R
return d
@hook.command(autohelp=False)
def near(inp, nick='', chan='', db=None):
try:
loc = db.execute("select lat, lon from location where chan=? and nick=lower(?)",
(chan, nick)).fetchone()
except db.OperationError:
loc = None
if loc is None:
return 'use .weather <loc> first to set your location'
lat, lon = loc
db.create_function('distance', 4, distance)
nearby = db.execute("select nick, distance(lat, lon, ?, ?) as dist from location where chan=?"
" and nick != lower(?) order by dist limit 20", (lat, lon, chan, nick)).fetchall()
in_miles = 'mi' in inp.lower()
out = '(km) '
factor = 1.0
if in_miles:
out = '(mi) '
factor = 0.621
while nearby and len(out) < 200:
nick, dist = nearby.pop(0)
out += '%s:%.0f ' % (munge(nick, 1), dist * factor)
return out
character_replacements = {
'a': 'ä',
# 'b': 'Б',
'c': 'ċ',
'd': 'đ',
'e': 'ë',
'f': 'ƒ',
'g': 'ġ',
'h': 'ħ',
'i': 'í',
'j': 'ĵ',
'k': 'ķ',
'l': 'ĺ',
# 'm': 'ṁ',
'n': 'ñ',
'o': 'ö',
'p': 'ρ',
# 'q': 'ʠ',
'r': 'ŗ',
's': 'š',
't': 'ţ',
'u': 'ü',
# 'v': '',
'w': 'ω',
'x': 'χ',
'y': 'ÿ',
'z': 'ź',
'A': 'Å',
'B': 'Β',
'C': 'Ç',
'D': 'Ď',
'E': 'Ē',
# 'F': 'Ḟ',
'G': 'Ġ',
'H': 'Ħ',
'I': 'Í',
'J': 'Ĵ',
'K': 'Ķ',
'L': 'Ĺ',
'M': 'Μ',
'N': 'Ν',
'O': 'Ö',
'P': 'Р',
# 'Q': 'Q',
'R': 'Ŗ',
'S': 'Š',
'T': 'Ţ',
'U': 'Ů',
# 'V': 'Ṿ',
'W': 'Ŵ',
'X': 'Χ',
'Y': 'Ỳ',
'Z': 'Ż'}
|
klusark/android_external_chromium_org | refs/heads/cm-11.0 | tools/perf/metrics/memory.py | 23 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
from metrics import Metric
class MemoryMetric(Metric):
"""MemoryMetric gathers memory statistics from the browser object."""
def __init__(self, browser):
super(MemoryMetric, self).__init__()
self._browser = browser
self._memory_stats = None
self._start_commit_charge = None
def Start(self, page=None, tab=None):
"""Record the initial value of 'SystemCommitCharge'."""
self._start_commit_charge = self._browser.memory_stats['SystemCommitCharge']
def Stop(self, page=None, tab=None):
"""Fetch the browser memory stats."""
assert self._start_commit_charge, 'Must call Start() first'
self._memory_stats = self._browser.memory_stats
def AddResults(self, tab, results):
"""Add summary results to the results object."""
assert self._memory_stats, 'Must call Stop() first'
if not self._memory_stats['Browser']:
return
metric = 'resident_set_size'
if sys.platform == 'win32':
metric = 'working_set'
def AddSummariesForProcessTypes(process_types_memory, process_type_trace):
"""Add all summaries to the results for a given set of process types.
Args:
process_types_memory: A list of process types, e.g. Browser, 'Renderer'
process_type_trace: The name of this set of process types in the output
"""
def AddSummary(value_name_memory, value_name_trace):
"""Add a summary to the results for a given statistic.
Args:
value_name_memory: Name of some statistic, e.g. VM, WorkingSetSize
value_name_trace: Name of this statistic to be used in the output
"""
if len(process_types_memory) > 1 and value_name_memory.endswith('Peak'):
return
values = []
for process_type_memory in process_types_memory:
stats = self._memory_stats[process_type_memory]
if value_name_memory in stats:
values.append(stats[value_name_memory])
if values:
results.AddSummary(value_name_trace + process_type_trace,
'bytes', sum(values), data_type='unimportant')
AddSummary('VM', 'vm_final_size_')
AddSummary('WorkingSetSize', 'vm_%s_final_size_' % metric)
AddSummary('PrivateDirty', 'vm_private_dirty_final_')
AddSummary('ProportionalSetSize', 'vm_proportional_set_size_final_')
AddSummary('VMPeak', 'vm_peak_size_')
AddSummary('WorkingSetSizePeak', '%s_peak_size_' % metric)
AddSummariesForProcessTypes(['Browser'], 'browser')
AddSummariesForProcessTypes(['Renderer'], 'renderer')
AddSummariesForProcessTypes(['Gpu'], 'gpu')
AddSummariesForProcessTypes(['Browser', 'Renderer', 'Gpu'], 'total')
end_commit_charge = self._memory_stats['SystemCommitCharge']
commit_charge_difference = end_commit_charge - self._start_commit_charge
results.AddSummary('commit_charge', 'kb', commit_charge_difference,
data_type='unimportant')
results.AddSummary('processes', 'count', self._memory_stats['ProcessCount'],
data_type='unimportant')
|
proxysh/Safejumper-for-Mac | refs/heads/master | buildlinux/env32/lib/python2.7/site-packages/Crypto/Hash/RIPEMD.py | 124 | # -*- coding: utf-8 -*-
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# 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.
# ===================================================================
"""RIPEMD-160 cryptographic hash algorithm.
RIPEMD-160_ produces the 160 bit digest of a message.
>>> from Crypto.Hash import RIPEMD
>>>
>>> h = RIPEMD.new()
>>> h.update(b'Hello')
>>> print h.hexdigest()
RIPEMD-160 stands for RACE Integrity Primitives Evaluation Message Digest
with a 160 bit digest. It was invented by Dobbertin, Bosselaers, and Preneel.
This algorithm is considered secure, although it has not been scrutinized as
extensively as SHA-1. Moreover, it provides an informal security level of just
80bits.
.. _RIPEMD-160: http://homes.esat.kuleuven.be/~bosselae/ripemd160.html
"""
_revision__ = "$Id$"
__all__ = ['new', 'digest_size', 'RIPEMD160Hash' ]
from Crypto.Util.py3compat import *
from Crypto.Hash.hashalgo import HashAlgo
import Crypto.Hash._RIPEMD160 as _RIPEMD160
hashFactory = _RIPEMD160
class RIPEMD160Hash(HashAlgo):
"""Class that implements a RIPMD-160 hash
:undocumented: block_size
"""
#: ASN.1 Object identifier (OID)::
#:
#: id-ripemd160 OBJECT IDENTIFIER ::= {
#: iso(1) identified-organization(3) teletrust(36)
#: algorithm(3) hashAlgorithm(2) ripemd160(1)
#: }
#:
#: This value uniquely identifies the RIPMD-160 algorithm.
oid = b("\x06\x05\x2b\x24\x03\x02\x01")
digest_size = 20
block_size = 64
def __init__(self, data=None):
HashAlgo.__init__(self, hashFactory, data)
def new(self, data=None):
return RIPEMD160Hash(data)
def new(data=None):
"""Return a fresh instance of the hash object.
:Parameters:
data : byte string
The very first chunk of the message to hash.
It is equivalent to an early call to `RIPEMD160Hash.update()`.
Optional.
:Return: A `RIPEMD160Hash` object
"""
return RIPEMD160Hash().new(data)
#: The size of the resulting hash in bytes.
digest_size = RIPEMD160Hash.digest_size
#: The internal block size of the hash algorithm in bytes.
block_size = RIPEMD160Hash.block_size
|
harshilasu/GraphicMelon | refs/heads/master | y/google-cloud-sdk/platform/gsutil/third_party/boto/tests/integration/datapipeline/test_layer1.py | 136 | #!/usr/bin/env python
# Copyright (c) 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
import time
from tests.unit import unittest
from boto.datapipeline import layer1
class TestDataPipeline(unittest.TestCase):
datapipeline = True
def setUp(self):
self.connection = layer1.DataPipelineConnection()
self.sample_pipeline_objects = [
{'fields': [
{'key': 'workerGroup', 'stringValue': 'MyworkerGroup'}],
'id': 'Default',
'name': 'Default'},
{'fields': [
{'key': 'startDateTime', 'stringValue': '2012-09-25T17:00:00'},
{'key': 'type', 'stringValue': 'Schedule'},
{'key': 'period', 'stringValue': '1 hour'},
{'key': 'endDateTime', 'stringValue': '2012-09-25T18:00:00'}],
'id': 'Schedule',
'name': 'Schedule'},
{'fields': [
{'key': 'type', 'stringValue': 'ShellCommandActivity'},
{'key': 'command', 'stringValue': 'echo hello'},
{'key': 'parent', 'refValue': 'Default'},
{'key': 'schedule', 'refValue': 'Schedule'}],
'id': 'SayHello',
'name': 'SayHello'}
]
self.connection.auth_service_name = 'datapipeline'
def create_pipeline(self, name, unique_id, description=None):
response = self.connection.create_pipeline(name, unique_id,
description)
pipeline_id = response['pipelineId']
self.addCleanup(self.connection.delete_pipeline, pipeline_id)
return pipeline_id
def get_pipeline_state(self, pipeline_id):
response = self.connection.describe_pipelines([pipeline_id])
for attr in response['pipelineDescriptionList'][0]['fields']:
if attr['key'] == '@pipelineState':
return attr['stringValue']
def test_can_create_and_delete_a_pipeline(self):
response = self.connection.create_pipeline('name', 'unique_id',
'description')
self.connection.delete_pipeline(response['pipelineId'])
def test_validate_pipeline(self):
pipeline_id = self.create_pipeline('name2', 'unique_id2')
self.connection.validate_pipeline_definition(
self.sample_pipeline_objects, pipeline_id)
def test_put_pipeline_definition(self):
pipeline_id = self.create_pipeline('name3', 'unique_id3')
self.connection.put_pipeline_definition(self.sample_pipeline_objects,
pipeline_id)
# We should now be able to get the pipeline definition and see
# that it matches what we put.
response = self.connection.get_pipeline_definition(pipeline_id)
objects = response['pipelineObjects']
self.assertEqual(len(objects), 3)
self.assertEqual(objects[0]['id'], 'Default')
self.assertEqual(objects[0]['name'], 'Default')
self.assertEqual(objects[0]['fields'],
[{'key': 'workerGroup', 'stringValue': 'MyworkerGroup'}])
def test_activate_pipeline(self):
pipeline_id = self.create_pipeline('name4', 'unique_id4')
self.connection.put_pipeline_definition(self.sample_pipeline_objects,
pipeline_id)
self.connection.activate_pipeline(pipeline_id)
attempts = 0
state = self.get_pipeline_state(pipeline_id)
while state != 'SCHEDULED' and attempts < 10:
time.sleep(10)
attempts += 1
state = self.get_pipeline_state(pipeline_id)
if attempts > 10:
self.fail("Pipeline did not become scheduled "
"after 10 attempts.")
objects = self.connection.describe_objects(['Default'], pipeline_id)
field = objects['pipelineObjects'][0]['fields'][0]
self.assertDictEqual(field, {'stringValue': 'COMPONENT', 'key': '@sphere'})
def test_list_pipelines(self):
pipeline_id = self.create_pipeline('name5', 'unique_id5')
pipeline_id_list = [p['id'] for p in
self.connection.list_pipelines()['pipelineIdList']]
self.assertTrue(pipeline_id in pipeline_id_list)
if __name__ == '__main__':
unittest.main()
|
iemejia/incubator-beam | refs/heads/master | sdks/python/setup.py | 1 | #
# 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.
#
"""Apache Beam SDK for Python setup file."""
from __future__ import absolute_import
from __future__ import print_function
import os
import platform
import sys
import warnings
from distutils.errors import DistutilsError
from distutils.version import StrictVersion
# Pylint and isort disagree here.
# pylint: disable=ungrouped-imports
import setuptools
from pkg_resources import DistributionNotFound
from pkg_resources import get_distribution
from pkg_resources import normalize_path
from pkg_resources import to_filename
from setuptools import Command
from setuptools.command.build_py import build_py
from setuptools.command.develop import develop
from setuptools.command.egg_info import egg_info
from setuptools.command.test import test
class mypy(Command):
user_options = []
def initialize_options(self):
"""Abstract method that is required to be overwritten"""
def finalize_options(self):
"""Abstract method that is required to be overwritten"""
def get_project_path(self):
self.run_command('egg_info')
# Build extensions in-place
self.reinitialize_command('build_ext', inplace=1)
self.run_command('build_ext')
ei_cmd = self.get_finalized_command("egg_info")
project_path = normalize_path(ei_cmd.egg_base)
return os.path.join(project_path, to_filename(ei_cmd.egg_name))
def run(self):
import subprocess
args = ['mypy', self.get_project_path()]
result = subprocess.call(args)
if result != 0:
raise DistutilsError("mypy exited with status %d" % result)
def get_version():
global_names = {}
exec( # pylint: disable=exec-used
open(os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'apache_beam/version.py')
).read(),
global_names
)
return global_names['__version__']
PACKAGE_NAME = 'apache-beam'
PACKAGE_VERSION = get_version()
PACKAGE_DESCRIPTION = 'Apache Beam SDK for Python'
PACKAGE_URL = 'https://beam.apache.org'
PACKAGE_DOWNLOAD_URL = 'https://pypi.python.org/pypi/apache-beam'
PACKAGE_AUTHOR = 'Apache Software Foundation'
PACKAGE_EMAIL = 'dev@beam.apache.org'
PACKAGE_KEYWORDS = 'apache beam'
PACKAGE_LONG_DESCRIPTION = '''
Apache Beam is a unified programming model for both batch and streaming
data processing, enabling efficient execution across diverse distributed
execution engines and providing extensibility points for connecting to
different technologies and user communities.
'''
REQUIRED_PIP_VERSION = '7.0.0'
_PIP_VERSION = get_distribution('pip').version
if StrictVersion(_PIP_VERSION) < StrictVersion(REQUIRED_PIP_VERSION):
warnings.warn(
"You are using version {0} of pip. " \
"However, version {1} is recommended.".format(
_PIP_VERSION, REQUIRED_PIP_VERSION
)
)
REQUIRED_CYTHON_VERSION = '0.28.1'
try:
_CYTHON_VERSION = get_distribution('cython').version
if StrictVersion(_CYTHON_VERSION) < StrictVersion(REQUIRED_CYTHON_VERSION):
warnings.warn(
"You are using version {0} of cython. " \
"However, version {1} is recommended.".format(
_CYTHON_VERSION, REQUIRED_CYTHON_VERSION
)
)
except DistributionNotFound:
# do nothing if Cython is not installed
pass
# Currently all compiled modules are optional (for performance only).
if platform.system() == 'Windows':
# Windows doesn't always provide int64_t.
cythonize = lambda *args, **kwargs: []
else:
try:
# pylint: disable=wrong-import-position
from Cython.Build import cythonize
except ImportError:
cythonize = lambda *args, **kwargs: []
REQUIRED_PACKAGES = [
# Apache Avro does not follow semantic versioning, so we should not auto
# upgrade on minor versions. Due to AVRO-2429, Dataflow still
# requires Avro 1.8.x.
'avro>=1.8.1,<1.10.0; python_version < "3.0"',
# Avro 1.9.2 for python3 was broken. The issue was fixed in version 1.9.2.1
'avro-python3>=1.8.1,!=1.9.2,<1.10.0; python_version >= "3.0"',
'crcmod>=1.7,<2.0',
# Dill doesn't have forwards-compatibility guarantees within minor version.
# Pickles created with a new version of dill may not unpickle using older
# version of dill. It is best to use the same version of dill on client and
# server, therefore list of allowed versions is very narrow.
# See: https://github.com/uqfoundation/dill/issues/341.
'dill>=0.3.1.1,<0.3.2',
'fastavro>=0.21.4,<0.24',
'funcsigs>=1.0.2,<2; python_version < "3.0"',
'future>=0.18.2,<1.0.0',
'futures>=3.2.0,<4.0.0; python_version < "3.0"',
'grpcio>=1.12.1,<2',
'hdfs>=2.1.0,<3.0.0',
'httplib2>=0.8,<0.18.0',
'mock>=1.0.1,<3.0.0',
'numpy>=1.14.3,<2',
'pymongo>=3.8.0,<4.0.0',
'oauth2client>=2.0.1,<4',
'protobuf>=3.5.0.post1,<4',
# [BEAM-6287] pyarrow is not supported on Windows for Python 2
('pyarrow>=0.15.1,<0.18.0; python_version >= "3.0" or '
'platform_system != "Windows"'),
'pydot>=1.2.0,<2',
'python-dateutil>=2.8.0,<3',
'pytz>=2018.3',
# [BEAM-5628] Beam VCF IO is not supported in Python 3.
'pyvcf>=0.6.8,<0.7.0; python_version < "3.0"',
# fixes and additions have been made since typing 3.5
'typing>=3.7.0,<3.8.0; python_version < "3.5.3"',
'typing-extensions>=3.7.0,<3.8.0',
]
# [BEAM-8181] pyarrow cannot be installed on 32-bit Windows platforms.
if sys.platform == 'win32' and sys.maxsize <= 2**32:
REQUIRED_PACKAGES = [
p for p in REQUIRED_PACKAGES if not p.startswith('pyarrow')
]
REQUIRED_TEST_PACKAGES = [
'freezegun>=0.3.12',
'nose>=1.3.7',
'nose_xunitmp>=0.4.1',
'pandas>=0.23.4,<0.25',
'parameterized>=0.7.1,<0.8.0',
# pyhamcrest==1.10.0 doesn't work on Py2. Beam still supports Py2.
# See: https://github.com/hamcrest/PyHamcrest/issues/131.
'pyhamcrest>=1.9,!=1.10.0,<2.0.0',
'pyyaml>=3.12,<6.0.0',
'requests_mock>=1.7,<2.0',
'tenacity>=5.0.2,<6.0',
'pytest>=4.4.0,<5.0',
'pytest-xdist>=1.29.0,<2',
'pytest-timeout>=1.3.3,<2',
]
GCP_REQUIREMENTS = [
'cachetools>=3.1.0,<4',
'google-apitools>=0.5.31,<0.5.32',
'google-cloud-datastore>=1.7.1,<1.8.0',
'google-cloud-pubsub>=0.39.0,<1.1.0',
# GCP packages required by tests
'google-cloud-bigquery>=1.6.0,<=1.24.0',
'google-cloud-core>=0.28.1,<2',
'google-cloud-bigtable>=0.31.1,<1.1.0',
'google-cloud-spanner>=1.13.0,<1.14.0',
'grpcio-gcp>=0.2.2,<1',
# GCP Packages required by ML functionality
'google-cloud-dlp>=0.12.0,<=0.13.0',
'google-cloud-language>=1.3.0,<2',
'google-cloud-videointelligence>=1.8.0,<1.14.0',
'google-cloud-vision>=0.38.0,<0.43.0',
]
INTERACTIVE_BEAM = [
'facets-overview>=1.0.0,<2',
'ipython>=5.8.0,<8',
'ipykernel>=5.2.0,<6',
'timeloop>=1.0.2,<2',
]
INTERACTIVE_BEAM_TEST = [
# notebok utils
'nbformat>=5.0.5,<6',
'nbconvert>=5.6.1,<6',
'jupyter-client>=6.1.2,<7',
# headless chrome based integration tests
'selenium>=3.141.0,<4',
'needle>=0.5.0,<1',
'chromedriver-binary>=80,<81',
# use a fixed major version of PIL for different python versions
'pillow>=7.1.1,<8',
]
AWS_REQUIREMENTS = [
'boto3 >=1.9'
]
# We must generate protos after setup_requires are installed.
def generate_protos_first(original_cmd):
try:
# See https://issues.apache.org/jira/browse/BEAM-2366
# pylint: disable=wrong-import-position
import gen_protos
class cmd(original_cmd, object):
def run(self):
gen_protos.generate_proto_files()
super(cmd, self).run()
return cmd
except ImportError:
warnings.warn("Could not import gen_protos, skipping proto generation.")
return original_cmd
python_requires = '>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*'
if sys.version_info[0] == 2:
warnings.warn(
'You are using Apache Beam with Python 2. '
'New releases of Apache Beam will soon support Python 3 only.')
setuptools.setup(
name=PACKAGE_NAME,
version=PACKAGE_VERSION,
description=PACKAGE_DESCRIPTION,
long_description=PACKAGE_LONG_DESCRIPTION,
url=PACKAGE_URL,
download_url=PACKAGE_DOWNLOAD_URL,
author=PACKAGE_AUTHOR,
author_email=PACKAGE_EMAIL,
packages=setuptools.find_packages(),
package_data={'apache_beam': [
'*/*.pyx', '*/*/*.pyx', '*/*.pxd', '*/*/*.pxd', 'testing/data/*.yaml',
'portability/api/*.yaml']},
ext_modules=cythonize([
'apache_beam/**/*.pyx',
'apache_beam/coders/coder_impl.py',
'apache_beam/metrics/cells.py',
'apache_beam/metrics/execution.py',
'apache_beam/runners/common.py',
'apache_beam/runners/worker/logger.py',
'apache_beam/runners/worker/opcounters.py',
'apache_beam/runners/worker/operations.py',
'apache_beam/transforms/cy_combiners.py',
'apache_beam/utils/counters.py',
'apache_beam/utils/windowed_value.py',
]),
install_requires=REQUIRED_PACKAGES,
python_requires=python_requires,
test_suite='nose.collector',
# BEAM-8840: Do NOT use tests_require or setup_requires.
extras_require={
'docs': ['Sphinx>=1.5.2,<2.0'],
'test': REQUIRED_TEST_PACKAGES,
'gcp': GCP_REQUIREMENTS,
'interactive': INTERACTIVE_BEAM,
'interactive_test': INTERACTIVE_BEAM_TEST,
'aws': AWS_REQUIREMENTS
},
zip_safe=False,
# PyPI package information.
classifiers=[
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
],
license='Apache License, Version 2.0',
keywords=PACKAGE_KEYWORDS,
entry_points={
'nose.plugins.0.10': [
'beam_test_plugin = test_config:BeamTestPlugin',
]},
cmdclass={
'build_py': generate_protos_first(build_py),
'develop': generate_protos_first(develop),
'egg_info': generate_protos_first(egg_info),
'test': generate_protos_first(test),
'mypy': generate_protos_first(mypy),
},
)
|
PyAngel/Sudoku | refs/heads/master | gui.py | 1 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import tkinter
import sudoku
from copy import deepcopy
class App():
def __init__(self, difficulty = 50, cheats = True):
self.resolution = (600, 600)
self.globalFont = ("Times", 30)
self.numberConf = {"font" : self.globalFont, "fg" : "black", "bg" : "white"}
self.originalConf = {"font" : self.globalFont, "fg" : "blue", "bg" : "white"}
self.noteConf = {"font" : ("Times", 12), "fg" : "gray", "bg" : "white"}
self.root = tkinter.Tk()
self.original = self.actual = self.solution = bytearray(81)
self.selected = None
self.notes = list([] for i in range(81))
self.difficulty = difficulty
self.cheats = cheats
#Widgets
self.sFrame = tkinter.Frame(bg = "red", padx = 1, pady = 1)
self.frames = [tkinter.Frame(self.sFrame, bg = "black") for i in range(9)]
self.labels = [tkinter.Label(self.frames[i // 27 * 3 + i % 9 // 3], fg = "blue", bg = "white") for i in range(81)]
#configuration
self.root.title("Sudoku")
self.root.geometry("{}x{}+{}+{}".format(self.resolution[0], self.resolution[1], 0, 0))
for i in range(3):
self.sFrame.columnconfigure(i, weight = 1, uniform = "same")
self.sFrame.rowconfigure(i, weight = 1, uniform = "same")
for j in range(9):
self.frames[j].columnconfigure(i, weight = 1, uniform = "same")
self.frames[j].rowconfigure(i, weight = 1, uniform = "same")
#Layout management
self.sFrame.pack(expand = True, fill = "both")
for x in range(9):
for y in range(9):
self.labels[x + 9 * y].grid(column = x % 3, row = y % 3, sticky = "NSEW", padx = 1, pady = 1)
for i in range(9):
self.frames[i].grid(column = i % 3, row = i // 3, sticky = "NSEW", padx = 1, pady = 1)
#Events
self.root.bind("<KeyPress>", self.listener)
self.root.bind_class("Label", "<1>", self.lclick)
self.root.bind_class("Label", "<2>", self.mclick)
self.root.bind_class("Label", "<3>", self.rclick)
self.root.bind("<Key-o>", self.restore)
self.root.bind("<Key-r>", self.restore)
self.root.bind("<Key-c>", self.clear_notes)
self.root.bind("<Key-g>", self.generate)
self.root.bind("<Key-s>", self.solve)
self.root.bind("<Key-n>", self.fill_notes)
self.root.bind("<Key-h>", self.help)
self.help()
self.root.after(50, self.generate)
self.root.mainloop()
def help(self, event = None):
print("\n" * 2)
print("Sudoku Gui".center(45, "-"))
print("Press O or R to restore the original sudoku\nPress C to clear all the notes\nPress G to generate a new sudoku\nPress H to see this help message\nLeft click to assign a number\nRight click to add/remove a note")
if self.cheats:
print("Cheat mode activated".center(45, "-"))
print("Press S to solve the sudoku\nPress N to automatically fill all the notes\nMiddle click to automatic define notes")
def generate(self, event = None):
self.original, self.solution = sudoku.generate(self.difficulty)
self.actual = deepcopy(self.original)
self.update_all()
def paint_background(self, color):
for i in self.labels:
i.config(bg = color)
def update_all(self):
for i in range(81): self.update(i)
self.check()
def update(self, n):
if self.actual[n] == 0: #notes
text = ""
for a, i in enumerate(sorted(self.notes[n])):
if a % 3 == 0 and a != 0:
text = text[:-1] + "\n"
text += "{};".format(i)
text = text[:-1]
self.labels[n].config(text = text)
self.labels[n].config(self.noteConf)
else: #number
if self.original[n] != 0:
self.labels[n].config(text = str(self.actual[n]))
self.labels[n].config(self.originalConf)
else:
self.labels[n].config(text = str(self.actual[n]))
self.labels[n].config(self.numberConf)
def check(self):
if not sudoku.islegit(self.actual): self.paint_background("yellow")
elif self.actual.count(0) == 0: self.paint_background("lime")
else: self.paint_background("white")
def listener(self, event):
if self.selected is not None:
if event.keysym in "123456789":
n = int(event.keysym)
if self.selected < 81: #Set number
self.actual[self.selected] = n
else: #Set note
if n in self.notes[self.selected % 81]: self.notes[self.selected % 81].remove(n)
else: self.notes[self.selected % 81].append(n)
self.actual[self.selected % 81] = 0
else:
self.actual[self.selected % 81] = 0
self.update(self.selected % 81)
self.check()
self.selected = None
def lclick(self, event):
try:
n = self.labels.index(event.widget)
if self.selected is not None:
self.labels[self.selected % 81].config(bg = "white")
if self.original[n] == 0:
self.selected = n
event.widget.config(bg = "cyan")
except ValueError: pass
def mclick(self, event):
if self.cheats:
try:
n = self.labels.index(event.widget)
self.notes[n] = list(sudoku.OPTIONS - set(sudoku.near(self.actual, n)))
self.actual[n] = 0
self.update(n)
self.check()
except ValueError: pass
def rclick(self, event):
try:
n = self.labels.index(event.widget)
if self.selected is not None:
self.labels[self.selected % 81].config(bg = "white")
if self.original[n] == 0:
self.selected = n + 81
event.widget.config(bg = "#DDDDAA")
except ValueError: pass
def fill_notes(self, event):
if self.cheats:
for i in range(81): self.notes[i] = list(sudoku.OPTIONS - set(sudoku.near(self.actual, i)))
self.update_all()
def clear_notes(self, event):
self.notes = list([] for i in range(81))
self.update_all()
def solve(self, event):
if self.cheats:
self.actual = deepcopy(self.solution)
self.update_all()
def restore(self, event):
self.actual = deepcopy(self.original)
self.clear_notes(event)
if __name__ == "__main__":
App() |
dmsuehir/spark-tk | refs/heads/master | python/sparktk/models/timeseries/arimax.py | 14 | # vim: set encoding=utf-8
# Copyright (c) 2016 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
ARIMAX (Autoregressive Integrated Moving Average with Exogeneous Variables) Model
"""
from sparktk.loggers import log_load; log_load(__name__); del log_load
from sparktk.lazyloader import implicit
from sparktk.propobj import PropertiesObject
def train(frame, ts_column, x_columns, p, d, q, x_max_lag, include_original_x=True, include_intercept=True, init_params=None):
"""
Creates Autoregressive Integrated Moving Average with Explanatory Variables (ARIMAX) Model from the specified
time series values.
Given a time series, fits an non-seasonal Autoregressive Integrated Moving Average with Explanatory Variables
(ARIMAX) model of order (p, d, q) where p represents the autoregression terms, d represents the order of differencing
and q represents the moving average error terms. X_max_lag represents the maximum lag order for exogenous variables.
If include_original_x is true, the model is fitted with an original exogenous variables. If includeIntercept is true,
the model is fitted with an intercept.
Parameters
----------
:param frame: (Frame) Frame used for training.
:param ts_column: (str) Name of the column that contains the time series values.
:param x_columns: (List(str)) Names of the column(s) that contain the values of exogenous regressors.
:param p: (int) Autoregressive order
:param d: (int) Differencing order
:param q: (int) Moving average order
:param x_max_lag: (int) The maximum lag order for exogenous variables.
:param include_original_x: (Optional(boolean)) If True, the model is fit with an original exogenous variables
(intercept for exogenous variables). Default is True.
:param include_intercept: (Optional(boolean)) If True, the model is fit with an intercept. Default is True.
:param init_params: (Optional(List[float]) A set of user provided initial parameters for optimization. If the
list is empty (default), initialized using Hannan-Rissanen algorithm. If provided, order
of parameter should be: intercept term, AR parameters (in increasing order of lag), MA
parameters (in increasing order of lag) and paramteres for exogenous variables (in
increasing order of lag).
:return: (ArimaxModel) Trained ARIMAX model
"""
if not isinstance(ts_column, basestring):
raise TypeError("'ts_column' should be a string (name of the column that has the timeseries value).")
if not isinstance(x_columns, list) or not all(isinstance(c, str) for c in x_columns):
raise TypeError("'x_columns' should be a list of strings (names of the exogenous columns).")
elif len(x_columns) <= 0:
raise ValueError("'x_columns' should not be empty.")
if not isinstance(p, int):
raise TypeError("'p' parameter must be an integer.")
if not isinstance(d, int):
raise TypeError("'d' parameter must be an integer.")
if not isinstance(q, int):
raise TypeError("'q' parameter must be an integer.")
if not isinstance(x_max_lag, int):
raise TypeError("'x_max_lag' should be an integer.")
if not isinstance(include_original_x, bool):
raise TypeError("'include_original_x' parameter must be a boolean")
if not isinstance(include_intercept, bool):
raise TypeError("'include_intercept' parameter must be a boolean")
if init_params is not None:
if not isinstance(init_params, list):
raise TypeError("'init_params' parameter must be a list")
tc = frame._tc
_scala_obj = _get_scala_obj(tc)
scala_x_columns = tc.jutils.convert.to_scala_vector_string(x_columns)
scala_init_params = tc.jutils.convert.to_scala_option_list_double(init_params)
scala_model = _scala_obj.train(frame._scala, ts_column, scala_x_columns, p, d, q, x_max_lag, include_original_x, include_intercept, scala_init_params)
return ArimaxModel(tc, scala_model)
def load(path, tc=implicit):
"""load ARIMAXModel from given path"""
if tc is implicit:
implicit.error("tc")
return tc.load(path, ArimaxModel)
def _get_scala_obj(tc):
"""Gets reference to the ARIMAX model scala object"""
return tc.sc._jvm.org.trustedanalytics.sparktk.models.timeseries.arimax.ArimaxModel
class ArimaxModel(PropertiesObject):
"""
A trained ARIMAX model.
Example
-------
Data from Lichman, M. (2013). UCI Machine Learning Repository [http://archive.ics.uci.edu/ml].
Irvine, CA: University of California, School of Information and Computer Science.
Consider the following model trained and tested on the sample data set in *frame* 'frame'.
The frame has five columns where "CO_GT" is the time series value and "C6H6_GT", "PT08_S2_NMHC"
and "T" are exogenous inputs.
CO_GT - True hourly averaged concentration CO in mg/m^3
C6H6_GT - True hourly averaged Benzene concentration in microg/m^3
PT08_S2_NMHC - Titania hourly averaged sensor response (nominally NMHC targeted)
T - Temperature in C
<hide>
>>> schema = [("CO_GT", float),("C6H6_GT", float),("PT08_S2_NMHC", float),("T", float)]
>>> frame = tc.frame.create([[2.6, 11.9, 1046.0, 13.6],
... [2.0, 9.4, 955.0, 13.3],
... [2.2, 9.0, 939.0, 11.9],
... [2.2, 9.2, 948.0, 11.0],
... [1.6, 6.5, 836.0, 11.2],
... [1.2, 4.7, 750.0, 11.2],
... [1.2, 3.6, 690.0, 11.3],
... [1.0, 3.3, 672.0, 10.7],
... [2.9, 2.3, 609.0, 10.7],
... [2.6, 1.7, 561.0, 10.3],
... [2.0, 1.3, 527.0, 10.1],
... [2.7, 1.1, 512.0, 11.0],
... [2.7, 1.6, 553.0, 10.5],
... [1.1, 3.2, 667.0, 10.2],
... [2.0, 8.0, 900.0, 10.8],
... [2.2, 9.5, 960.0, 10.5],
... [2.7, 6.3, 827.0, 10.8],
... [2.5, 5.0, 762.0, 10.5],
... [2.6, 5.2, 774.0, 9.5],
... [2.9, 7.3, 869.0, 8.3]],
... schema=schema, validate_schema=True)
-etc-
</hide>
>>> frame.inspect()
[#] CO_GT C6H6_GT PT08_S2_NMHC T
=======================================
[0] 2.6 11.9 1046.0 13.6
[1] 2.0 9.4 955.0 13.3
[2] 2.2 9.0 939.0 11.9
[3] 2.2 9.2 948.0 11.0
[4] 1.6 6.5 836.0 11.2
[5] 1.2 4.7 750.0 11.2
[6] 1.2 3.6 690.0 11.3
[7] 1.0 3.3 672.0 10.7
[8] 2.9 2.3 609.0 10.7
[9] 2.6 1.7 561.0 10.3
>>> model = tc.models.timeseries.arimax.train(frame, "CO_GT", ["C6H6_GT", "PT08_S2_NMHC", "T"], 1, 1, 1, 1, True, False)
<progress>
>>> model.c
0.24886373113659435
>>> model.ar
[-0.8612398115782316]
>>> model.ma
[-0.45556700539598505]
>>> model.xreg
[0.09496697769170012, -0.00043805552312166737, 0.0006888829627820128, 0.8523170824191132, -0.017901092786057428, 0.017936687425751337]
In this example, we will call predict using the same frame that was used for training, again specifying the name
of the time series column and the names of the columns that contain exogenous regressors.
>>> predicted_frame = model.predict(frame, "CO_GT", ["C6H6_GT", "PT08_S2_NMHC", "T"])
<progress>
The predicted_frame that's return has a new column called *predicted_y*. This column contains the predicted
time series values.
>>> predicted_frame.column_names
[u'CO_GT', u'C6H6_GT', u'PT08_S2_NMHC', u'T', u'predicted_y']
>>> predicted_frame.inspect(columns=["CO_GT","predicted_y"])
[#] CO_GT predicted_y
=========================
[0] 2.6 2.83896716391
[1] 2.0 2.89056663602
[2] 2.2 2.84550712171
[3] 2.2 2.88445194591
[4] 1.6 2.85091111286
[5] 1.2 2.8798667019
[6] 1.2 2.85451566607
[7] 1.0 2.87634898739
[8] 2.9 2.85726970866
[9] 2.6 2.87356376648
The trained model can be saved to be used later:
>>> model_path = "sandbox/savedArimaxModel"
>>> model.save(model_path)
The saved model can be loaded through the tk context and then used for forecasting values the same way
that the original model was used.
>>> loaded_model = tc.load(model_path)
>>> predicted_frame = loaded_model.predict(frame, "CO_GT", ["C6H6_GT", "PT08_S2_NMHC", "T"])
>>> predicted_frame.inspect(columns=["CO_GT","predicted_y"])
[#] CO_GT predicted_y
=========================
[0] 2.6 2.83896716391
[1] 2.0 2.89056663602
[2] 2.2 2.84550712171
[3] 2.2 2.88445194591
[4] 1.6 2.85091111286
[5] 1.2 2.8798667019
[6] 1.2 2.85451566607
[7] 1.0 2.87634898739
[8] 2.9 2.85726970866
[9] 2.6 2.87356376648
The trained model can also be exported to a .mar file, to be used with the scoring engine:
>>> canonical_path = model.export_to_mar("sandbox/arimax.mar")
<hide>
>>> import os
>>> assert(os.path.isfile(canonical_path))
</hide>
"""
def __init__(self, tc, scala_model):
self._tc = tc
tc.jutils.validate_is_jvm_instance_of(scala_model, _get_scala_obj(tc))
self._scala = scala_model
@staticmethod
def _from_scala(tc, scala_model):
"""
Load an ARIMAX model
:param tc: (TkContext) Active TkContext
:param scala_model: (scala ArimaxModel) Scala model to load.
:return: (ArimaxModel) ArimaxModel object
"""
return ArimaxModel(tc, scala_model)
@property
def p(self):
"""
Autoregressive order
"""
return self._scala.p()
@property
def d(self):
"""
Differencing order
"""
return self._scala.d()
@property
def q(self):
"""
Moving average order
"""
return self._scala.q()
@property
def x_max_lag(self):
"""
The maximum lag order for exogenous variables.
"""
return self._scala.xregMaxLag()
@property
def includeIntercept(self):
"""
A boolean flag indicating if the intercept should be included.
"""
return self._scala.includeIntercept()
@property
def includeOriginalXreg(self):
"""
A boolean flag indicating if the non-lagged exogenous variables should be included.
"""
return self._scala.includeOriginalXreg()
@property
def init_params(self):
"""
A set of user provided initial parameters for optimization
"""
return self._scala.initParams()
@property
def c(self):
"""
Intercept
"""
return self._scala.c()
@property
def ar(self):
"""
Coefficient values from the trained model (AR with increasing degrees).
"""
return list(self._tc.jutils.convert.from_scala_seq(self._scala.ar()))
@property
def ma(self):
"""
Coefficient values from the trained model (MA with increasing degrees).
"""
return list(self._tc.jutils.convert.from_scala_seq(self._scala.ma()))
@property
def xreg(self):
"""
Coefficient values from the trained model fox exogenous variables with increasing degrees.
"""
return list(self._tc.jutils.convert.from_scala_seq(self._scala.xreg()))
def predict(self, frame, ts_column, x_columns):
"""
New frame with column of predicted y values
Predict the time series values for a test frame, based on the specified x values. Creates a new frame
revision with the existing columns and a new predicted_y column.
Parameters
----------
:param frame: (Frame) Frame used for predicting the ts values
:param ts_column: (str) Name of the time series column
:param x_columns: (List[str]) Names of the column(s) that contain the values of the exogenous inputs.
:return: (Frame) A new frame containing the original frame's columns and a column *predictied_y*
"""
if not isinstance(frame, self._tc.frame.Frame):
raise TypeError("'frame' parameter should be a spark-tk Frame object.")
if not isinstance(ts_column, basestring):
raise TypeError("'ts_column' parameter should be a string (name of the column that has the timeseries value).")
if not isinstance(x_columns, list) or not all(isinstance(c, str) for c in x_columns):
raise TypeError("'x_columns' parameter should be a list of strings (names of the exogenous columns).")
elif len(x_columns) <= 0:
raise ValueError("'x_columns' should not be empty.")
scala_x_columns = self._tc.jutils.convert.to_scala_vector_string(x_columns)
from sparktk.frame.frame import Frame
return Frame(self._tc, self._scala.predict(frame._scala, ts_column, scala_x_columns))
def save(self, path):
"""
Save the trained model to the specified path
Parameters
----------
:param path: Path to save
"""
self._scala.save(self._tc._scala_sc, path)
def export_to_mar(self, path):
"""
Exports the trained model as a model archive (.mar) to the specified path.
Parameters
----------
:param path: (str) Path to save the trained model
:returns (str) Full path to the saved .mar file
"""
if not isinstance(path, basestring):
raise TypeError("path parameter must be a str, but received %s" % type(path))
return self._scala.exportToMar(self._tc._scala_sc, path)
del PropertiesObject
|
yamila-moreno/django | refs/heads/master | django/core/management/commands/inspectdb.py | 86 | from __future__ import unicode_literals
import keyword
import re
from collections import OrderedDict
from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS, connections
class Command(BaseCommand):
help = "Introspects the database tables in the given database and outputs a Django model module."
requires_system_checks = False
db_module = 'django.db'
def add_arguments(self, parser):
parser.add_argument('--database', action='store', dest='database',
default=DEFAULT_DB_ALIAS, help='Nominates a database to '
'introspect. Defaults to using the "default" database.')
def handle(self, **options):
try:
for line in self.handle_inspection(options):
self.stdout.write("%s\n" % line)
except NotImplementedError:
raise CommandError("Database inspection isn't supported for the currently selected database backend.")
def handle_inspection(self, options):
connection = connections[options['database']]
# 'table_name_filter' is a stealth option
table_name_filter = options.get('table_name_filter')
table2model = lambda table_name: re.sub(r'[^a-zA-Z0-9]', '', table_name.title())
strip_prefix = lambda s: s[1:] if s.startswith("u'") else s
with connection.cursor() as cursor:
yield "# This is an auto-generated Django model module."
yield "# You'll have to do the following manually to clean this up:"
yield "# * Rearrange models' order"
yield "# * Make sure each model has one field with primary_key=True"
yield (
"# * Remove `managed = False` lines if you wish to allow "
"Django to create, modify, and delete the table"
)
yield "# Feel free to rename the models, but don't rename db_table values or field names."
yield "from __future__ import unicode_literals"
yield ''
yield 'from %s import models' % self.db_module
known_models = []
for table_name in connection.introspection.table_names(cursor):
if table_name_filter is not None and callable(table_name_filter):
if not table_name_filter(table_name):
continue
yield ''
yield ''
yield 'class %s(models.Model):' % table2model(table_name)
known_models.append(table2model(table_name))
try:
relations = connection.introspection.get_relations(cursor, table_name)
except NotImplementedError:
relations = {}
try:
indexes = connection.introspection.get_indexes(cursor, table_name)
except NotImplementedError:
indexes = {}
try:
constraints = connection.introspection.get_constraints(cursor, table_name)
except NotImplementedError:
constraints = {}
used_column_names = [] # Holds column names used in the table so far
for row in connection.introspection.get_table_description(cursor, table_name):
comment_notes = [] # Holds Field notes, to be displayed in a Python comment.
extra_params = OrderedDict() # Holds Field parameters such as 'db_column'.
column_name = row[0]
is_relation = column_name in relations
att_name, params, notes = self.normalize_col_name(
column_name, used_column_names, is_relation)
extra_params.update(params)
comment_notes.extend(notes)
used_column_names.append(att_name)
# Add primary_key and unique, if necessary.
if column_name in indexes:
if indexes[column_name]['primary_key']:
extra_params['primary_key'] = True
elif indexes[column_name]['unique']:
extra_params['unique'] = True
if is_relation:
rel_to = "self" if relations[column_name][1] == table_name else table2model(relations[column_name][1])
if rel_to in known_models:
field_type = 'ForeignKey(%s' % rel_to
else:
field_type = "ForeignKey('%s'" % rel_to
else:
# Calling `get_field_type` to get the field type string and any
# additional parameters and notes.
field_type, field_params, field_notes = self.get_field_type(connection, table_name, row)
extra_params.update(field_params)
comment_notes.extend(field_notes)
field_type += '('
# Don't output 'id = meta.AutoField(primary_key=True)', because
# that's assumed if it doesn't exist.
if att_name == 'id' and extra_params == {'primary_key': True}:
if field_type == 'AutoField(':
continue
elif field_type == 'IntegerField(' and not connection.features.can_introspect_autofield:
comment_notes.append('AutoField?')
# Add 'null' and 'blank', if the 'null_ok' flag was present in the
# table description.
if row[6]: # If it's NULL...
if field_type == 'BooleanField(':
field_type = 'NullBooleanField('
else:
extra_params['blank'] = True
extra_params['null'] = True
field_desc = '%s = %s%s' % (
att_name,
# Custom fields will have a dotted path
'' if '.' in field_type else 'models.',
field_type,
)
if extra_params:
if not field_desc.endswith('('):
field_desc += ', '
field_desc += ', '.join(
'%s=%s' % (k, strip_prefix(repr(v)))
for k, v in extra_params.items())
field_desc += ')'
if comment_notes:
field_desc += ' # ' + ' '.join(comment_notes)
yield ' %s' % field_desc
for meta_line in self.get_meta(table_name, constraints):
yield meta_line
def normalize_col_name(self, col_name, used_column_names, is_relation):
"""
Modify the column name to make it Python-compatible as a field name
"""
field_params = {}
field_notes = []
new_name = col_name.lower()
if new_name != col_name:
field_notes.append('Field name made lowercase.')
if is_relation:
if new_name.endswith('_id'):
new_name = new_name[:-3]
else:
field_params['db_column'] = col_name
new_name, num_repl = re.subn(r'\W', '_', new_name)
if num_repl > 0:
field_notes.append('Field renamed to remove unsuitable characters.')
if new_name.find('__') >= 0:
while new_name.find('__') >= 0:
new_name = new_name.replace('__', '_')
if col_name.lower().find('__') >= 0:
# Only add the comment if the double underscore was in the original name
field_notes.append("Field renamed because it contained more than one '_' in a row.")
if new_name.startswith('_'):
new_name = 'field%s' % new_name
field_notes.append("Field renamed because it started with '_'.")
if new_name.endswith('_'):
new_name = '%sfield' % new_name
field_notes.append("Field renamed because it ended with '_'.")
if keyword.iskeyword(new_name):
new_name += '_field'
field_notes.append('Field renamed because it was a Python reserved word.')
if new_name[0].isdigit():
new_name = 'number_%s' % new_name
field_notes.append("Field renamed because it wasn't a valid Python identifier.")
if new_name in used_column_names:
num = 0
while '%s_%d' % (new_name, num) in used_column_names:
num += 1
new_name = '%s_%d' % (new_name, num)
field_notes.append('Field renamed because of name conflict.')
if col_name != new_name and field_notes:
field_params['db_column'] = col_name
return new_name, field_params, field_notes
def get_field_type(self, connection, table_name, row):
"""
Given the database connection, the table name, and the cursor row
description, this routine will return the given field type name, as
well as any additional keyword parameters and notes for the field.
"""
field_params = OrderedDict()
field_notes = []
try:
field_type = connection.introspection.get_field_type(row[1], row)
except KeyError:
field_type = 'TextField'
field_notes.append('This field type is a guess.')
# This is a hook for data_types_reverse to return a tuple of
# (field_type, field_params_dict).
if type(field_type) is tuple:
field_type, new_params = field_type
field_params.update(new_params)
# Add max_length for all CharFields.
if field_type == 'CharField' and row[3]:
field_params['max_length'] = int(row[3])
if field_type == 'DecimalField':
if row[4] is None or row[5] is None:
field_notes.append(
'max_digits and decimal_places have been guessed, as this '
'database handles decimal fields as float')
field_params['max_digits'] = row[4] if row[4] is not None else 10
field_params['decimal_places'] = row[5] if row[5] is not None else 5
else:
field_params['max_digits'] = row[4]
field_params['decimal_places'] = row[5]
return field_type, field_params, field_notes
def get_meta(self, table_name, constraints):
"""
Return a sequence comprising the lines of code necessary
to construct the inner Meta class for the model corresponding
to the given database table name.
"""
unique_together = []
for index, params in constraints.items():
if params['unique']:
columns = params['columns']
if len(columns) > 1:
# we do not want to include the u"" or u'' prefix
# so we build the string rather than interpolate the tuple
tup = '(' + ', '.join("'%s'" % c for c in columns) + ')'
unique_together.append(tup)
meta = ["",
" class Meta:",
" managed = False",
" db_table = '%s'" % table_name]
if unique_together:
tup = '(' + ', '.join(unique_together) + ',)'
meta += [" unique_together = %s" % tup]
return meta
|
chris-ch/coinarb | refs/heads/master | bf-arb-pylab/scripts/testbitfinex.py | 1 | import json
import asyncio
import websockets
WSS_BITFINEX_2 = 'wss://api2.bitfinex.com:3000/ws'
async def consumer_handler(pair):
async with websockets.connect(WSS_BITFINEX_2) as websocket:
subscription = json.dumps({
'event': 'subscribe',
'channel': 'book',
'symbol': pair,
'prec': 'P0', # precision level
'freq': 'F0', # realtime
})
await websocket.send(subscription)
event_info = json.loads(await websocket.recv())
print(event_info['event'], event_info['version'])
subscription_status = json.loads(await websocket.recv())
subscribed_status = subscription_status['event']
channel_id = subscription_status['chanId']
print(subscribed_status, channel_id)
# Order Book
orderbook_snapshot = json.loads(await websocket.recv())
print("> {}".format(orderbook_snapshot))
while True:
orderbook_update = json.loads(await websocket.recv())
if orderbook_update[1] == 'hb':
continue
channel_id, price, count, amount = orderbook_update
print("> {}, {}, {}".format(price, count, amount))
def main():
asyncio.get_event_loop().run_until_complete(consumer_handler('BTCUSD'))
if __name__ == '__main__':
main() |
smartdj/chrome-sync-server | refs/heads/master | google/protobuf/python/google/protobuf/descriptor_database.py | 230 | # Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# http://code.google.com/p/protobuf/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Provides a container for DescriptorProtos."""
__author__ = 'matthewtoia@google.com (Matt Toia)'
class DescriptorDatabase(object):
"""A container accepting FileDescriptorProtos and maps DescriptorProtos."""
def __init__(self):
self._file_desc_protos_by_file = {}
self._file_desc_protos_by_symbol = {}
def Add(self, file_desc_proto):
"""Adds the FileDescriptorProto and its types to this database.
Args:
file_desc_proto: The FileDescriptorProto to add.
"""
self._file_desc_protos_by_file[file_desc_proto.name] = file_desc_proto
package = file_desc_proto.package
for message in file_desc_proto.message_type:
self._file_desc_protos_by_symbol.update(
(name, file_desc_proto) for name in _ExtractSymbols(message, package))
for enum in file_desc_proto.enum_type:
self._file_desc_protos_by_symbol[
'.'.join((package, enum.name))] = file_desc_proto
def FindFileByName(self, name):
"""Finds the file descriptor proto by file name.
Typically the file name is a relative path ending to a .proto file. The
proto with the given name will have to have been added to this database
using the Add method or else an error will be raised.
Args:
name: The file name to find.
Returns:
The file descriptor proto matching the name.
Raises:
KeyError if no file by the given name was added.
"""
return self._file_desc_protos_by_file[name]
def FindFileContainingSymbol(self, symbol):
"""Finds the file descriptor proto containing the specified symbol.
The symbol should be a fully qualified name including the file descriptor's
package and any containing messages. Some examples:
'some.package.name.Message'
'some.package.name.Message.NestedEnum'
The file descriptor proto containing the specified symbol must be added to
this database using the Add method or else an error will be raised.
Args:
symbol: The fully qualified symbol name.
Returns:
The file descriptor proto containing the symbol.
Raises:
KeyError if no file contains the specified symbol.
"""
return self._file_desc_protos_by_symbol[symbol]
def _ExtractSymbols(desc_proto, package):
"""Pulls out all the symbols from a descriptor proto.
Args:
desc_proto: The proto to extract symbols from.
package: The package containing the descriptor type.
Yields:
The fully qualified name found in the descriptor.
"""
message_name = '.'.join((package, desc_proto.name))
yield message_name
for nested_type in desc_proto.nested_type:
for symbol in _ExtractSymbols(nested_type, message_name):
yield symbol
for enum_type in desc_proto.enum_type:
yield '.'.join((message_name, enum_type.name))
|
rdeheele/odoo | refs/heads/master | addons/purchase_double_validation/__openerp__.py | 52 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name' : 'Double Validation on Purchases',
'version' : '1.1',
'category': 'Purchase Management',
'images' : ['images/purchase_validation.jpeg'],
'depends' : ['base','purchase'],
'author' : 'OpenERP SA',
'description': """
Double-validation for purchases exceeding minimum amount.
=========================================================
This module modifies the purchase workflow in order to validate purchases that
exceeds minimum amount set by configuration wizard.
""",
'website': 'https://www.odoo.com/page/purchase',
'data': [
'purchase_double_validation_workflow.xml',
'purchase_double_validation_installer.xml',
'purchase_double_validation_view.xml',
],
'test': [
'test/purchase_double_validation_demo.yml',
'test/purchase_double_validation_test.yml'
],
'demo': [],
'installable': True,
'auto_install': False
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
tomhenderson/ns-3-dev-testing | refs/heads/master | src/nix-vector-routing/bindings/modulegen__gcc_ILP32.py | 28 | 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()
|
paulproteus/django | refs/heads/master | tests/regressiontests/admin_scripts/simple_app/models.py | 153 | from __future__ import absolute_import
from ..complex_app.models.bar import Bar
|
btabibian/scikit-learn | refs/heads/master | examples/cluster/plot_mini_batch_kmeans.py | 86 | """
====================================================================
Comparison of the K-Means and MiniBatchKMeans clustering algorithms
====================================================================
We want to compare the performance of the MiniBatchKMeans and KMeans:
the MiniBatchKMeans is faster, but gives slightly different results (see
:ref:`mini_batch_kmeans`).
We will cluster a set of data, first with KMeans and then with
MiniBatchKMeans, and plot the results.
We will also plot the points that are labelled differently between the two
algorithms.
"""
print(__doc__)
import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import MiniBatchKMeans, KMeans
from sklearn.metrics.pairwise import pairwise_distances_argmin
from sklearn.datasets.samples_generator import make_blobs
##############################################################################
# Generate sample data
np.random.seed(0)
batch_size = 45
centers = [[1, 1], [-1, -1], [1, -1]]
n_clusters = len(centers)
X, labels_true = make_blobs(n_samples=3000, centers=centers, cluster_std=0.7)
##############################################################################
# Compute clustering with Means
k_means = KMeans(init='k-means++', n_clusters=3, n_init=10)
t0 = time.time()
k_means.fit(X)
t_batch = time.time() - t0
##############################################################################
# Compute clustering with MiniBatchKMeans
mbk = MiniBatchKMeans(init='k-means++', n_clusters=3, batch_size=batch_size,
n_init=10, max_no_improvement=10, verbose=0)
t0 = time.time()
mbk.fit(X)
t_mini_batch = time.time() - t0
##############################################################################
# Plot result
fig = plt.figure(figsize=(8, 3))
fig.subplots_adjust(left=0.02, right=0.98, bottom=0.05, top=0.9)
colors = ['#4EACC5', '#FF9C34', '#4E9A06']
# We want to have the same colors for the same cluster from the
# MiniBatchKMeans and the KMeans algorithm. Let's pair the cluster centers per
# closest one.
k_means_cluster_centers = np.sort(k_means.cluster_centers_, axis=0)
mbk_means_cluster_centers = np.sort(mbk.cluster_centers_, axis=0)
k_means_labels = pairwise_distances_argmin(X, k_means_cluster_centers)
mbk_means_labels = pairwise_distances_argmin(X, mbk_means_cluster_centers)
order = pairwise_distances_argmin(k_means_cluster_centers,
mbk_means_cluster_centers)
# KMeans
ax = fig.add_subplot(1, 3, 1)
for k, col in zip(range(n_clusters), colors):
my_members = k_means_labels == k
cluster_center = k_means_cluster_centers[k]
ax.plot(X[my_members, 0], X[my_members, 1], 'w',
markerfacecolor=col, marker='.')
ax.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col,
markeredgecolor='k', markersize=6)
ax.set_title('KMeans')
ax.set_xticks(())
ax.set_yticks(())
plt.text(-3.5, 1.8, 'train time: %.2fs\ninertia: %f' % (
t_batch, k_means.inertia_))
# MiniBatchKMeans
ax = fig.add_subplot(1, 3, 2)
for k, col in zip(range(n_clusters), colors):
my_members = mbk_means_labels == order[k]
cluster_center = mbk_means_cluster_centers[order[k]]
ax.plot(X[my_members, 0], X[my_members, 1], 'w',
markerfacecolor=col, marker='.')
ax.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col,
markeredgecolor='k', markersize=6)
ax.set_title('MiniBatchKMeans')
ax.set_xticks(())
ax.set_yticks(())
plt.text(-3.5, 1.8, 'train time: %.2fs\ninertia: %f' %
(t_mini_batch, mbk.inertia_))
# Initialise the different array to all False
different = (mbk_means_labels == 4)
ax = fig.add_subplot(1, 3, 3)
for k in range(n_clusters):
different += ((k_means_labels == k) != (mbk_means_labels == order[k]))
identic = np.logical_not(different)
ax.plot(X[identic, 0], X[identic, 1], 'w',
markerfacecolor='#bbbbbb', marker='.')
ax.plot(X[different, 0], X[different, 1], 'w',
markerfacecolor='m', marker='.')
ax.set_title('Difference')
ax.set_xticks(())
ax.set_yticks(())
plt.show()
|
chronicwaffle/PokemonGo-DesktopMap | refs/heads/master | app/pywin/Lib/idlelib/idle_test/test_warning.py | 49 | '''Test warnings replacement in PyShell.py and run.py.
This file could be expanded to include traceback overrides
(in same two modules). If so, change name.
Revise if output destination changes (http://bugs.python.org/issue18318).
Make sure warnings module is left unaltered (http://bugs.python.org/issue18081).
'''
import unittest
from test.test_support import captured_stderr
import warnings
# Try to capture default showwarning before Idle modules are imported.
showwarning = warnings.showwarning
# But if we run this file within idle, we are in the middle of the run.main loop
# and default showwarnings has already been replaced.
running_in_idle = 'idle' in showwarning.__name__
from idlelib import run
from idlelib import PyShell as shell
# The following was generated from PyShell.idle_formatwarning
# and checked as matching expectation.
idlemsg = '''
Warning (from warnings module):
File "test_warning.py", line 99
Line of code
UserWarning: Test
'''
shellmsg = idlemsg + ">>> "
class RunWarnTest(unittest.TestCase):
@unittest.skipIf(running_in_idle, "Does not work when run within Idle.")
def test_showwarnings(self):
self.assertIs(warnings.showwarning, showwarning)
run.capture_warnings(True)
self.assertIs(warnings.showwarning, run.idle_showwarning_subproc)
run.capture_warnings(False)
self.assertIs(warnings.showwarning, showwarning)
def test_run_show(self):
with captured_stderr() as f:
run.idle_showwarning_subproc(
'Test', UserWarning, 'test_warning.py', 99, f, 'Line of code')
# The following uses .splitlines to erase line-ending differences
self.assertEqual(idlemsg.splitlines(), f.getvalue().splitlines())
class ShellWarnTest(unittest.TestCase):
@unittest.skipIf(running_in_idle, "Does not work when run within Idle.")
def test_showwarnings(self):
self.assertIs(warnings.showwarning, showwarning)
shell.capture_warnings(True)
self.assertIs(warnings.showwarning, shell.idle_showwarning)
shell.capture_warnings(False)
self.assertIs(warnings.showwarning, showwarning)
def test_idle_formatter(self):
# Will fail if format changed without regenerating idlemsg
s = shell.idle_formatwarning(
'Test', UserWarning, 'test_warning.py', 99, 'Line of code')
self.assertEqual(idlemsg, s)
def test_shell_show(self):
with captured_stderr() as f:
shell.idle_showwarning(
'Test', UserWarning, 'test_warning.py', 99, f, 'Line of code')
self.assertEqual(shellmsg.splitlines(), f.getvalue().splitlines())
if __name__ == '__main__':
unittest.main(verbosity=2, exit=False)
|
nazeehshoura/crawler | refs/heads/master | env/lib/python2.7/site-packages/pip/_vendor/html5lib/treewalkers/__init__.py | 1229 | """A collection of modules for iterating through different kinds of
tree, generating tokens identical to those produced by the tokenizer
module.
To create a tree walker for a new type of tree, you need to do
implement a tree walker object (called TreeWalker by convention) that
implements a 'serialize' method taking a tree as sole argument and
returning an iterator generating tokens.
"""
from __future__ import absolute_import, division, unicode_literals
import sys
from ..utils import default_etree
treeWalkerCache = {}
def getTreeWalker(treeType, implementation=None, **kwargs):
"""Get a TreeWalker class for various types of tree with built-in support
treeType - the name of the tree type required (case-insensitive). Supported
values are:
"dom" - The xml.dom.minidom DOM implementation
"pulldom" - The xml.dom.pulldom event stream
"etree" - A generic walker for tree implementations exposing an
elementtree-like interface (known to work with
ElementTree, cElementTree and lxml.etree).
"lxml" - Optimized walker for lxml.etree
"genshi" - a Genshi stream
implementation - (Currently applies to the "etree" tree type only). A module
implementing the tree type e.g. xml.etree.ElementTree or
cElementTree."""
treeType = treeType.lower()
if treeType not in treeWalkerCache:
if treeType in ("dom", "pulldom"):
name = "%s.%s" % (__name__, treeType)
__import__(name)
mod = sys.modules[name]
treeWalkerCache[treeType] = mod.TreeWalker
elif treeType == "genshi":
from . import genshistream
treeWalkerCache[treeType] = genshistream.TreeWalker
elif treeType == "lxml":
from . import lxmletree
treeWalkerCache[treeType] = lxmletree.TreeWalker
elif treeType == "etree":
from . import etree
if implementation is None:
implementation = default_etree
# XXX: NEVER cache here, caching is done in the etree submodule
return etree.getETreeModule(implementation, **kwargs).TreeWalker
return treeWalkerCache.get(treeType)
|
mne-tools/mne-python | refs/heads/main | examples/connectivity/mne_inverse_connectivity_spectrum.py | 6 | """
==============================================================
Compute full spectrum source space connectivity between labels
==============================================================
The connectivity is computed between 4 labels across the spectrum
between 7.5 Hz and 40 Hz.
"""
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)
import matplotlib.pyplot as plt
import mne
from mne.datasets import sample
from mne.minimum_norm import apply_inverse_epochs, read_inverse_operator
from mne.connectivity import spectral_connectivity
print(__doc__)
data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
fname_raw = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
fname_event = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
# Load data
inverse_operator = read_inverse_operator(fname_inv)
raw = mne.io.read_raw_fif(fname_raw)
events = mne.read_events(fname_event)
# Add a bad channel
raw.info['bads'] += ['MEG 2443']
# Pick MEG channels
picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True,
exclude='bads')
# Define epochs for left-auditory condition
event_id, tmin, tmax = 1, -0.2, 0.5
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13,
eog=150e-6))
# Compute inverse solution and for each epoch. By using "return_generator=True"
# stcs will be a generator object instead of a list.
snr = 1.0 # use lower SNR for single epochs
lambda2 = 1.0 / snr ** 2
method = "dSPM" # use dSPM method (could also be MNE or sLORETA)
stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method,
pick_ori="normal", return_generator=True)
# Read some labels
names = ['Aud-lh', 'Aud-rh', 'Vis-lh', 'Vis-rh']
labels = [mne.read_label(data_path + '/MEG/sample/labels/%s.label' % name)
for name in names]
# Average the source estimates within each label using sign-flips to reduce
# signal cancellations, also here we return a generator
src = inverse_operator['src']
label_ts = mne.extract_label_time_course(stcs, labels, src, mode='mean_flip',
return_generator=True)
fmin, fmax = 7.5, 40.
sfreq = raw.info['sfreq'] # the sampling frequency
con, freqs, times, n_epochs, n_tapers = spectral_connectivity(
label_ts, method='wpli2_debiased', mode='multitaper', sfreq=sfreq,
fmin=fmin, fmax=fmax, mt_adaptive=True, n_jobs=1)
n_rows, n_cols = con.shape[:2]
fig, axes = plt.subplots(n_rows, n_cols, sharex=True, sharey=True)
for i in range(n_rows):
for j in range(i + 1):
if i == j:
axes[i, j].set_axis_off()
continue
axes[i, j].plot(freqs, con[i, j, :])
axes[j, i].plot(freqs, con[i, j, :])
if j == 0:
axes[i, j].set_ylabel(names[i])
axes[0, i].set_title(names[i])
if i == (n_rows - 1):
axes[i, j].set_xlabel(names[j])
axes[i, j].set(xlim=[fmin, fmax], ylim=[-0.2, 1])
axes[j, i].set(xlim=[fmin, fmax], ylim=[-0.2, 1])
# Show band limits
for f in [8, 12, 18, 35]:
axes[i, j].axvline(f, color='k')
axes[j, i].axvline(f, color='k')
plt.tight_layout()
plt.show()
|
dsprenkels/servo | refs/heads/master | tests/wpt/web-platform-tests/XMLHttpRequest/resources/conditional.py | 205 | def main(request, response):
tag = request.GET.first("tag", None)
match = request.headers.get("If-None-Match", None)
date = request.GET.first("date", "")
modified = request.headers.get("If-Modified-Since", None)
if tag:
response.headers.set("ETag", '"%s"' % tag)
elif date:
response.headers.set("Last-Modified", date)
if ((match is not None and match == tag) or
(modified is not None and modified == date)):
response.status = (304, "SUPERCOOL")
return ""
else:
response.headers.set("Content-Type", "text/plain")
return "MAYBE NOT"
|
wandec/grr | refs/heads/master | server/data_server/master.py | 4 | #!/usr/bin/env python
"""Data master specific classes."""
import socket
import threading
import urlparse
import urllib3
from urllib3 import connectionpool
import logging
from grr.lib import config_lib
from grr.lib import rdfvalue
from grr.lib import utils
from grr.server.data_server import constants
from grr.server.data_server import rebalance
from grr.server.data_server import utils as sutils
class DataMasterError(Exception):
"""Raised when some critical error happens in the data master."""
pass
class DataServer(object):
"""DataServer objects for each data server."""
def __init__(self, location, index):
# Parse location.
loc = urlparse.urlparse(location, scheme="http")
offline = rdfvalue.DataServerState.Status.OFFLINE
state = rdfvalue.DataServerState(size=0, load=0, status=offline)
self.server_info = rdfvalue.DataServerInformation(index=index,
address=loc.hostname,
port=loc.port,
state=state)
self.registered = False
self.removed = False
logging.info("Configured DataServer on %s:%d", self.Address(), self.Port())
def SetInitialInterval(self, num_servers):
self.server_info.interval = sutils.CreateStartInterval(self.Index(),
num_servers)
def IsRegistered(self):
return self.registered
def Matches(self, addr, port):
if isinstance(addr, list):
if self.Address() not in addr:
return False
else:
# Handle hostnames and IPs
if socket.gethostbyname(self.Address()) != socket.gethostbyname(addr):
return False
return self.Port() == port
def Register(self):
"""Once the server is registered, it is allowed to use the database."""
self.registered = True
def Deregister(self):
self.registered = False
def Port(self):
return self.server_info.port
def Address(self):
return self.server_info.address
def Index(self):
return self.server_info.index
def SetIndex(self, newindex):
self.server_info.index = newindex
def Size(self):
return self.server_info.state.size
def Load(self):
return self.server_info.state.load
def Interval(self):
return self.server_info.interval
def SetInterval(self, start, end):
self.server_info.interval.start = start
self.server_info.interval.end = end
def GetInfo(self):
return self.server_info
def UpdateState(self, newstate):
"""Update state of server."""
self.server_info.state = newstate
def Remove(self):
self.removed = True
def WasRemoved(self):
return self.removed
class DataMaster(object):
"""DataMaster information."""
def __init__(self, myport, service):
self.service = service
stores = config_lib.CONFIG["Dataserver.server_list"]
if not stores:
logging.error("Dataserver.server_list is empty: no data servers will"
" be available")
raise DataMasterError("Dataserver.server_list is empty")
self.servers = [DataServer(loc, idx) for idx, loc in enumerate(stores)]
self.registered_count = 0
# Load server mapping.
self.mapping = self.service.LoadServerMapping()
if not self.mapping:
# Bootstrap mapping.
# Each server information is linked to its corresponding object.
# Updating the data server object will reflect immediately on
# the mapping.
for server in self.servers:
server.SetInitialInterval(len(self.servers))
servers_info = [server.server_info for server in self.servers]
self.mapping = rdfvalue.DataServerMapping(version=0,
num_servers=len(self.servers),
servers=servers_info)
self.service.SaveServerMapping(self.mapping, create_pathing=True)
else:
# Check mapping and configuration matching.
if len(self.mapping.servers) != len(self.servers):
raise DataMasterError("Server mapping does not correspond "
"to the configuration.")
for server in self.servers:
self._EnsureServerInMapping(server)
# Create locks.
self.server_lock = threading.Lock()
# Register the master.
self.myself = self.servers[0]
if self.myself.Port() == myport:
self._DoRegisterServer(self.myself)
else:
logging.warning("First server in Dataserver.server_list is not the "
"master. Found port '%i' but my port is '%i'. If you"
" really are running master, you may want to specify"
" flag --port %i.",
self.myself.Port(), myport, myport)
raise DataMasterError("First server in Dataserver.server_list must be "
"the master.")
# Start database measuring thread.
sleep = config_lib.CONFIG["Dataserver.stats_frequency"]
self.periodic_thread = utils.InterruptableThread(
target=self._PeriodicThread, sleep_time=sleep)
self.periodic_thread.start()
# Holds current rebalance operation.
self.rebalance = None
self.rebalance_pool = []
def LoadMapping(self):
return self.mapping
def _PeriodicThread(self):
"""Periodically update our state and store the mappings."""
ok = rdfvalue.DataServerState.Status.AVAILABLE
num_components, avg_component = self.service.GetComponentInformation()
state = rdfvalue.DataServerState(size=self.service.Size(),
load=0,
status=ok,
num_components=num_components,
avg_component=avg_component)
self.myself.UpdateState(state)
self.service.SaveServerMapping(self.mapping)
def _EnsureServerInMapping(self, server):
"""Ensure that the data server exists on the mapping."""
index = server.Index()
server_info = self.mapping.servers[index]
if server_info.address != server.Address():
return False
if server_info.port != server.Port():
return False
# Change underlying server information.
server.server_info = server_info
def RegisterServer(self, addr, port):
"""Register incoming data server. Return server object."""
for server in self.servers:
if server == self.myself:
continue
if server.Matches(addr, port):
with self.server_lock:
if server.IsRegistered():
return None
else:
self._DoRegisterServer(server)
return server
return None
def HasServer(self, addr, port):
"""Checks if a given server is already in the set."""
for server in self.servers:
if server.Matches(addr, port):
return server
return None
def _DoRegisterServer(self, server):
self.registered_count += 1
server.Register()
logging.info("Registered server %s:%d", server.Address(), server.Port())
if self.AllRegistered():
logging.info("All data servers have registered!")
def DeregisterServer(self, server):
"""Deregister a data server."""
with self.server_lock:
server.Deregister()
self.registered_count -= 1
def AllRegistered(self):
"""Check if all servers have registered."""
return self.registered_count == len(self.servers)
def Stop(self):
self.service.SaveServerMapping(self.mapping)
self.periodic_thread.Stop()
def SetRebalancing(self, reb):
"""Sets a new rebalance operation and starts communication with servers."""
self.rebalance = reb
self.rebalance_pool = []
try:
for serv in self.servers:
pool = connectionpool.HTTPConnectionPool(serv.Address(),
port=serv.Port())
self.rebalance_pool.append(pool)
except urllib3.exceptions.MaxRetryError:
self.CancelRebalancing()
return False
return True
def CancelRebalancing(self):
self.rebalance = None
for pool in self.rebalance_pool:
pool.close()
self.rebalance_pool = []
def IsRebalancing(self):
return self.rebalance
def AddServer(self, addr, port):
"""Add new server to the group."""
server = DataServer("http://%s:%d" % (addr, port), len(self.servers))
self.servers.append(server)
server.SetInterval(constants.MAX_RANGE, constants.MAX_RANGE)
self.mapping.servers.Append(server.GetInfo())
self.mapping.num_servers += 1
# At this point, the new server is now part of the group.
return server
def RemoveServer(self, removed_server):
"""Remove a server. Returns None if server interval is not empty."""
interval = removed_server.Interval()
# Interval range must be 0.
if interval.start != interval.end:
return None
# Update ids of other servers.
newserverlist = []
for serv in self.servers:
if serv == removed_server:
continue
if serv.Index() > removed_server.Index():
serv.SetIndex(serv.Index() - 1)
newserverlist.append(serv.GetInfo())
# Change list of servers.
self.mapping.servers = newserverlist
self.mapping.num_servers -= 1
self.servers.pop(removed_server.Index())
self.DeregisterServer(removed_server)
removed_server.Remove()
return removed_server
def SyncMapping(self, skip=None):
"""Syncs mapping with other servers."""
pools = []
try:
# Update my state.
self._PeriodicThread()
for serv in self.servers[1:]:
if skip and serv in skip:
continue
pool = connectionpool.HTTPConnectionPool(serv.Address(),
port=serv.Port())
pools.append((serv, pool))
body = self.mapping.SerializeToString()
headers = {"Content-Length": len(body)}
for serv, pool in pools:
res = pool.urlopen("POST", "/servers/sync", headers=headers,
body=body)
if res.status != constants.RESPONSE_OK:
logging.warning("Could not sync with server %s:%d", serv.Address(),
serv.Port())
return False
state = rdfvalue.DataServerState()
state.ParseFromString(res.data)
serv.UpdateState(state)
except urllib3.exceptions.MaxRetryError:
return False
finally:
for _, pool in pools:
pool.close()
return True
def FetchRebalanceInformation(self):
"""Asks data servers for number of changes for rebalancing."""
body = self.rebalance.SerializeToString()
size = len(body)
headers = {"Content-Length": size}
for pool in self.rebalance_pool:
try:
res = pool.urlopen("POST", "/rebalance/statistics", headers=headers,
body=body)
if res.status != constants.RESPONSE_OK:
self.CancelRebalancing()
return False
reb = rdfvalue.DataServerRebalance()
reb.ParseFromString(res.data)
ls = list(reb.moving)
if ls:
logging.warning("Moving %d", ls[0])
self.rebalance.moving.Append(ls[0])
else:
self.CancelRebalancing()
return False
except urllib3.exceptions.MaxRetryError:
self.CancelRebalancing()
return False
return True
def CopyRebalanceFiles(self):
"""Tell servers to copy files to the corresponding servers."""
body = self.rebalance.SerializeToString()
size = len(body)
headers = {"Content-Length": size}
for pool in self.rebalance_pool:
try:
res = pool.urlopen("POST", "/rebalance/copy", headers=headers,
body=body)
if res.status != constants.RESPONSE_OK:
self.CancelRebalancing()
return False
except urllib3.exceptions.MaxRetryError:
self.CancelRebalancing()
return False
return True
def RebalanceCommit(self):
"""Tell servers to commit rebalance changes."""
# Save rebalance information to a file, so we can recover later.
rebalance.SaveCommitInformation(self.rebalance)
body = self.rebalance.SerializeToString()
size = len(body)
headers = {"Content-Length": size}
for i, pool in enumerate(self.rebalance_pool):
try:
res = pool.urlopen("POST", "/rebalance/perform", headers=headers,
body=body)
if res.status != constants.RESPONSE_OK:
logging.error("Server %d failed to perform transaction %s", i,
self.rebalance.id)
self.CancelRebalancing()
return None
stat = rdfvalue.DataServerState()
stat.ParseFromString(res.data)
data_server = self.servers[i]
data_server.UpdateState(stat)
except urllib3.exceptions.MaxRetryError:
self.CancelRebalancing()
return None
# Update server intervals.
mapping = self.rebalance.mapping
for i, serv in enumerate(list(self.mapping.servers)):
serv.interval = mapping.servers[i].interval
self.rebalance.mapping = self.mapping
self.service.SaveServerMapping(self.mapping)
# We can finally delete the temporary file, since we have succeeded.
rebalance.DeleteCommitInformation(self.rebalance)
rebalance.RemoveDirectory(self.rebalance)
self.CancelRebalancing()
return self.mapping
|
luckasfb/android_kernel_iocean_x7 | refs/heads/master | tools/perf/python/twatch.py | 7370 | #! /usr/bin/python
# -*- python -*-
# -*- coding: utf-8 -*-
# twatch - Experimental use of the perf python interface
# Copyright (C) 2011 Arnaldo Carvalho de Melo <acme@redhat.com>
#
# This application is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2.
#
# This application 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.
import perf
def main():
cpus = perf.cpu_map()
threads = perf.thread_map()
evsel = perf.evsel(task = 1, comm = 1, mmap = 0,
wakeup_events = 1, watermark = 1,
sample_id_all = 1,
sample_type = perf.SAMPLE_PERIOD | perf.SAMPLE_TID | perf.SAMPLE_CPU | perf.SAMPLE_TID)
evsel.open(cpus = cpus, threads = threads);
evlist = perf.evlist(cpus, threads)
evlist.add(evsel)
evlist.mmap()
while True:
evlist.poll(timeout = -1)
for cpu in cpus:
event = evlist.read_on_cpu(cpu)
if not event:
continue
print "cpu: %2d, pid: %4d, tid: %4d" % (event.sample_cpu,
event.sample_pid,
event.sample_tid),
print event
if __name__ == '__main__':
main()
|
bsmrstu-warriors/Moytri--The-Drone-Aider | refs/heads/master | ExtLibs/Mavlink/pymavlink/generator/mavtemplate.py | 68 | #!/usr/bin/env python
'''
simple templating system for mavlink generator
Copyright Andrew Tridgell 2011
Released under GNU GPL version 3 or later
'''
from .mavparse import MAVParseError
class MAVTemplate(object):
'''simple templating system'''
def __init__(self,
start_var_token="${",
end_var_token="}",
start_rep_token="${{",
end_rep_token="}}",
trim_leading_lf=True,
checkmissing=True):
self.start_var_token = start_var_token
self.end_var_token = end_var_token
self.start_rep_token = start_rep_token
self.end_rep_token = end_rep_token
self.trim_leading_lf = trim_leading_lf
self.checkmissing = checkmissing
def find_end(self, text, start_token, end_token, ignore_end_token=None):
'''find the of a token.
Returns the offset in the string immediately after the matching end_token'''
if not text.startswith(start_token):
raise MAVParseError("invalid token start")
offset = len(start_token)
nesting = 1
while nesting > 0:
idx1 = text[offset:].find(start_token)
idx2 = text[offset:].find(end_token)
# Check for false positives due to another similar token
# For example, make sure idx2 points to the second '}' in ${{field: ${name}}}
if ignore_end_token:
combined_token = ignore_end_token + end_token
if text[offset+idx2:offset+idx2+len(combined_token)] == combined_token:
idx2 += len(ignore_end_token)
if idx1 == -1 and idx2 == -1:
raise MAVParseError("token nesting error")
if idx1 == -1 or idx1 > idx2:
offset += idx2 + len(end_token)
nesting -= 1
else:
offset += idx1 + len(start_token)
nesting += 1
return offset
def find_var_end(self, text):
'''find the of a variable'''
return self.find_end(text, self.start_var_token, self.end_var_token)
def find_rep_end(self, text):
'''find the of a repitition'''
return self.find_end(text, self.start_rep_token, self.end_rep_token, ignore_end_token=self.end_var_token)
def substitute(self, text, subvars={},
trim_leading_lf=None, checkmissing=None):
'''substitute variables in a string'''
if trim_leading_lf is None:
trim_leading_lf = self.trim_leading_lf
if checkmissing is None:
checkmissing = self.checkmissing
# handle repititions
while True:
subidx = text.find(self.start_rep_token)
if subidx == -1:
break
endidx = self.find_rep_end(text[subidx:])
if endidx == -1:
raise MAVParseError("missing end macro in %s" % text[subidx:])
part1 = text[0:subidx]
part2 = text[subidx+len(self.start_rep_token):subidx+(endidx-len(self.end_rep_token))]
part3 = text[subidx+endidx:]
a = part2.split(':')
field_name = a[0]
rest = ':'.join(a[1:])
v = None
if isinstance(subvars, dict):
v = subvars.get(field_name, None)
else:
v = getattr(subvars, field_name, None)
if v is None:
raise MAVParseError('unable to find field %s' % field_name)
t1 = part1
for f in v:
t1 += self.substitute(rest, f, trim_leading_lf=False, checkmissing=False)
if len(v) != 0 and t1[-1] in ["\n", ","]:
t1 = t1[:-1]
t1 += part3
text = t1
if trim_leading_lf:
if text[0] == '\n':
text = text[1:]
while True:
idx = text.find(self.start_var_token)
if idx == -1:
return text
endidx = text[idx:].find(self.end_var_token)
if endidx == -1:
raise MAVParseError('missing end of variable: %s' % text[idx:idx+10])
varname = text[idx+2:idx+endidx]
if isinstance(subvars, dict):
if not varname in subvars:
if checkmissing:
raise MAVParseError("unknown variable in '%s%s%s'" % (
self.start_var_token, varname, self.end_var_token))
return text[0:idx+endidx] + self.substitute(text[idx+endidx:], subvars,
trim_leading_lf=False, checkmissing=False)
value = subvars[varname]
else:
value = getattr(subvars, varname, None)
if value is None:
if checkmissing:
raise MAVParseError("unknown variable in '%s%s%s'" % (
self.start_var_token, varname, self.end_var_token))
return text[0:idx+endidx] + self.substitute(text[idx+endidx:], subvars,
trim_leading_lf=False, checkmissing=False)
text = text.replace("%s%s%s" % (self.start_var_token, varname, self.end_var_token), str(value))
return text
def write(self, file, text, subvars={}, trim_leading_lf=True):
'''write to a file with variable substitution'''
file.write(self.substitute(text, subvars=subvars, trim_leading_lf=trim_leading_lf))
|
mcltn/ansible-modules-extras | refs/heads/devel | cloud/amazon/ec2_vpc_nacl.py | 33 | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
module: ec2_vpc_nacl
short_description: create and delete Network ACLs.
description:
- Read the AWS documentation for Network ACLS
U(http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_ACLs.html)
version_added: "2.2"
options:
name:
description:
- Tagged name identifying a network ACL.
required: true
vpc_id:
description:
- VPC id of the requesting VPC.
required: true
subnets:
description:
- The list of subnets that should be associated with the network ACL.
- Must be specified as a list
- Each subnet can be specified as subnet ID, or its tagged name.
required: false
egress:
description:
- A list of rules for outgoing traffic.
- Each rule must be specified as a list.
required: false
ingress:
description:
- List of rules for incoming traffic.
- Each rule must be specified as a list.
required: false
tags:
description:
- Dictionary of tags to look for and apply when creating a network ACL.
required: false
state:
description:
- Creates or modifies an existing NACL
- Deletes a NACL and reassociates subnets to the default NACL
required: false
choices: ['present', 'absent']
default: present
author: Mike Mochan(@mmochan)
extends_documentation_fragment: aws
requirements: [ botocore, boto3, json ]
'''
EXAMPLES = '''
# Complete example to create and delete a network ACL
# that allows SSH, HTTP and ICMP in, and all traffic out.
- name: "Create and associate production DMZ network ACL with DMZ subnets"
ec2_vpc_nacl:
vpc_id: vpc-12345678
name: prod-dmz-nacl
region: ap-southeast-2
subnets: ['prod-dmz-1', 'prod-dmz-2']
tags:
CostCode: CC1234
Project: phoenix
Description: production DMZ
ingress: [
# rule no, protocol, allow/deny, cidr, icmp_code, icmp_type,
# port from, port to
[100, 'tcp', 'allow', '0.0.0.0/0', null, null, 22, 22],
[200, 'tcp', 'allow', '0.0.0.0/0', null, null, 80, 80],
[300, 'icmp', 'allow', '0.0.0.0/0', 0, 8],
]
egress: [
[100, 'all', 'allow', '0.0.0.0/0', null, null, null, null]
]
state: 'present'
- name: "Remove the ingress and egress rules - defaults to deny all"
ec2_vpc_nacl:
vpc_id: vpc-12345678
name: prod-dmz-nacl
region: ap-southeast-2
subnets:
- prod-dmz-1
- prod-dmz-2
tags:
CostCode: CC1234
Project: phoenix
Description: production DMZ
state: present
- name: "Remove the NACL subnet associations and tags"
ec2_vpc_nacl:
vpc_id: 'vpc-12345678'
name: prod-dmz-nacl
region: ap-southeast-2
state: present
- name: "Delete nacl and subnet associations"
ec2_vpc_nacl:
vpc_id: vpc-12345678
name: prod-dmz-nacl
state: absent
'''
RETURN = '''
task:
description: The result of the create, or delete action.
returned: success
type: dictionary
'''
try:
import json
import botocore
import boto3
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
# Common fields for the default rule that is contained within every VPC NACL.
DEFAULT_RULE_FIELDS = {
'RuleNumber': 32767,
'RuleAction': 'deny',
'CidrBlock': '0.0.0.0/0',
'Protocol': '-1'
}
DEFAULT_INGRESS = dict(DEFAULT_RULE_FIELDS.items() + [('Egress', False)])
DEFAULT_EGRESS = dict(DEFAULT_RULE_FIELDS.items() + [('Egress', True)])
# VPC-supported IANA protocol numbers
# http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
PROTOCOL_NUMBERS = {'all': -1, 'icmp': 1, 'tcp': 6, 'udp': 17, }
#Utility methods
def icmp_present(entry):
if len(entry) == 6 and entry[1] == 'icmp' or entry[1] == 1:
return True
def load_tags(module):
tags = []
if module.params.get('tags'):
for name, value in module.params.get('tags').iteritems():
tags.append({'Key': name, 'Value': str(value)})
tags.append({'Key': "Name", 'Value': module.params.get('name')})
else:
tags.append({'Key': "Name", 'Value': module.params.get('name')})
return tags
def subnets_removed(nacl_id, subnets, client, module):
results = find_acl_by_id(nacl_id, client, module)
associations = results['NetworkAcls'][0]['Associations']
subnet_ids = [assoc['SubnetId'] for assoc in associations]
return [subnet for subnet in subnet_ids if subnet not in subnets]
def subnets_added(nacl_id, subnets, client, module):
results = find_acl_by_id(nacl_id, client, module)
associations = results['NetworkAcls'][0]['Associations']
subnet_ids = [assoc['SubnetId'] for assoc in associations]
return [subnet for subnet in subnets if subnet not in subnet_ids]
def subnets_changed(nacl, client, module):
changed = False
response = {}
vpc_id = module.params.get('vpc_id')
nacl_id = nacl['NetworkAcls'][0]['NetworkAclId']
subnets = subnets_to_associate(nacl, client, module)
if not subnets:
default_nacl_id = find_default_vpc_nacl(vpc_id, client, module)[0]
subnets = find_subnet_ids_by_nacl_id(nacl_id, client, module)
if subnets:
replace_network_acl_association(default_nacl_id, subnets, client, module)
changed = True
return changed
changed = False
return changed
subs_added = subnets_added(nacl_id, subnets, client, module)
if subs_added:
replace_network_acl_association(nacl_id, subs_added, client, module)
changed = True
subs_removed = subnets_removed(nacl_id, subnets, client, module)
if subs_removed:
default_nacl_id = find_default_vpc_nacl(vpc_id, client, module)[0]
replace_network_acl_association(default_nacl_id, subs_removed, client, module)
changed = True
return changed
def nacls_changed(nacl, client, module):
changed = False
params = dict()
params['egress'] = module.params.get('egress')
params['ingress'] = module.params.get('ingress')
nacl_id = nacl['NetworkAcls'][0]['NetworkAclId']
nacl = describe_network_acl(client, module)
entries = nacl['NetworkAcls'][0]['Entries']
tmp_egress = [entry for entry in entries if entry['Egress'] is True and DEFAULT_EGRESS !=entry]
tmp_ingress = [entry for entry in entries if entry['Egress'] is False]
egress = [rule for rule in tmp_egress if DEFAULT_EGRESS != rule]
ingress = [rule for rule in tmp_ingress if DEFAULT_INGRESS != rule]
if rules_changed(egress, params['egress'], True, nacl_id, client, module):
changed = True
if rules_changed(ingress, params['ingress'], False, nacl_id, client, module):
changed = True
return changed
def tags_changed(nacl_id, client, module):
changed = False
tags = dict()
if module.params.get('tags'):
tags = module.params.get('tags')
tags['Name'] = module.params.get('name')
nacl = find_acl_by_id(nacl_id, client, module)
if nacl['NetworkAcls']:
nacl_values = [t.values() for t in nacl['NetworkAcls'][0]['Tags']]
nacl_tags = [item for sublist in nacl_values for item in sublist]
tag_values = [[key, str(value)] for key, value in tags.iteritems()]
tags = [item for sublist in tag_values for item in sublist]
if sorted(nacl_tags) == sorted(tags):
changed = False
return changed
else:
delete_tags(nacl_id, client, module)
create_tags(nacl_id, client, module)
changed = True
return changed
return changed
def rules_changed(aws_rules, param_rules, Egress, nacl_id, client, module):
changed = False
rules = list()
for entry in param_rules:
rules.append(process_rule_entry(entry, Egress))
if rules == aws_rules:
return changed
else:
removed_rules = [x for x in aws_rules if x not in rules]
if removed_rules:
params = dict()
for rule in removed_rules:
params['NetworkAclId'] = nacl_id
params['RuleNumber'] = rule['RuleNumber']
params['Egress'] = Egress
delete_network_acl_entry(params, client, module)
changed = True
added_rules = [x for x in rules if x not in aws_rules]
if added_rules:
for rule in added_rules:
rule['NetworkAclId'] = nacl_id
create_network_acl_entry(rule, client, module)
changed = True
return changed
def process_rule_entry(entry, Egress):
params = dict()
params['RuleNumber'] = entry[0]
params['Protocol'] = str(PROTOCOL_NUMBERS[entry[1]])
params['RuleAction'] = entry[2]
params['Egress'] = Egress
params['CidrBlock'] = entry[3]
if icmp_present(entry):
params['IcmpTypeCode'] = {"Type": int(entry[4]), "Code": int(entry[5])}
else:
if entry[6] or entry[7]:
params['PortRange'] = {"From": entry[6], 'To': entry[7]}
return params
def restore_default_associations(assoc_ids, default_nacl_id, client, module):
if assoc_ids:
params = dict()
params['NetworkAclId'] = default_nacl_id[0]
for assoc_id in assoc_ids:
params['AssociationId'] = assoc_id
restore_default_acl_association(params, client, module)
return True
def construct_acl_entries(nacl, client, module):
for entry in module.params.get('ingress'):
params = process_rule_entry(entry, Egress=False)
params['NetworkAclId'] = nacl['NetworkAcl']['NetworkAclId']
create_network_acl_entry(params, client, module)
for rule in module.params.get('egress'):
params = process_rule_entry(rule, Egress=True)
params['NetworkAclId'] = nacl['NetworkAcl']['NetworkAclId']
create_network_acl_entry(params, client, module)
## Module invocations
def setup_network_acl(client, module):
changed = False
nacl = describe_network_acl(client, module)
if not nacl['NetworkAcls']:
nacl = create_network_acl(module.params.get('vpc_id'), client, module)
nacl_id = nacl['NetworkAcl']['NetworkAclId']
create_tags(nacl_id, client, module)
subnets = subnets_to_associate(nacl, client, module)
replace_network_acl_association(nacl_id, subnets, client, module)
construct_acl_entries(nacl, client, module)
changed = True
return(changed, nacl['NetworkAcl']['NetworkAclId'])
else:
changed = False
nacl_id = nacl['NetworkAcls'][0]['NetworkAclId']
subnet_result = subnets_changed(nacl, client, module)
nacl_result = nacls_changed(nacl, client, module)
tag_result = tags_changed(nacl_id, client, module)
if subnet_result is True or nacl_result is True or tag_result is True:
changed = True
return(changed, nacl_id)
return (changed, nacl_id)
def remove_network_acl(client, module):
changed = False
result = dict()
vpc_id = module.params.get('vpc_id')
nacl = describe_network_acl(client, module)
if nacl['NetworkAcls']:
nacl_id = nacl['NetworkAcls'][0]['NetworkAclId']
associations = nacl['NetworkAcls'][0]['Associations']
assoc_ids = [a['NetworkAclAssociationId'] for a in associations]
default_nacl_id = find_default_vpc_nacl(vpc_id, client, module)
if not default_nacl_id:
result = {vpc_id: "Default NACL ID not found - Check the VPC ID"}
return changed, result
if restore_default_associations(assoc_ids, default_nacl_id, client, module):
delete_network_acl(nacl_id, client, module)
changed = True
result[nacl_id] = "Successfully deleted"
return changed, result
if not assoc_ids:
delete_network_acl(nacl_id, client, module)
changed = True
result[nacl_id] = "Successfully deleted"
return changed, result
return changed, result
#Boto3 client methods
def create_network_acl(vpc_id, client, module):
try:
nacl = client.create_network_acl(VpcId=vpc_id)
except botocore.exceptions.ClientError as e:
module.fail_json(msg=str(e))
return nacl
def create_network_acl_entry(params, client, module):
try:
result = client.create_network_acl_entry(**params)
except botocore.exceptions.ClientError as e:
module.fail_json(msg=str(e))
return result
def create_tags(nacl_id, client, module):
try:
delete_tags(nacl_id, client, module)
client.create_tags(Resources=[nacl_id], Tags=load_tags(module))
except botocore.exceptions.ClientError as e:
module.fail_json(msg=str(e))
def delete_network_acl(nacl_id, client, module):
try:
client.delete_network_acl(NetworkAclId=nacl_id)
except botocore.exceptions.ClientError as e:
module.fail_json(msg=str(e))
def delete_network_acl_entry(params, client, module):
try:
client.delete_network_acl_entry(**params)
except botocore.exceptions.ClientError as e:
module.fail_json(msg=str(e))
def delete_tags(nacl_id, client, module):
try:
client.delete_tags(Resources=[nacl_id])
except botocore.exceptions.ClientError as e:
module.fail_json(msg=str(e))
def describe_acl_associations(subnets, client, module):
if not subnets:
return []
try:
results = client.describe_network_acls(Filters=[
{'Name': 'association.subnet-id', 'Values': subnets}
])
except botocore.exceptions.ClientError as e:
module.fail_json(msg=str(e))
associations = results['NetworkAcls'][0]['Associations']
return [a['NetworkAclAssociationId'] for a in associations if a['SubnetId'] in subnets]
def describe_network_acl(client, module):
try:
nacl = client.describe_network_acls(Filters=[
{'Name': 'tag:Name', 'Values': [module.params.get('name')]}
])
except botocore.exceptions.ClientError as e:
module.fail_json(msg=str(e))
return nacl
def find_acl_by_id(nacl_id, client, module):
try:
return client.describe_network_acls(NetworkAclIds=[nacl_id])
except botocore.exceptions.ClientError as e:
module.fail_json(msg=str(e))
def find_default_vpc_nacl(vpc_id, client, module):
try:
response = client.describe_network_acls(Filters=[
{'Name': 'vpc-id', 'Values': [vpc_id]}])
except botocore.exceptions.ClientError as e:
module.fail_json(msg=str(e))
nacls = response['NetworkAcls']
return [n['NetworkAclId'] for n in nacls if n['IsDefault'] == True]
def find_subnet_ids_by_nacl_id(nacl_id, client, module):
try:
results = client.describe_network_acls(Filters=[
{'Name': 'association.network-acl-id', 'Values': [nacl_id]}
])
except botocore.exceptions.ClientError as e:
module.fail_json(msg=str(e))
if results['NetworkAcls']:
associations = results['NetworkAcls'][0]['Associations']
return [s['SubnetId'] for s in associations if s['SubnetId']]
else:
return []
def replace_network_acl_association(nacl_id, subnets, client, module):
params = dict()
params['NetworkAclId'] = nacl_id
for association in describe_acl_associations(subnets, client, module):
params['AssociationId'] = association
try:
client.replace_network_acl_association(**params)
except botocore.exceptions.ClientError as e:
module.fail_json(msg=str(e))
def replace_network_acl_entry(entries, Egress, nacl_id, client, module):
params = dict()
for entry in entries:
params = entry
params['NetworkAclId'] = nacl_id
try:
client.replace_network_acl_entry(**params)
except botocore.exceptions.ClientError as e:
module.fail_json(msg=str(e))
def restore_default_acl_association(params, client, module):
try:
client.replace_network_acl_association(**params)
except botocore.exceptions.ClientError as e:
module.fail_json(msg=str(e))
def subnets_to_associate(nacl, client, module):
params = list(module.params.get('subnets'))
if not params:
return []
if params[0].startswith("subnet-"):
try:
subnets = client.describe_subnets(Filters=[
{'Name': 'subnet-id', 'Values': params}])
except botocore.exceptions.ClientError as e:
module.fail_json(msg=str(e))
else:
try:
subnets = client.describe_subnets(Filters=[
{'Name': 'tag:Name', 'Values': params}])
except botocore.exceptions.ClientError as e:
module.fail_json(msg=str(e))
return [s['SubnetId'] for s in subnets['Subnets'] if s['SubnetId']]
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(dict(
vpc_id=dict(required=True),
name=dict(required=True),
subnets=dict(required=False, type='list', default=list()),
tags=dict(required=False, type='dict'),
ingress=dict(required=False, type='list', default=list()),
egress=dict(required=False, type='list', default=list(),),
state=dict(default='present', choices=['present', 'absent']),
),
)
module = AnsibleModule(argument_spec=argument_spec)
if not HAS_BOTO3:
module.fail_json(msg='json, botocore and boto3 are required.')
state = module.params.get('state').lower()
try:
region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)
client = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_kwargs)
except botocore.exceptions.NoCredentialsError, e:
module.fail_json(msg="Can't authorize connection - "+str(e))
invocations = {
"present": setup_network_acl,
"absent": remove_network_acl
}
(changed, results) = invocations[state](client, module)
module.exit_json(changed=changed, nacl_id=results)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
if __name__ == '__main__':
main()
|
mmnelemane/nova | refs/heads/master | nova/objects/migration.py | 12 | # Copyright 2013 IBM Corp.
#
# 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 nova import db
from nova import exception
from nova import objects
from nova.objects import base
from nova.objects import fields
from nova import utils
def _determine_migration_type(migration):
if migration['old_instance_type_id'] != migration['new_instance_type_id']:
return 'resize'
else:
return 'migration'
# TODO(berrange): Remove NovaObjectDictCompat
@base.NovaObjectRegistry.register
class Migration(base.NovaPersistentObject, base.NovaObject,
base.NovaObjectDictCompat):
# Version 1.0: Initial version
# Version 1.1: String attributes updated to support unicode
# Version 1.2: Added migration_type and hidden
VERSION = '1.2'
fields = {
'id': fields.IntegerField(),
'source_compute': fields.StringField(nullable=True),
'dest_compute': fields.StringField(nullable=True),
'source_node': fields.StringField(nullable=True),
'dest_node': fields.StringField(nullable=True),
'dest_host': fields.StringField(nullable=True),
'old_instance_type_id': fields.IntegerField(nullable=True),
'new_instance_type_id': fields.IntegerField(nullable=True),
'instance_uuid': fields.StringField(nullable=True),
'status': fields.StringField(nullable=True),
'migration_type': fields.EnumField(['migration', 'resize',
'live-migration', 'evacuation'],
nullable=False),
'hidden': fields.BooleanField(nullable=False, default=False),
}
@staticmethod
def _from_db_object(context, migration, db_migration):
for key in migration.fields:
value = db_migration[key]
if key == 'migration_type' and value is None:
value = _determine_migration_type(db_migration)
migration[key] = value
migration._context = context
migration.obj_reset_changes()
return migration
def obj_make_compatible(self, primitive, target_version):
super(Migration, self).obj_make_compatible(primitive, target_version)
target_version = utils.convert_version_to_tuple(target_version)
if target_version < (1, 2):
if 'migration_type' in primitive:
del primitive['migration_type']
del primitive['hidden']
def obj_load_attr(self, attrname):
if attrname == 'migration_type':
# NOTE(danms): The only reason we'd need to load this is if
# some older node sent us one. So, guess the type.
self.migration_type = _determine_migration_type(self)
elif attrname == 'hidden':
self.hidden = False
else:
super(Migration, self).obj_load_attr(attrname)
@base.remotable_classmethod
def get_by_id(cls, context, migration_id):
db_migration = db.migration_get(context, migration_id)
return cls._from_db_object(context, cls(), db_migration)
@base.remotable_classmethod
def get_by_instance_and_status(cls, context, instance_uuid, status):
db_migration = db.migration_get_by_instance_and_status(
context, instance_uuid, status)
return cls._from_db_object(context, cls(), db_migration)
@base.remotable
def create(self):
if self.obj_attr_is_set('id'):
raise exception.ObjectActionError(action='create',
reason='already created')
updates = self.obj_get_changes()
db_migration = db.migration_create(self._context, updates)
self._from_db_object(self._context, self, db_migration)
@base.remotable
def save(self):
updates = self.obj_get_changes()
updates.pop('id', None)
db_migration = db.migration_update(self._context, self.id, updates)
self._from_db_object(self._context, self, db_migration)
self.obj_reset_changes()
@property
def instance(self):
return objects.Instance.get_by_uuid(self._context, self.instance_uuid)
@base.NovaObjectRegistry.register
class MigrationList(base.ObjectListBase, base.NovaObject):
# Version 1.0: Initial version
# Migration <= 1.1
# Version 1.1: Added use_slave to get_unconfirmed_by_dest_compute
# Version 1.2: Migration version 1.2
VERSION = '1.2'
fields = {
'objects': fields.ListOfObjectsField('Migration'),
}
# NOTE(danms): Migration was at 1.1 before we added this
obj_relationships = {
'objects': [('1.0', '1.1'), ('1.1', '1.1'), ('1.2', '1.2')],
}
@base.remotable_classmethod
def get_unconfirmed_by_dest_compute(cls, context, confirm_window,
dest_compute, use_slave=False):
db_migrations = db.migration_get_unconfirmed_by_dest_compute(
context, confirm_window, dest_compute, use_slave=use_slave)
return base.obj_make_list(context, cls(context), objects.Migration,
db_migrations)
@base.remotable_classmethod
def get_in_progress_by_host_and_node(cls, context, host, node):
db_migrations = db.migration_get_in_progress_by_host_and_node(
context, host, node)
return base.obj_make_list(context, cls(context), objects.Migration,
db_migrations)
@base.remotable_classmethod
def get_by_filters(cls, context, filters):
db_migrations = db.migration_get_all_by_filters(context, filters)
return base.obj_make_list(context, cls(context), objects.Migration,
db_migrations)
|
ThirdProject/android_external_chromium_org | refs/heads/cm-11.0 | third_party/protobuf/python/stubout.py | 670 | #!/usr/bin/python2.4
#
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This file is used for testing. The original is at:
# http://code.google.com/p/pymox/
class StubOutForTesting:
"""Sample Usage:
You want os.path.exists() to always return true during testing.
stubs = StubOutForTesting()
stubs.Set(os.path, 'exists', lambda x: 1)
...
stubs.UnsetAll()
The above changes os.path.exists into a lambda that returns 1. Once
the ... part of the code finishes, the UnsetAll() looks up the old value
of os.path.exists and restores it.
"""
def __init__(self):
self.cache = []
self.stubs = []
def __del__(self):
self.SmartUnsetAll()
self.UnsetAll()
def SmartSet(self, obj, attr_name, new_attr):
"""Replace obj.attr_name with new_attr. This method is smart and works
at the module, class, and instance level while preserving proper
inheritance. It will not stub out C types however unless that has been
explicitly allowed by the type.
This method supports the case where attr_name is a staticmethod or a
classmethod of obj.
Notes:
- If obj is an instance, then it is its class that will actually be
stubbed. Note that the method Set() does not do that: if obj is
an instance, it (and not its class) will be stubbed.
- The stubbing is using the builtin getattr and setattr. So, the __get__
and __set__ will be called when stubbing (TODO: A better idea would
probably be to manipulate obj.__dict__ instead of getattr() and
setattr()).
Raises AttributeError if the attribute cannot be found.
"""
if (inspect.ismodule(obj) or
(not inspect.isclass(obj) and obj.__dict__.has_key(attr_name))):
orig_obj = obj
orig_attr = getattr(obj, attr_name)
else:
if not inspect.isclass(obj):
mro = list(inspect.getmro(obj.__class__))
else:
mro = list(inspect.getmro(obj))
mro.reverse()
orig_attr = None
for cls in mro:
try:
orig_obj = cls
orig_attr = getattr(obj, attr_name)
except AttributeError:
continue
if orig_attr is None:
raise AttributeError("Attribute not found.")
# Calling getattr() on a staticmethod transforms it to a 'normal' function.
# We need to ensure that we put it back as a staticmethod.
old_attribute = obj.__dict__.get(attr_name)
if old_attribute is not None and isinstance(old_attribute, staticmethod):
orig_attr = staticmethod(orig_attr)
self.stubs.append((orig_obj, attr_name, orig_attr))
setattr(orig_obj, attr_name, new_attr)
def SmartUnsetAll(self):
"""Reverses all the SmartSet() calls, restoring things to their original
definition. Its okay to call SmartUnsetAll() repeatedly, as later calls
have no effect if no SmartSet() calls have been made.
"""
self.stubs.reverse()
for args in self.stubs:
setattr(*args)
self.stubs = []
def Set(self, parent, child_name, new_child):
"""Replace child_name's old definition with new_child, in the context
of the given parent. The parent could be a module when the child is a
function at module scope. Or the parent could be a class when a class'
method is being replaced. The named child is set to new_child, while
the prior definition is saved away for later, when UnsetAll() is called.
This method supports the case where child_name is a staticmethod or a
classmethod of parent.
"""
old_child = getattr(parent, child_name)
old_attribute = parent.__dict__.get(child_name)
if old_attribute is not None and isinstance(old_attribute, staticmethod):
old_child = staticmethod(old_child)
self.cache.append((parent, old_child, child_name))
setattr(parent, child_name, new_child)
def UnsetAll(self):
"""Reverses all the Set() calls, restoring things to their original
definition. Its okay to call UnsetAll() repeatedly, as later calls have
no effect if no Set() calls have been made.
"""
# Undo calls to Set() in reverse order, in case Set() was called on the
# same arguments repeatedly (want the original call to be last one undone)
self.cache.reverse()
for (parent, old_child, child_name) in self.cache:
setattr(parent, child_name, old_child)
self.cache = []
|
bbansalWolfPack/servo | refs/heads/master | tests/wpt/web-platform-tests/websockets/handlers/handshake_protocol_wsh.py | 215 | #!/usr/bin/python
from mod_pywebsocket import common, msgutil, util
from mod_pywebsocket.handshake import hybi
def web_socket_do_extra_handshake(request):
request.connection.write('HTTP/1.1 101 Switching Protocols:\x0D\x0AConnection: Upgrade\x0D\x0AUpgrade: WebSocket\x0D\x0ASec-WebSocket-Protocol: foobar\x0D\x0ASec-WebSocket-Origin: '+request.ws_origin+'\x0D\x0ASec-WebSocket-Accept: '+hybi.compute_accept(request.headers_in.get(common.SEC_WEBSOCKET_KEY_HEADER))[0]+'\x0D\x0A\x0D\x0A')
return
def web_socket_transfer_data(request):
while True:
return |
kawamon/hue | refs/heads/master | desktop/core/ext-py/Django-1.11.29/tests/migrations/test_migrations_squashed_complex/3_squashed_5.py | 770 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
replaces = [
("migrations", "3_auto"),
("migrations", "4_auto"),
("migrations", "5_auto"),
]
dependencies = [("migrations", "2_auto")]
operations = [
migrations.RunPython(migrations.RunPython.noop)
]
|
keyru/hdl-make | refs/heads/develop | tests/counter/syn/brevia2_dk_diamond/verilog/Manifest.py | 2 | target = "lattice"
action = "synthesis"
syn_device = "lfxp2-5e"
syn_grade = "-6"
syn_package = "tn144c"
syn_top = "brevia2_top"
syn_project = "demo"
syn_tool = "diamond"
modules = {
"local" : [ "../../../top/brevia2_dk/verilog" ],
}
|
MotorolaMobilityLLC/external-chromium_org | refs/heads/kitkat-mr1-release-falcon-gpe | tools/json_schema_compiler/schema_util_test.py | 169 | #!/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.
from schema_util import JsFunctionNameToClassName
from schema_util import StripNamespace
import unittest
class SchemaUtilTest(unittest.TestCase):
def testStripNamespace(self):
self.assertEquals('Bar', StripNamespace('foo.Bar'))
self.assertEquals('Baz', StripNamespace('Baz'))
def testJsFunctionNameToClassName(self):
self.assertEquals('FooBar', JsFunctionNameToClassName('foo', 'bar'))
self.assertEquals('FooBar',
JsFunctionNameToClassName('experimental.foo', 'bar'))
self.assertEquals('FooBarBaz',
JsFunctionNameToClassName('foo.bar', 'baz'))
self.assertEquals('FooBarBaz',
JsFunctionNameToClassName('experimental.foo.bar', 'baz'))
if __name__ == '__main__':
unittest.main()
|
jiangzhuo/kbengine | refs/heads/master | kbe/res/scripts/common/Lib/unittest/runner.py | 195 | """Running tests"""
import sys
import time
import warnings
from . import result
from .signals import registerResult
__unittest = True
class _WritelnDecorator(object):
"""Used to decorate file-like objects with a handy 'writeln' method"""
def __init__(self,stream):
self.stream = stream
def __getattr__(self, attr):
if attr in ('stream', '__getstate__'):
raise AttributeError(attr)
return getattr(self.stream,attr)
def writeln(self, arg=None):
if arg:
self.write(arg)
self.write('\n') # text-mode streams translate to \r\n if needed
class TextTestResult(result.TestResult):
"""A test result class that can print formatted text results to a stream.
Used by TextTestRunner.
"""
separator1 = '=' * 70
separator2 = '-' * 70
def __init__(self, stream, descriptions, verbosity):
super(TextTestResult, self).__init__(stream, descriptions, verbosity)
self.stream = stream
self.showAll = verbosity > 1
self.dots = verbosity == 1
self.descriptions = descriptions
def getDescription(self, test):
doc_first_line = test.shortDescription()
if self.descriptions and doc_first_line:
return '\n'.join((str(test), doc_first_line))
else:
return str(test)
def startTest(self, test):
super(TextTestResult, self).startTest(test)
if self.showAll:
self.stream.write(self.getDescription(test))
self.stream.write(" ... ")
self.stream.flush()
def addSuccess(self, test):
super(TextTestResult, self).addSuccess(test)
if self.showAll:
self.stream.writeln("ok")
elif self.dots:
self.stream.write('.')
self.stream.flush()
def addError(self, test, err):
super(TextTestResult, self).addError(test, err)
if self.showAll:
self.stream.writeln("ERROR")
elif self.dots:
self.stream.write('E')
self.stream.flush()
def addFailure(self, test, err):
super(TextTestResult, self).addFailure(test, err)
if self.showAll:
self.stream.writeln("FAIL")
elif self.dots:
self.stream.write('F')
self.stream.flush()
def addSkip(self, test, reason):
super(TextTestResult, self).addSkip(test, reason)
if self.showAll:
self.stream.writeln("skipped {0!r}".format(reason))
elif self.dots:
self.stream.write("s")
self.stream.flush()
def addExpectedFailure(self, test, err):
super(TextTestResult, self).addExpectedFailure(test, err)
if self.showAll:
self.stream.writeln("expected failure")
elif self.dots:
self.stream.write("x")
self.stream.flush()
def addUnexpectedSuccess(self, test):
super(TextTestResult, self).addUnexpectedSuccess(test)
if self.showAll:
self.stream.writeln("unexpected success")
elif self.dots:
self.stream.write("u")
self.stream.flush()
def printErrors(self):
if self.dots or self.showAll:
self.stream.writeln()
self.printErrorList('ERROR', self.errors)
self.printErrorList('FAIL', self.failures)
def printErrorList(self, flavour, errors):
for test, err in errors:
self.stream.writeln(self.separator1)
self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
self.stream.writeln(self.separator2)
self.stream.writeln("%s" % err)
class TextTestRunner(object):
"""A test runner class that displays results in textual form.
It prints out the names of tests as they are run, errors as they
occur, and a summary of the results at the end of the test run.
"""
resultclass = TextTestResult
def __init__(self, stream=None, descriptions=True, verbosity=1,
failfast=False, buffer=False, resultclass=None, warnings=None):
if stream is None:
stream = sys.stderr
self.stream = _WritelnDecorator(stream)
self.descriptions = descriptions
self.verbosity = verbosity
self.failfast = failfast
self.buffer = buffer
self.warnings = warnings
if resultclass is not None:
self.resultclass = resultclass
def _makeResult(self):
return self.resultclass(self.stream, self.descriptions, self.verbosity)
def run(self, test):
"Run the given test case or test suite."
result = self._makeResult()
registerResult(result)
result.failfast = self.failfast
result.buffer = self.buffer
with warnings.catch_warnings():
if self.warnings:
# if self.warnings is set, use it to filter all the warnings
warnings.simplefilter(self.warnings)
# if the filter is 'default' or 'always', special-case the
# warnings from the deprecated unittest methods to show them
# no more than once per module, because they can be fairly
# noisy. The -Wd and -Wa flags can be used to bypass this
# only when self.warnings is None.
if self.warnings in ['default', 'always']:
warnings.filterwarnings('module',
category=DeprecationWarning,
message='Please use assert\w+ instead.')
startTime = time.time()
startTestRun = getattr(result, 'startTestRun', None)
if startTestRun is not None:
startTestRun()
try:
test(result)
finally:
stopTestRun = getattr(result, 'stopTestRun', None)
if stopTestRun is not None:
stopTestRun()
stopTime = time.time()
timeTaken = stopTime - startTime
result.printErrors()
if hasattr(result, 'separator2'):
self.stream.writeln(result.separator2)
run = result.testsRun
self.stream.writeln("Ran %d test%s in %.3fs" %
(run, run != 1 and "s" or "", timeTaken))
self.stream.writeln()
expectedFails = unexpectedSuccesses = skipped = 0
try:
results = map(len, (result.expectedFailures,
result.unexpectedSuccesses,
result.skipped))
except AttributeError:
pass
else:
expectedFails, unexpectedSuccesses, skipped = results
infos = []
if not result.wasSuccessful():
self.stream.write("FAILED")
failed, errored = len(result.failures), len(result.errors)
if failed:
infos.append("failures=%d" % failed)
if errored:
infos.append("errors=%d" % errored)
else:
self.stream.write("OK")
if skipped:
infos.append("skipped=%d" % skipped)
if expectedFails:
infos.append("expected failures=%d" % expectedFails)
if unexpectedSuccesses:
infos.append("unexpected successes=%d" % unexpectedSuccesses)
if infos:
self.stream.writeln(" (%s)" % (", ".join(infos),))
else:
self.stream.write("\n")
return result
|
harry-7/addons-server | refs/heads/master | src/olympia/api/parsers.py | 16 | from rest_framework.parsers import DataAndFiles, MultiPartParser
class MultiPartParser(MultiPartParser):
"""
Parser for multipart form data, which may include file data.
Lifted from https://github.com/tomchristie/django-rest-framework/pull/4026/
to work around request.data being empty when multipart/form-data is posted.
See https://github.com/tomchristie/django-rest-framework/issues/3951
"""
def parse(self, stream, media_type=None, parser_context=None):
"""
Parses the incoming bytestream as a multipart encoded form,
and returns a DataAndFiles object.
`.data` will be a `QueryDict` containing all the form parameters.
`.files` will be a `QueryDict` containing all the form files.
For POSTs, accept Django request parsing. See issue #3951.
"""
parser_context = parser_context or {}
request = parser_context['request']
_request = request._request
if _request.method == 'POST':
return DataAndFiles(_request.POST, _request.FILES)
return super(MultiPartParser, self).parse(
stream, media_type=media_type, parser_context=parser_context)
|
lxn2/mxnet | refs/heads/master | example/speech-demo/io_func/convert2kaldi.py | 15 | # Copyright 2013 Yajie Miao Carnegie Mellon University
# 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
#
# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
# WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
# MERCHANTABLITY OR NON-INFRINGEMENT.
# See the Apache 2 License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import os
import sys
from StringIO import StringIO
import json
import utils.utils as utils
from model_io import string_2_array
# Various functions to convert models into Kaldi formats
def _nnet2kaldi(nnet_spec, set_layer_num = -1, filein='nnet.in',
fileout='nnet.out', activation='sigmoid', withfinal=True):
_nnet2kaldi_main(nnet_spec, set_layer_num=set_layer_num, filein=filein,
fileout=fileout, activation=activation, withfinal=withfinal, maxout=False)
def _nnet2kaldi_maxout(nnet_spec, pool_size = 1, set_layer_num = -1,
filein='nnet.in', fileout='nnet.out', activation='sigmoid', withfinal=True):
_nnet2kaldi_main(nnet_spec, set_layer_num=set_layer_num, filein=filein,
fileout=fileout, activation=activation, withfinal=withfinal,
pool_size = 1, maxout=True)
def _nnet2kaldi_main(nnet_spec, set_layer_num = -1, filein='nnet.in',
fileout='nnet.out', activation='sigmoid', withfinal=True, maxout=False):
elements = nnet_spec.split(':')
layers = []
for x in elements:
layers.append(int(x))
if set_layer_num == -1:
layer_num = len(layers) - 1
else:
layer_num = set_layer_num + 1
nnet_dict = {}
nnet_dict = utils.pickle_load(filein)
fout = open(fileout, 'wb')
for i in xrange(layer_num - 1):
input_size = int(layers[i])
if maxout:
output_size = int(layers[i + 1]) * pool_size
else:
output_size = int(layers[i + 1])
W_layer = []
b_layer = ''
for rowX in xrange(output_size):
W_layer.append('')
dict_key = str(i) + ' ' + activation + ' W'
matrix = string_2_array(nnet_dict[dict_key])
for x in xrange(input_size):
for t in xrange(output_size):
W_layer[t] = W_layer[t] + str(matrix[x][t]) + ' '
dict_key = str(i) + ' ' + activation + ' b'
vector = string_2_array(nnet_dict[dict_key])
for x in xrange(output_size):
b_layer = b_layer + str(vector[x]) + ' '
fout.write('<affinetransform> ' + str(output_size) + ' ' + str(input_size) + '\n')
fout.write('[' + '\n')
for x in xrange(output_size):
fout.write(W_layer[x].strip() + '\n')
fout.write(']' + '\n')
fout.write('[ ' + b_layer.strip() + ' ]' + '\n')
if maxout:
fout.write('<maxout> ' + str(int(layers[i + 1])) + ' ' + str(output_size) + '\n')
else:
fout.write('<sigmoid> ' + str(output_size) + ' ' + str(output_size) + '\n')
if withfinal:
input_size = int(layers[-2])
output_size = int(layers[-1])
W_layer = []
b_layer = ''
for rowX in xrange(output_size):
W_layer.append('')
dict_key = 'logreg W'
matrix = string_2_array(nnet_dict[dict_key])
for x in xrange(input_size):
for t in xrange(output_size):
W_layer[t] = W_layer[t] + str(matrix[x][t]) + ' '
dict_key = 'logreg b'
vector = string_2_array(nnet_dict[dict_key])
for x in xrange(output_size):
b_layer = b_layer + str(vector[x]) + ' '
fout.write('<affinetransform> ' + str(output_size) + ' ' + str(input_size) + '\n')
fout.write('[' + '\n')
for x in xrange(output_size):
fout.write(W_layer[x].strip() + '\n')
fout.write(']' + '\n')
fout.write('[ ' + b_layer.strip() + ' ]' + '\n')
fout.write('<softmax> ' + str(output_size) + ' ' + str(output_size) + '\n')
fout.close(); |
alexus37/AugmentedRealityChess | refs/heads/master | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGL/raw/WGL/NV/multisample_coverage.py | 8 | '''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.WGL import _types as _cs
# End users want this...
from OpenGL.raw.WGL._types import *
from OpenGL.raw.WGL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_EXTENSION_NAME = 'WGL_NV_multisample_coverage'
def _f( function ):
return _p.createFunction( function,_p.PLATFORM.WGL,'WGL_NV_multisample_coverage',error_checker=_errors._error_checker)
WGL_COLOR_SAMPLES_NV=_C('WGL_COLOR_SAMPLES_NV',0x20B9)
WGL_COVERAGE_SAMPLES_NV=_C('WGL_COVERAGE_SAMPLES_NV',0x2042)
|
google-research/augmix | refs/heads/master | augmentations.py | 1 | # Copyright 2019 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
#
# https://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.
# ==============================================================================
"""Base augmentations operators."""
import numpy as np
from PIL import Image, ImageOps, ImageEnhance
# ImageNet code should change this value
IMAGE_SIZE = 32
def int_parameter(level, maxval):
"""Helper function to scale `val` between 0 and maxval .
Args:
level: Level of the operation that will be between [0, `PARAMETER_MAX`].
maxval: Maximum value that the operation can have. This will be scaled to
level/PARAMETER_MAX.
Returns:
An int that results from scaling `maxval` according to `level`.
"""
return int(level * maxval / 10)
def float_parameter(level, maxval):
"""Helper function to scale `val` between 0 and maxval.
Args:
level: Level of the operation that will be between [0, `PARAMETER_MAX`].
maxval: Maximum value that the operation can have. This will be scaled to
level/PARAMETER_MAX.
Returns:
A float that results from scaling `maxval` according to `level`.
"""
return float(level) * maxval / 10.
def sample_level(n):
return np.random.uniform(low=0.1, high=n)
def autocontrast(pil_img, _):
return ImageOps.autocontrast(pil_img)
def equalize(pil_img, _):
return ImageOps.equalize(pil_img)
def posterize(pil_img, level):
level = int_parameter(sample_level(level), 4)
return ImageOps.posterize(pil_img, 4 - level)
def rotate(pil_img, level):
degrees = int_parameter(sample_level(level), 30)
if np.random.uniform() > 0.5:
degrees = -degrees
return pil_img.rotate(degrees, resample=Image.BILINEAR)
def solarize(pil_img, level):
level = int_parameter(sample_level(level), 256)
return ImageOps.solarize(pil_img, 256 - level)
def shear_x(pil_img, level):
level = float_parameter(sample_level(level), 0.3)
if np.random.uniform() > 0.5:
level = -level
return pil_img.transform((IMAGE_SIZE, IMAGE_SIZE),
Image.AFFINE, (1, level, 0, 0, 1, 0),
resample=Image.BILINEAR)
def shear_y(pil_img, level):
level = float_parameter(sample_level(level), 0.3)
if np.random.uniform() > 0.5:
level = -level
return pil_img.transform((IMAGE_SIZE, IMAGE_SIZE),
Image.AFFINE, (1, 0, 0, level, 1, 0),
resample=Image.BILINEAR)
def translate_x(pil_img, level):
level = int_parameter(sample_level(level), IMAGE_SIZE / 3)
if np.random.random() > 0.5:
level = -level
return pil_img.transform((IMAGE_SIZE, IMAGE_SIZE),
Image.AFFINE, (1, 0, level, 0, 1, 0),
resample=Image.BILINEAR)
def translate_y(pil_img, level):
level = int_parameter(sample_level(level), IMAGE_SIZE / 3)
if np.random.random() > 0.5:
level = -level
return pil_img.transform((IMAGE_SIZE, IMAGE_SIZE),
Image.AFFINE, (1, 0, 0, 0, 1, level),
resample=Image.BILINEAR)
# operation that overlaps with ImageNet-C's test set
def color(pil_img, level):
level = float_parameter(sample_level(level), 1.8) + 0.1
return ImageEnhance.Color(pil_img).enhance(level)
# operation that overlaps with ImageNet-C's test set
def contrast(pil_img, level):
level = float_parameter(sample_level(level), 1.8) + 0.1
return ImageEnhance.Contrast(pil_img).enhance(level)
# operation that overlaps with ImageNet-C's test set
def brightness(pil_img, level):
level = float_parameter(sample_level(level), 1.8) + 0.1
return ImageEnhance.Brightness(pil_img).enhance(level)
# operation that overlaps with ImageNet-C's test set
def sharpness(pil_img, level):
level = float_parameter(sample_level(level), 1.8) + 0.1
return ImageEnhance.Sharpness(pil_img).enhance(level)
augmentations = [
autocontrast, equalize, posterize, rotate, solarize, shear_x, shear_y,
translate_x, translate_y
]
augmentations_all = [
autocontrast, equalize, posterize, rotate, solarize, shear_x, shear_y,
translate_x, translate_y, color, contrast, brightness, sharpness
]
|
ResidentMario/py-events | refs/heads/master | backend.py | 2 | """backend.py
This library defines the backend used by the application webservice, `app.py`.
The Watson/Core methods contained here are wrappers of `event_insight_lib.py` methods."""
# Redistributables.
import json
import os
import random
import itertools
import requests
# My own libraries.
import event_insight_lib
# from user import User
#############
# INTERFACE #
#############
# This section contains all of the backend methods servicing the user interface layer of the webservice.
def emailAlreadyInUse(new_email, filename='accounts.json'):
"""Checks if an email is already in use. Returns True if it is, False if not."""
# Open the accounts file.
if filename in [f for f in os.listdir('.') if os.path.isfile(f)]:
list_of_users = json.load(open(filename))['accounts']
# Check to see if the selected email appears in the list.
for existing_user in list_of_users:
if existing_user['email'] == new_email:
return True
return False
def authenticateUser(email, password, filename='accounts.json'):
"""Authenticates a user's email-password combination."""
if filename in [f for f in os.listdir('.') if os.path.isfile(f)]:
list_of_users = json.load(open(filename))['accounts']
# Check to see if the selected email appears in the list.
for existing_user in list_of_users:
if existing_user['email'] == email and existing_user['password'] == password:
return True
return False
def initializeSecretString():
"""
Imports the secret string used by some of the Flask plug-ins for security purposes.
The secret string is be a simple randomly generated numerical, defined at runtime.
"""
return random.random()
#################
# END INTERFACE #
#################
###############
# WATSON/CORE #
###############
# This section contains the systemic core of the application---its interface with the IBM Watson Concept Insights service.
# These are high-level methods which wrap low-level methods contained in the event_insight_lib library.
# Some terminology:
# A "Concept Node" is a Wikipedia pagename which is associated with an "Concept Model" when run through the Concept Insights service.
# The "Concept Model" is the model for a particular user's conceptual preferences.
# eg. {'Modern art': 0.67, 'History of music': 0.89}
# These are associated with the .model property of an ObjectModel object, which stores the model and some metadata about the model:
# its maturity and the email of the associated account.
# ConceptModel objects are read from and written to `accounts.json` for permanent storage.
def getToken(tokenfile='token.json'):
"""
This is the primary-use access method meant to be used throughout the application.
Path-wrapper for the getToken() method in event_insight_lib.py.
"""
return event_insight_lib.getToken(tokenfile)
def fetchConceptsForUserConcept(institution, token, cutoff=0.5):
"""
Given a user-defined concept name and an access token this function returns the dictionary model for the given raw concept.
This method is called as a part of processing on user input during registration.
The top-scoring result of a call to annotateText *should*, in ordinary cases, correspond with the article-name of the concept.
This result is then run through event_insight_lib.fetchRelatedConcepts().
"""
# Fetch the precise name of the node (article title) associated with the institution.
_concept_node = event_insight_lib.annotateText(institution, token)
# If the correction call is successful, keep going.
if 'annotations' in _concept_node.keys() and len(_concept_node['annotations']) != 0:
_concept_node_title = _concept_node['annotations'][0]['concept']['label']
_related_concepts = event_insight_lib.fetchRelatedConcepts(_concept_node_title, token)
return parseRawConceptCall(_related_concepts, cutoff)
# Otherwise, if the call was not successful, return a None flag.
else:
return None
def fetchConceptsForEvent(event_string, token, cutoff=0.2):
"""
Returns the result of a Watson query against an event string.
Decorator for event_insight_lib.annotateText() that adds a cutoff parameter.
TODO: Test!
"""
return parseRawEventCall(event_insight_lib.annotateText(event_string, token), cutoff)
def parseRawConceptCall(raw_output, cutoff=0.5):
"""
Parses the raw results of a call to the `label_search` IBM Watson API, implementing a cutoff in the process.
Used to parse the results for the `fetchConceptsForUserConcept()` front-facing method.
Returns a dict that can be assigned to an ObjectModel.
Minor semantic differences from `parseRawEventCall()`, below.
"""
dat = dict()
# If there is nothing to parse, don't parse it.
if 'concepts' not in raw_output.keys():
return dat
else:
for concept in raw_output['concepts']:
if concept['score'] >= cutoff:
dat[concept['concept']['label']] = concept['score']
return dat
def parseRawEventCall(raw_output, cutoff=0.5):
"""
Parses the raw results of a call to the `label_search` IBM Watson API, implementing a cutoff in the process.
Used to parse the results for the `fetchConceptsForEvent()` front-facing method.
Returns a dict that can be assigned to an ObjectModel.
Minor semantic differences from `parseRawConceptCall()`, above.
"""
dat = dict()
# If there is nothing to parse, don't parse it.
if 'annotations' not in raw_output.keys():
return dat
else:
for concept in raw_output['annotations']:
if concept['score'] >= cutoff:
dat[concept['concept']['label']] = concept['score']
return dat
###################
# END WATSON/CORE #
################### |
rec/echomesh | refs/heads/master | lib/darwin/PIL/ImageSequence.py | 15 | #
# The Python Imaging Library.
# $Id$
#
# sequence support classes
#
# history:
# 1997-02-20 fl Created
#
# Copyright (c) 1997 by Secret Labs AB.
# Copyright (c) 1997 by Fredrik Lundh.
#
# See the README file for information on usage and redistribution.
#
##
class Iterator:
"""
This class implements an iterator object that can be used to loop
over an image sequence.
You can use the ``[]`` operator to access elements by index. This operator
will raise an :py:exc:`IndexError` if you try to access a nonexistent
frame.
:param im: An image object.
"""
def __init__(self, im):
if not hasattr(im, "seek"):
raise AttributeError("im must have seek method")
self.im = im
def __getitem__(self, ix):
try:
if ix:
self.im.seek(ix)
return self.im
except EOFError:
raise IndexError # end of sequence
|
gamechanger/dusty | refs/heads/master | tests/unit/warnings_test.py | 1 | from ..testcases import DustyTestCase
from dusty.warnings import Warnings
class TestWarnings(DustyTestCase):
def setUp(self):
super(TestWarnings, self).setUp()
self.warnings = Warnings()
def test_warn(self):
message_1 = 'Something is wrong, yo'
message_2 = 'Yo this thing is also wrong'
self.warnings.warn('test', message_1)
self.assertItemsEqual(self.warnings._stored, {'test': [message_1]})
self.warnings.warn('test', message_2)
self.assertItemsEqual(self.warnings._stored, {'test': [message_1, message_2]})
def test_has_warnings(self):
self.assertFalse(self.warnings.has_warnings)
self.warnings.warn('test', 'yo')
self.assertTrue(self.warnings.has_warnings)
def test_pretty_with_no_warnings(self):
self.assertEqual(self.warnings.pretty(), "")
def test_pretty(self):
message_1 = 'Something is wrong, yo'
message_2 = 'Something is very wrong, and that something takes way more than 80 characters to communicate the fact that it is wrong'
self.warnings.warn('test', message_1)
self.warnings.warn('test', message_2)
self.assertEqual(self.warnings.pretty(), "WARNING (test): Something is wrong, yo\nWARNING (test): Something is very wrong, and that something takes way more than 80 characters to\ncommunicate the fact that it is wrong\n")
def test_clear_namespace(self):
self.warnings.warn('test', 'Something is wrong, yo')
self.assertEqual(len(self.warnings._stored['test']), 1)
self.warnings.clear_namespace('test')
self.assertEqual(len(self.warnings._stored['test']), 0)
def test_clear_namespace_leaves_others_unaffected(self):
self.warnings.warn('test', 'Something is wrong, yo')
self.assertEqual(len(self.warnings._stored['test']), 1)
self.warnings.clear_namespace('some-other-namespace')
self.assertEqual(len(self.warnings._stored['test']), 1)
|
Jaccorot/django-cms | refs/heads/develop | cms/tests/test_i18n.py | 22 | try:
from importlib import import_module
except ImportError:
# Python < 2.7
from django.utils.importlib import import_module
from django.conf import settings
from django.test.utils import override_settings
from cms import api
from cms.test_utils.testcases import CMSTestCase
from cms.utils import i18n
from cms.utils.compat.dj import LANGUAGE_SESSION_KEY
@override_settings(
LANGUAGE_CODE='en',
LANGUAGES=(('fr', 'French'),
('en', 'English'),
('de', 'German'),
('es', 'Spanish')),
CMS_LANGUAGES={
1: [{'code' : 'en',
'name': 'English',
'public': True},
{'code': 'fr',
'name': 'French',
'public': False},
],
'default': {
'public': True,
'hide_untranslated': False,
},
},
SITE_ID=1,
)
class TestLanguages(CMSTestCase):
def test_language_code(self):
self.assertEqual(i18n.get_language_code('en'), 'en')
self.assertEqual(i18n.get_current_language(), 'en')
def test_get_languages_default_site(self):
result = i18n.get_languages()
self.assertEqual(2, len(result))
lang = result[0]
self.assertEqual(lang['code'], 'en')
self.assertEqual(i18n.get_language_code(lang['code']), 'en')
self.assertEqual(lang['public'], True)
lang = result[1]
self.assertEqual(lang['code'], 'fr')
self.assertEqual(i18n.get_language_code(lang['code']), 'fr')
self.assertEqual(lang['public'], False)
def test_get_languages_defined_site(self):
result = i18n.get_languages(1)
self.assertEqual(2, len(result))
lang = result[0]
self.assertEqual(lang['code'], 'en')
self.assertEqual(i18n.get_language_code(lang['code']), 'en')
self.assertEqual(lang['public'], True)
lang = result[1]
self.assertEqual(lang['code'], 'fr')
self.assertEqual(i18n.get_language_code(lang['code']), 'fr')
self.assertEqual(lang['public'], False)
def test_get_languages_undefined_site(self):
result = i18n.get_languages(66)
self.assertEqual(4, len(result))
self.assertEqual(result[0]['code'], 'fr')
self.assertEqual(i18n.get_language_code(result[0]['code']), 'fr')
self.assertEqual(result[1]['code'], 'en')
self.assertEqual(i18n.get_language_code(result[1]['code']), 'en')
self.assertEqual(result[2]['code'], 'de')
self.assertEqual(i18n.get_language_code(result[2]['code']), 'de')
self.assertEqual(result[3]['code'], 'es')
self.assertEqual(i18n.get_language_code(result[3]['code']), 'es')
for lang in result:
self.assertEqual(lang['public'], True)
self.assertEqual(lang['hide_untranslated'], False)
@override_settings(
LANGUAGE_CODE='en',
LANGUAGES=(('fr', 'French'),
('en', 'English'),
('de', 'German'),
('es', 'Spanish')),
CMS_LANGUAGES={
1: [{'code' : 'en',
'name': 'English',
'public': True},
{'code': 'fr',
'name': 'French',
'public': False},
],
},
SITE_ID=1,
)
class TestLanguagesNoDefault(CMSTestCase):
def test_get_languages_default_site(self):
result = i18n.get_languages()
self.assertEqual(2, len(result))
lang = result[0]
self.assertEqual(lang['code'], 'en')
self.assertEqual(i18n.get_language_code(lang['code']), 'en')
self.assertEqual(lang['public'], True)
lang = result[1]
self.assertEqual(lang['code'], 'fr')
self.assertEqual(i18n.get_language_code(lang['code']), 'fr')
self.assertEqual(lang['public'], False)
def test_get_languages_defined_site(self):
result = i18n.get_languages(1)
self.assertEqual(2, len(result))
lang = result[0]
self.assertEqual(lang['code'], 'en')
self.assertEqual(i18n.get_language_code(lang['code']), 'en')
self.assertEqual(lang['public'], True)
lang = result[1]
self.assertEqual(lang['code'], 'fr')
self.assertEqual(i18n.get_language_code(lang['code']), 'fr')
self.assertEqual(lang['public'], False)
def test_get_languages_undefined_site(self):
result = i18n.get_languages(66)
self.assertEqual(4, len(result))
self.assertEqual(result[0]['code'], 'fr')
self.assertEqual(i18n.get_language_code(result[0]['code']), 'fr')
self.assertEqual(result[1]['code'], 'en')
self.assertEqual(i18n.get_language_code(result[1]['code']), 'en')
self.assertEqual(result[2]['code'], 'de')
self.assertEqual(i18n.get_language_code(result[2]['code']), 'de')
self.assertEqual(result[3]['code'], 'es')
self.assertEqual(i18n.get_language_code(result[3]['code']), 'es')
for lang in result:
self.assertEqual(lang['public'], True)
self.assertEqual(lang['hide_untranslated'], True)
@override_settings(
LANGUAGE_CODE='en-us',
LANGUAGES=(('fr-ca', 'French (Canada)'),
('en-us', 'English (US)'),
('en-gb', 'English (UK)'),
('de', 'German'),
('es', 'Spanish')),
CMS_LANGUAGES={
1: [{'code' : 'en-us',
'name': 'English (US)',
'public': True},
{'code': 'fr-ca',
'name': 'French (Canada)',
'public': False},
],
'default': {
'public': True,
'hide_untranslated': False,
},
},
SITE_ID=1,
)
class TestLanguageCodesEnUS(CMSTestCase):
def test_language_code(self):
self.assertEqual(i18n.get_language_code('en-us'), 'en-us')
self.assertEqual(i18n.get_current_language(), 'en-us')
def test_get_languages_default_site(self):
result = i18n.get_languages()
self.assertEqual(2, len(result))
lang = result[0]
self.assertEqual(lang['code'], 'en-us')
self.assertEqual(i18n.get_language_code(lang['code']), 'en-us')
self.assertEqual(lang['public'], True)
lang = result[1]
self.assertEqual(lang['code'], 'fr-ca')
self.assertEqual(i18n.get_language_code(lang['code']), 'fr-ca')
self.assertEqual(lang['public'], False)
def test_get_languages_defined_site(self):
result = i18n.get_languages(1)
self.assertEqual(2, len(result))
lang = result[0]
self.assertEqual(lang['code'], 'en-us')
self.assertEqual(i18n.get_language_code(lang['code']), 'en-us')
self.assertEqual(lang['public'], True)
lang = result[1]
self.assertEqual(lang['code'], 'fr-ca')
self.assertEqual(i18n.get_language_code(lang['code']), 'fr-ca')
self.assertEqual(lang['public'], False)
def test_get_languages_undefined_site(self):
result = i18n.get_languages(66)
self.assertEqual(5, len(result))
self.assertEqual(result[0]['code'], 'fr-ca')
self.assertEqual(i18n.get_language_code(result[0]['code']), 'fr-ca')
self.assertEqual(result[1]['code'], 'en-us')
self.assertEqual(i18n.get_language_code(result[1]['code']), 'en-us')
self.assertEqual(result[2]['code'], 'en-gb')
self.assertEqual(i18n.get_language_code(result[2]['code']), 'en-gb')
self.assertEqual(result[3]['code'], 'de')
self.assertEqual(i18n.get_language_code(result[3]['code']), 'de')
self.assertEqual(result[4]['code'], 'es')
self.assertEqual(i18n.get_language_code(result[4]['code']), 'es')
for lang in result:
self.assertEqual(lang['public'], True)
self.assertEqual(lang['hide_untranslated'], False)
@override_settings(
LANGUAGE_CODE='en-gb',
LANGUAGES=(('fr-ca', 'French (Canada)'),
('en-us', 'English (US)'),
('en-gb', 'English (UK)'),
('de', 'German'),
('es', 'Spanish')),
CMS_LANGUAGES={
1: [{'code' : 'en-gb',
'name': 'English (UK)',
'public': True},
{'code': 'fr-ca',
'name': 'French (Canada)',
'public': False},
],
'default': {
'public': True,
'hide_untranslated': False,
},
},
SITE_ID=1,
)
class TestLanguageCodesEnGB(CMSTestCase):
def test_language_code(self):
self.assertEqual(i18n.get_language_code('en-gb'), 'en-gb')
self.assertEqual(i18n.get_current_language(), 'en-gb')
def test_get_languages_default_site(self):
result = i18n.get_languages()
self.assertEqual(2, len(result))
lang = result[0]
self.assertEqual(lang['code'], 'en-gb')
self.assertEqual(i18n.get_language_code(lang['code']), 'en-gb')
self.assertEqual(lang['public'], True)
lang = result[1]
self.assertEqual(lang['code'], 'fr-ca')
self.assertEqual(i18n.get_language_code(lang['code']), 'fr-ca')
self.assertEqual(lang['public'], False)
def test_get_languages_defined_site(self):
result = i18n.get_languages(1)
self.assertEqual(2, len(result))
lang = result[0]
self.assertEqual(lang['code'], 'en-gb')
self.assertEqual(i18n.get_language_code(lang['code']), 'en-gb')
self.assertEqual(lang['public'], True)
lang = result[1]
self.assertEqual(lang['code'], 'fr-ca')
self.assertEqual(i18n.get_language_code(lang['code']), 'fr-ca')
self.assertEqual(lang['public'], False)
def test_get_languages_undefined_site(self):
result = i18n.get_languages(66)
self.assertEqual(5, len(result))
self.assertEqual(result[0]['code'], 'fr-ca')
self.assertEqual(i18n.get_language_code(result[0]['code']), 'fr-ca')
self.assertEqual(result[1]['code'], 'en-us')
self.assertEqual(i18n.get_language_code(result[1]['code']), 'en-us')
self.assertEqual(result[2]['code'], 'en-gb')
self.assertEqual(i18n.get_language_code(result[2]['code']), 'en-gb')
self.assertEqual(result[3]['code'], 'de')
self.assertEqual(i18n.get_language_code(result[3]['code']), 'de')
self.assertEqual(result[4]['code'], 'es')
self.assertEqual(i18n.get_language_code(result[4]['code']), 'es')
for lang in result:
self.assertEqual(lang['public'], True)
self.assertEqual(lang['hide_untranslated'], False)
@override_settings(
LANGUAGE_CODE='en',
LANGUAGES=[
('en', 'English'),
('de', 'German'),
('fr', 'French')
],
CMS_LANGUAGES={
1: [{'code': 'de',
'name': 'German',
'public': True},
{'code': 'fr',
'name': 'French',
'public': True}],
'default': {
'fallbacks': ['de', 'fr'],
},
},
SITE_ID=1,
)
class TestLanguagesNotInCMSLanguages(CMSTestCase):
def test_get_fallback_languages(self):
languages = i18n.get_fallback_languages('en', 1)
self.assertEqual(languages, ['de', 'fr'])
@override_settings(
LANGUAGE_CODE='en',
LANGUAGES=(('fr', 'French'),
('en', 'English'),
('de', 'German'),
('es', 'Spanish')),
CMS_LANGUAGES={
1: [{'code' : 'en',
'name': 'English',
'public': False},
{'code': 'fr',
'name': 'French',
'public': True},
],
'default': {
'fallbacks': ['en', 'fr'],
'redirect_on_fallback': False,
'public': True,
'hide_untranslated': False,
}
},
SITE_ID=1,
)
class TestLanguageFallbacks(CMSTestCase):
def test_language_code(self):
api.create_page("home", "nav_playground.html", "fr", published=True)
response = self.client.get('/')
self.assertEqual(response.status_code, 302)
response = self.client.get('/en/')
self.assertEqual(response.status_code, 302)
self.assertRedirects(response, '/fr/')
@override_settings(
CMS_LANGUAGES={
1: [{'code' : 'en',
'name': 'English',
'public': True},
{'code': 'fr',
'name': 'French',
'public': True},
]
},
)
def test_session_language(self):
page = api.create_page("home", "nav_playground.html", "en", published=True)
api.create_title('fr', "home", page)
page.publish('fr')
page.publish('en')
response = self.client.get('/')
self.assertEqual(response.status_code, 302)
self.assertRedirects(response, '/en/')
engine = import_module(settings.SESSION_ENGINE)
store = engine.SessionStore()
store.save() # we need to make load() work, or the cookie is worthless
self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key
# ugly and long set of session
session = self.client.session
session[LANGUAGE_SESSION_KEY] = 'fr'
session.save()
response = self.client.get('/')
self.assertEqual(response.status_code, 302)
self.assertRedirects(response, '/fr/')
self.client.get('/en/')
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], 'en')
response = self.client.get('/')
self.assertEqual(response.status_code, 302)
self.assertRedirects(response, '/en/')
|
frreiss/tensorflow-fred | refs/heads/master | tensorflow/python/ops/signal/mel_ops.py | 5 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""mel conversion ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops.signal import shape_ops
from tensorflow.python.util import dispatch
from tensorflow.python.util.tf_export import tf_export
# mel spectrum constants.
_MEL_BREAK_FREQUENCY_HERTZ = 700.0
_MEL_HIGH_FREQUENCY_Q = 1127.0
def _mel_to_hertz(mel_values, name=None):
"""Converts frequencies in `mel_values` from the mel scale to linear scale.
Args:
mel_values: A `Tensor` of frequencies in the mel scale.
name: An optional name for the operation.
Returns:
A `Tensor` of the same shape and type as `mel_values` containing linear
scale frequencies in Hertz.
"""
with ops.name_scope(name, 'mel_to_hertz', [mel_values]):
mel_values = ops.convert_to_tensor(mel_values)
return _MEL_BREAK_FREQUENCY_HERTZ * (
math_ops.exp(mel_values / _MEL_HIGH_FREQUENCY_Q) - 1.0
)
def _hertz_to_mel(frequencies_hertz, name=None):
"""Converts frequencies in `frequencies_hertz` in Hertz to the mel scale.
Args:
frequencies_hertz: A `Tensor` of frequencies in Hertz.
name: An optional name for the operation.
Returns:
A `Tensor` of the same shape and type of `frequencies_hertz` containing
frequencies in the mel scale.
"""
with ops.name_scope(name, 'hertz_to_mel', [frequencies_hertz]):
frequencies_hertz = ops.convert_to_tensor(frequencies_hertz)
return _MEL_HIGH_FREQUENCY_Q * math_ops.log(
1.0 + (frequencies_hertz / _MEL_BREAK_FREQUENCY_HERTZ))
def _validate_arguments(num_mel_bins, sample_rate,
lower_edge_hertz, upper_edge_hertz, dtype):
"""Checks the inputs to linear_to_mel_weight_matrix."""
if num_mel_bins <= 0:
raise ValueError('num_mel_bins must be positive. Got: %s' % num_mel_bins)
if lower_edge_hertz < 0.0:
raise ValueError('lower_edge_hertz must be non-negative. Got: %s' %
lower_edge_hertz)
if lower_edge_hertz >= upper_edge_hertz:
raise ValueError('lower_edge_hertz %.1f >= upper_edge_hertz %.1f' %
(lower_edge_hertz, upper_edge_hertz))
if not isinstance(sample_rate, ops.Tensor):
if sample_rate <= 0.0:
raise ValueError('sample_rate must be positive. Got: %s' % sample_rate)
if upper_edge_hertz > sample_rate / 2:
raise ValueError('upper_edge_hertz must not be larger than the Nyquist '
'frequency (sample_rate / 2). Got %s for sample_rate: %s'
% (upper_edge_hertz, sample_rate))
if not dtype.is_floating:
raise ValueError('dtype must be a floating point type. Got: %s' % dtype)
@tf_export('signal.linear_to_mel_weight_matrix')
@dispatch.add_dispatch_support
def linear_to_mel_weight_matrix(num_mel_bins=20,
num_spectrogram_bins=129,
sample_rate=8000,
lower_edge_hertz=125.0,
upper_edge_hertz=3800.0,
dtype=dtypes.float32,
name=None):
"""Returns a matrix to warp linear scale spectrograms to the [mel scale][mel].
Returns a weight matrix that can be used to re-weight a `Tensor` containing
`num_spectrogram_bins` linearly sampled frequency information from
`[0, sample_rate / 2]` into `num_mel_bins` frequency information from
`[lower_edge_hertz, upper_edge_hertz]` on the [mel scale][mel].
This function follows the [Hidden Markov Model Toolkit
(HTK)](http://htk.eng.cam.ac.uk/) convention, defining the mel scale in
terms of a frequency in hertz according to the following formula:
$$\textrm{mel}(f) = 2595 * \textrm{log}_{10}(1 + \frac{f}{700})$$
In the returned matrix, all the triangles (filterbanks) have a peak value
of 1.0.
For example, the returned matrix `A` can be used to right-multiply a
spectrogram `S` of shape `[frames, num_spectrogram_bins]` of linear
scale spectrum values (e.g. STFT magnitudes) to generate a "mel spectrogram"
`M` of shape `[frames, num_mel_bins]`.
# `S` has shape [frames, num_spectrogram_bins]
# `M` has shape [frames, num_mel_bins]
M = tf.matmul(S, A)
The matrix can be used with `tf.tensordot` to convert an arbitrary rank
`Tensor` of linear-scale spectral bins into the mel scale.
# S has shape [..., num_spectrogram_bins].
# M has shape [..., num_mel_bins].
M = tf.tensordot(S, A, 1)
Args:
num_mel_bins: Python int. How many bands in the resulting mel spectrum.
num_spectrogram_bins: An integer `Tensor`. How many bins there are in the
source spectrogram data, which is understood to be `fft_size // 2 + 1`,
i.e. the spectrogram only contains the nonredundant FFT bins.
sample_rate: An integer or float `Tensor`. Samples per second of the input
signal used to create the spectrogram. Used to figure out the frequencies
corresponding to each spectrogram bin, which dictates how they are mapped
into the mel scale.
lower_edge_hertz: Python float. Lower bound on the frequencies to be
included in the mel spectrum. This corresponds to the lower edge of the
lowest triangular band.
upper_edge_hertz: Python float. The desired top edge of the highest
frequency band.
dtype: The `DType` of the result matrix. Must be a floating point type.
name: An optional name for the operation.
Returns:
A `Tensor` of shape `[num_spectrogram_bins, num_mel_bins]`.
Raises:
ValueError: If `num_mel_bins`/`num_spectrogram_bins`/`sample_rate` are not
positive, `lower_edge_hertz` is negative, frequency edges are incorrectly
ordered, `upper_edge_hertz` is larger than the Nyquist frequency.
[mel]: https://en.wikipedia.org/wiki/Mel_scale
"""
with ops.name_scope(name, 'linear_to_mel_weight_matrix') as name:
# Convert Tensor `sample_rate` to float, if possible.
if isinstance(sample_rate, ops.Tensor):
maybe_const_val = tensor_util.constant_value(sample_rate)
if maybe_const_val is not None:
sample_rate = maybe_const_val
# Note: As num_spectrogram_bins is passed to `math_ops.linspace`
# and the validation is already done in linspace (both in shape function
# and in kernel), there is no need to validate num_spectrogram_bins here.
_validate_arguments(num_mel_bins, sample_rate,
lower_edge_hertz, upper_edge_hertz, dtype)
# This function can be constant folded by graph optimization since there are
# no Tensor inputs.
sample_rate = math_ops.cast(
sample_rate, dtype, name='sample_rate')
lower_edge_hertz = ops.convert_to_tensor(
lower_edge_hertz, dtype, name='lower_edge_hertz')
upper_edge_hertz = ops.convert_to_tensor(
upper_edge_hertz, dtype, name='upper_edge_hertz')
zero = ops.convert_to_tensor(0.0, dtype)
# HTK excludes the spectrogram DC bin.
bands_to_zero = 1
nyquist_hertz = sample_rate / 2.0
linear_frequencies = math_ops.linspace(
zero, nyquist_hertz, num_spectrogram_bins)[bands_to_zero:]
spectrogram_bins_mel = array_ops.expand_dims(
_hertz_to_mel(linear_frequencies), 1)
# Compute num_mel_bins triples of (lower_edge, center, upper_edge). The
# center of each band is the lower and upper edge of the adjacent bands.
# Accordingly, we divide [lower_edge_hertz, upper_edge_hertz] into
# num_mel_bins + 2 pieces.
band_edges_mel = shape_ops.frame(
math_ops.linspace(_hertz_to_mel(lower_edge_hertz),
_hertz_to_mel(upper_edge_hertz),
num_mel_bins + 2), frame_length=3, frame_step=1)
# Split the triples up and reshape them into [1, num_mel_bins] tensors.
lower_edge_mel, center_mel, upper_edge_mel = tuple(array_ops.reshape(
t, [1, num_mel_bins]) for t in array_ops.split(
band_edges_mel, 3, axis=1))
# Calculate lower and upper slopes for every spectrogram bin.
# Line segments are linear in the mel domain, not Hertz.
lower_slopes = (spectrogram_bins_mel - lower_edge_mel) / (
center_mel - lower_edge_mel)
upper_slopes = (upper_edge_mel - spectrogram_bins_mel) / (
upper_edge_mel - center_mel)
# Intersect the line segments with each other and zero.
mel_weights_matrix = math_ops.maximum(
zero, math_ops.minimum(lower_slopes, upper_slopes))
# Re-add the zeroed lower bins we sliced out above.
return array_ops.pad(
mel_weights_matrix, [[bands_to_zero, 0], [0, 0]], name=name)
|
obi-two/Rebelion | refs/heads/master | data/scripts/templates/object/tangible/medicine/crafted/shared_medpack_wound_action_d.py | 2 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/medicine/crafted/shared_medpack_wound_action_d.iff"
result.attribute_template_id = 7
result.stfName("medicine_name","medpack_wound_action_d")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
levilucio/SyVOLT | refs/heads/master | UMLRT2Kiltera_MM/Properties/positive/Himesis/HExitpoint2procdefparTrueNOATTR_IsolatedLHS.py | 1 |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import cPickle as pickle
from uuid import UUID
class HExitpoint2procdefparTrueNOATTR_IsolatedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HExitpoint2procdefparTrueNOATTR_IsolatedLHS.
"""
# Flag this instance as compiled now
self.is_compiled = True
super(HExitpoint2procdefparTrueNOATTR_IsolatedLHS, self).__init__(name='HExitpoint2procdefparTrueNOATTR_IsolatedLHS', num_nodes=2, edges=[])
# Add the edges
self.add_edges([])
# Set the graph attributes
self["mm__"] = pickle.loads("""(lp1
S'MT_pre__UMLRT2Kiltera_MM'
p2
aS'MoTifRule'
p3
a.""")
self["MT_constraint__"] = """#===============================================================================
# This code is executed after the nodes in the LHS have been matched.
# You can access a matched node labelled n by: PreNode('n').
# To access attribute x of node n, use: PreNode('n')['x'].
# The given constraint must evaluate to a boolean expression:
# returning True enables the rule to be applied,
# returning False forbids the rule from being applied.
#===============================================================================
return True
"""
self["name"] = """"""
self["GUID__"] = UUID('28d34143-34b5-4c33-b9d8-726e2b60d13f')
# Set the node attributes
self.vs[0]["MT_subtypeMatching__"] = False
self.vs[0]["MT_pre__classtype"] = """
#===============================================================================
# This code is executed when evaluating if a node shall be matched by this rule.
# You can access the value of the current node's attribute value by: attr_value.
# You can access any attribute x of this node by: this['x'].
# If the constraint relies on attribute values from other nodes,
# use the LHS/NAC constraint instead.
# The given constraint must evaluate to a boolean expression.
#===============================================================================
return True
"""
self.vs[0]["MT_label__"] = """1"""
self.vs[0]["MT_subtypes__"] = pickle.loads("""(lp1
.""")
self.vs[0]["MT_dirty__"] = False
self.vs[0]["mm__"] = """MT_pre__State"""
self.vs[0]["MT_pre__cardinality"] = """
#===============================================================================
# This code is executed when evaluating if a node shall be matched by this rule.
# You can access the value of the current node's attribute value by: attr_value.
# You can access any attribute x of this node by: this['x'].
# If the constraint relies on attribute values from other nodes,
# use the LHS/NAC constraint instead.
# The given constraint must evaluate to a boolean expression.
#===============================================================================
return True
"""
self.vs[0]["MT_pre__name"] = """
#===============================================================================
# This code is executed when evaluating if a node shall be matched by this rule.
# You can access the value of the current node's attribute value by: attr_value.
# You can access any attribute x of this node by: this['x'].
# If the constraint relies on attribute values from other nodes,
# use the LHS/NAC constraint instead.
# The given constraint must evaluate to a boolean expression.
#===============================================================================
return True
"""
self.vs[0]["GUID__"] = UUID('18813039-0a0f-44f3-83cc-1ffb3ccb1758')
self.vs[1]["MT_subtypeMatching__"] = False
self.vs[1]["MT_pre__classtype"] = """
#===============================================================================
# This code is executed when evaluating if a node shall be matched by this rule.
# You can access the value of the current node's attribute value by: attr_value.
# You can access any attribute x of this node by: this['x'].
# If the constraint relies on attribute values from other nodes,
# use the LHS/NAC constraint instead.
# The given constraint must evaluate to a boolean expression.
#===============================================================================
return True
"""
self.vs[1]["MT_label__"] = """12"""
self.vs[1]["MT_subtypes__"] = pickle.loads("""(lp1
.""")
self.vs[1]["MT_dirty__"] = False
self.vs[1]["mm__"] = """MT_pre__ExitPoint"""
self.vs[1]["MT_pre__cardinality"] = """
#===============================================================================
# This code is executed when evaluating if a node shall be matched by this rule.
# You can access the value of the current node's attribute value by: attr_value.
# You can access any attribute x of this node by: this['x'].
# If the constraint relies on attribute values from other nodes,
# use the LHS/NAC constraint instead.
# The given constraint must evaluate to a boolean expression.
#===============================================================================
return True
"""
self.vs[1]["MT_pre__name"] = """
#===============================================================================
# This code is executed when evaluating if a node shall be matched by this rule.
# You can access the value of the current node's attribute value by: attr_value.
# You can access any attribute x of this node by: this['x'].
# If the constraint relies on attribute values from other nodes,
# use the LHS/NAC constraint instead.
# The given constraint must evaluate to a boolean expression.
#===============================================================================
return True
"""
self.vs[1]["GUID__"] = UUID('cf7e2cb2-cca0-4619-bdc3-e2b1fdf7cfb4')
def eval_classtype1(self, attr_value, this):
#===============================================================================
# This code is executed when evaluating if a node shall be matched by this rule.
# You can access the value of the current node's attribute value by: attr_value.
# You can access any attribute x of this node by: this['x'].
# If the constraint relies on attribute values from other nodes,
# use the LHS/NAC constraint instead.
# The given constraint must evaluate to a boolean expression.
#===============================================================================
return True
def eval_cardinality1(self, attr_value, this):
#===============================================================================
# This code is executed when evaluating if a node shall be matched by this rule.
# You can access the value of the current node's attribute value by: attr_value.
# You can access any attribute x of this node by: this['x'].
# If the constraint relies on attribute values from other nodes,
# use the LHS/NAC constraint instead.
# The given constraint must evaluate to a boolean expression.
#===============================================================================
return True
def eval_name1(self, attr_value, this):
#===============================================================================
# This code is executed when evaluating if a node shall be matched by this rule.
# You can access the value of the current node's attribute value by: attr_value.
# You can access any attribute x of this node by: this['x'].
# If the constraint relies on attribute values from other nodes,
# use the LHS/NAC constraint instead.
# The given constraint must evaluate to a boolean expression.
#===============================================================================
return True
def eval_classtype12(self, attr_value, this):
#===============================================================================
# This code is executed when evaluating if a node shall be matched by this rule.
# You can access the value of the current node's attribute value by: attr_value.
# You can access any attribute x of this node by: this['x'].
# If the constraint relies on attribute values from other nodes,
# use the LHS/NAC constraint instead.
# The given constraint must evaluate to a boolean expression.
#===============================================================================
return True
def eval_cardinality12(self, attr_value, this):
#===============================================================================
# This code is executed when evaluating if a node shall be matched by this rule.
# You can access the value of the current node's attribute value by: attr_value.
# You can access any attribute x of this node by: this['x'].
# If the constraint relies on attribute values from other nodes,
# use the LHS/NAC constraint instead.
# The given constraint must evaluate to a boolean expression.
#===============================================================================
return True
def eval_name12(self, attr_value, this):
#===============================================================================
# This code is executed when evaluating if a node shall be matched by this rule.
# You can access the value of the current node's attribute value by: attr_value.
# You can access any attribute x of this node by: this['x'].
# If the constraint relies on attribute values from other nodes,
# use the LHS/NAC constraint instead.
# The given constraint must evaluate to a boolean expression.
#===============================================================================
return True
def constraint(self, PreNode, graph):
"""
Executable constraint code.
@param PreNode: Function taking an integer as parameter
and returns the node corresponding to that label.
"""
#===============================================================================
# This code is executed after the nodes in the LHS have been matched.
# You can access a matched node labelled n by: PreNode('n').
# To access attribute x of node n, use: PreNode('n')['x'].
# The given constraint must evaluate to a boolean expression:
# returning True enables the rule to be applied,
# returning False forbids the rule from being applied.
#===============================================================================
return True
|
bhargav2408/python-for-android | refs/heads/master | python3-alpha/extra_modules/gdata/Crypto/PublicKey/RSA.py | 45 | #
# RSA.py : RSA encryption/decryption
#
# Part of the Python Cryptography Toolkit
#
# Distribute and use freely; there are no restrictions on further
# dissemination and usage except those imposed by the laws of your
# country of residence. This software is provided "as is" without
# warranty of fitness for use or suitability for any purpose, express
# or implied. Use at your own risk or not at all.
#
__revision__ = "$Id: RSA.py,v 1.20 2004/05/06 12:52:54 akuchling Exp $"
from Crypto.PublicKey import pubkey
from Crypto.Util import number
try:
from Crypto.PublicKey import _fastmath
except ImportError:
_fastmath = None
class error (Exception):
pass
def generate(bits, randfunc, progress_func=None):
"""generate(bits:int, randfunc:callable, progress_func:callable)
Generate an RSA key of length 'bits', using 'randfunc' to get
random data and 'progress_func', if present, to display
the progress of the key generation.
"""
obj=RSAobj()
# Generate the prime factors of n
if progress_func:
progress_func('p,q\n')
p = q = 1
while number.size(p*q) < bits:
p = pubkey.getPrime(bits/2, randfunc)
q = pubkey.getPrime(bits/2, randfunc)
# p shall be smaller than q (for calc of u)
if p > q:
(p, q)=(q, p)
obj.p = p
obj.q = q
if progress_func:
progress_func('u\n')
obj.u = pubkey.inverse(obj.p, obj.q)
obj.n = obj.p*obj.q
obj.e = 65537
if progress_func:
progress_func('d\n')
obj.d=pubkey.inverse(obj.e, (obj.p-1)*(obj.q-1))
assert bits <= 1+obj.size(), "Generated key is too small"
return obj
def construct(tuple):
"""construct(tuple:(long,) : RSAobj
Construct an RSA object from a 2-, 3-, 5-, or 6-tuple of numbers.
"""
obj=RSAobj()
if len(tuple) not in [2,3,5,6]:
raise error('argument for construct() wrong length')
for i in range(len(tuple)):
field = obj.keydata[i]
setattr(obj, field, tuple[i])
if len(tuple) >= 5:
# Ensure p is smaller than q
if obj.p>obj.q:
(obj.p, obj.q)=(obj.q, obj.p)
if len(tuple) == 5:
# u not supplied, so we're going to have to compute it.
obj.u=pubkey.inverse(obj.p, obj.q)
return obj
class RSAobj(pubkey.pubkey):
keydata = ['n', 'e', 'd', 'p', 'q', 'u']
def _encrypt(self, plaintext, K=''):
if self.n<=plaintext:
raise error('Plaintext too large')
return (pow(plaintext, self.e, self.n),)
def _decrypt(self, ciphertext):
if (not hasattr(self, 'd')):
raise error('Private key not available in this object')
if self.n<=ciphertext[0]:
raise error('Ciphertext too large')
return pow(ciphertext[0], self.d, self.n)
def _sign(self, M, K=''):
return (self._decrypt((M,)),)
def _verify(self, M, sig):
m2=self._encrypt(sig[0])
if m2[0]==M:
return 1
else: return 0
def _blind(self, M, B):
tmp = pow(B, self.e, self.n)
return (M * tmp) % self.n
def _unblind(self, M, B):
tmp = pubkey.inverse(B, self.n)
return (M * tmp) % self.n
def can_blind (self):
"""can_blind() : bool
Return a Boolean value recording whether this algorithm can
blind data. (This does not imply that this
particular key object has the private information required to
to blind a message.)
"""
return 1
def size(self):
"""size() : int
Return the maximum number of bits that can be handled by this key.
"""
return number.size(self.n) - 1
def has_private(self):
"""has_private() : bool
Return a Boolean denoting whether the object contains
private components.
"""
if hasattr(self, 'd'):
return 1
else: return 0
def publickey(self):
"""publickey(): RSAobj
Return a new key object containing only the public key information.
"""
return construct((self.n, self.e))
class RSAobj_c(pubkey.pubkey):
keydata = ['n', 'e', 'd', 'p', 'q', 'u']
def __init__(self, key):
self.key = key
def __getattr__(self, attr):
if attr in self.keydata:
return getattr(self.key, attr)
else:
if attr in self.__dict__:
self.__dict__[attr]
else:
raise AttributeError('%s instance has no attribute %s' % (self.__class__, attr))
def __getstate__(self):
d = {}
for k in self.keydata:
if hasattr(self.key, k):
d[k]=getattr(self.key, k)
return d
def __setstate__(self, state):
n,e = state['n'], state['e']
if 'd' not in state:
self.key = _fastmath.rsa_construct(n,e)
else:
d = state['d']
if 'q' not in state:
self.key = _fastmath.rsa_construct(n,e,d)
else:
p, q, u = state['p'], state['q'], state['u']
self.key = _fastmath.rsa_construct(n,e,d,p,q,u)
def _encrypt(self, plain, K):
return (self.key._encrypt(plain),)
def _decrypt(self, cipher):
return self.key._decrypt(cipher[0])
def _sign(self, M, K):
return (self.key._sign(M),)
def _verify(self, M, sig):
return self.key._verify(M, sig[0])
def _blind(self, M, B):
return self.key._blind(M, B)
def _unblind(self, M, B):
return self.key._unblind(M, B)
def can_blind (self):
return 1
def size(self):
return self.key.size()
def has_private(self):
return self.key.has_private()
def publickey(self):
return construct_c((self.key.n, self.key.e))
def generate_c(bits, randfunc, progress_func = None):
# Generate the prime factors of n
if progress_func:
progress_func('p,q\n')
p = q = 1
while number.size(p*q) < bits:
p = pubkey.getPrime(bits/2, randfunc)
q = pubkey.getPrime(bits/2, randfunc)
# p shall be smaller than q (for calc of u)
if p > q:
(p, q)=(q, p)
if progress_func:
progress_func('u\n')
u=pubkey.inverse(p, q)
n=p*q
e = 65537
if progress_func:
progress_func('d\n')
d=pubkey.inverse(e, (p-1)*(q-1))
key = _fastmath.rsa_construct(n,e,d,p,q,u)
obj = RSAobj_c(key)
## print p
## print q
## print number.size(p), number.size(q), number.size(q*p),
## print obj.size(), bits
assert bits <= 1+obj.size(), "Generated key is too small"
return obj
def construct_c(tuple):
key = _fastmath.rsa_construct(*tuple)
return RSAobj_c(key)
object = RSAobj
generate_py = generate
construct_py = construct
if _fastmath:
#print "using C version of RSA"
generate = generate_c
construct = construct_c
error = _fastmath.error
|
wazeerzulfikar/scikit-learn | refs/heads/master | examples/feature_selection/plot_f_test_vs_mi.py | 82 | """
===========================================
Comparison of F-test and mutual information
===========================================
This example illustrates the differences between univariate F-test statistics
and mutual information.
We consider 3 features x_1, x_2, x_3 distributed uniformly over [0, 1], the
target depends on them as follows:
y = x_1 + sin(6 * pi * x_2) + 0.1 * N(0, 1), that is the third features is
completely irrelevant.
The code below plots the dependency of y against individual x_i and normalized
values of univariate F-tests statistics and mutual information.
As F-test captures only linear dependency, it rates x_1 as the most
discriminative feature. On the other hand, mutual information can capture any
kind of dependency between variables and it rates x_2 as the most
discriminative feature, which probably agrees better with our intuitive
perception for this example. Both methods correctly marks x_3 as irrelevant.
"""
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.feature_selection import f_regression, mutual_info_regression
np.random.seed(0)
X = np.random.rand(1000, 3)
y = X[:, 0] + np.sin(6 * np.pi * X[:, 1]) + 0.1 * np.random.randn(1000)
f_test, _ = f_regression(X, y)
f_test /= np.max(f_test)
mi = mutual_info_regression(X, y)
mi /= np.max(mi)
plt.figure(figsize=(15, 5))
for i in range(3):
plt.subplot(1, 3, i + 1)
plt.scatter(X[:, i], y, edgecolor='black', s=20)
plt.xlabel("$x_{}$".format(i + 1), fontsize=14)
if i == 0:
plt.ylabel("$y$", fontsize=14)
plt.title("F-test={:.2f}, MI={:.2f}".format(f_test[i], mi[i]),
fontsize=16)
plt.show()
|
jtrobec/pants | refs/heads/master | contrib/node/src/python/pants/contrib/node/register.py | 10 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.build_graph.build_file_aliases import BuildFileAliases
from pants.goal.task_registrar import TaskRegistrar as task
from pants.contrib.node.subsystems.resolvers.node_preinstalled_module_resolver import \
NodePreinstalledModuleResolver
from pants.contrib.node.subsystems.resolvers.npm_resolver import NpmResolver
from pants.contrib.node.targets.node_module import NodeModule
from pants.contrib.node.targets.node_preinstalled_module import NodePreinstalledModule
from pants.contrib.node.targets.node_remote_module import NodeRemoteModule
from pants.contrib.node.targets.node_test import NodeTest as NodeTestTarget
from pants.contrib.node.tasks.node_repl import NodeRepl
from pants.contrib.node.tasks.node_resolve import NodeResolve
from pants.contrib.node.tasks.node_run import NodeRun
from pants.contrib.node.tasks.node_test import NodeTest as NodeTestTask
def build_file_aliases():
return BuildFileAliases(
targets={
'node_module': NodeModule,
'node_preinstalled_module': NodePreinstalledModule,
'node_remote_module': NodeRemoteModule,
'node_test': NodeTestTarget,
},
)
def register_goals():
task(name='node', action=NodeRepl).install('repl')
task(name='node', action=NodeResolve).install('resolve')
task(name='node', action=NodeRun).install('run')
task(name='node', action=NodeTestTask).install('test')
def global_subsystems():
return (NodePreinstalledModuleResolver, NpmResolver)
|
moandcompany/luigi | refs/heads/master | test/contrib/test_ssh.py | 5 | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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.
#
"""
Integration tests for ssh module.
"""
from __future__ import print_function
import os
import random
import socket
import subprocess
from helpers import unittest
import target_test
from luigi.contrib.ssh import RemoteContext, RemoteFileSystem, RemoteTarget, RemoteCalledProcessError
from luigi.target import MissingParentDirectory, FileAlreadyExists
working_ssh_host = os.environ.get('SSH_TEST_HOST', 'localhost')
# set this to a working ssh host string (e.g. "localhost") to activate integration tests
# The following tests require a working ssh server at `working_ssh_host`
# the test runner can ssh into using password-less authentication
# since `nc` has different syntax on different platforms
# we use a short python command to start
# a 'hello'-server on the remote machine
HELLO_SERVER_CMD = """
import socket, sys
listener = socket.socket()
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(('localhost', 2134))
listener.listen(1)
sys.stdout.write('ready')
sys.stdout.flush()
conn = listener.accept()[0]
conn.sendall(b'hello')
"""
try:
x = subprocess.check_output(
"ssh %s -S none -o BatchMode=yes 'echo 1'" % working_ssh_host,
shell=True
)
if x != b'1\n':
raise unittest.SkipTest('Not able to connect to ssh server')
except Exception:
raise unittest.SkipTest('Not able to connect to ssh server')
class TestRemoteContext(unittest.TestCase):
def setUp(self):
self.context = RemoteContext(working_ssh_host)
def tearDown(self):
try:
self.remote_server_handle.terminate()
except Exception:
pass
def test_check_output(self):
""" Test check_output ssh
Assumes the running user can ssh to working_ssh_host
"""
output = self.context.check_output(["echo", "-n", "luigi"])
self.assertEqual(output, b"luigi")
def test_tunnel(self):
print("Setting up remote listener...")
self.remote_server_handle = self.context.Popen([
"python", "-c", '"{0}"'.format(HELLO_SERVER_CMD)
], stdout=subprocess.PIPE)
print("Setting up tunnel")
with self.context.tunnel(2135, 2134):
print("Tunnel up!")
# hack to make sure the listener process is up
# and running before we write to it
server_output = self.remote_server_handle.stdout.read(5)
self.assertEqual(server_output, b"ready")
print("Connecting to server via tunnel")
s = socket.socket()
s.connect(("localhost", 2135))
print("Receiving...",)
response = s.recv(5)
self.assertEqual(response, b"hello")
print("Closing connection")
s.close()
print("Waiting for listener...")
output, _ = self.remote_server_handle.communicate()
self.assertEqual(self.remote_server_handle.returncode, 0)
print("Closing tunnel")
class TestRemoteTarget(unittest.TestCase):
""" These tests assume RemoteContext working
in order for setUp and tearDown to work
"""
def setUp(self):
self.ctx = RemoteContext(working_ssh_host)
self.filepath = "/tmp/luigi_remote_test.dat"
self.target = RemoteTarget(
self.filepath,
working_ssh_host,
)
self.ctx.check_output(["rm", "-rf", self.filepath])
self.ctx.check_output(["echo -n 'hello' >", self.filepath])
def tearDown(self):
self.ctx.check_output(["rm", "-rf", self.filepath])
def test_exists(self):
self.assertTrue(self.target.exists())
no_file = RemoteTarget(
"/tmp/_file_that_doesnt_exist_",
working_ssh_host,
)
self.assertFalse(no_file.exists())
def test_remove(self):
self.target.remove()
self.assertRaises(
subprocess.CalledProcessError,
self.ctx.check_output,
["cat", self.filepath]
)
def test_open(self):
f = self.target.open('r')
file_content = f.read()
f.close()
self.assertEqual(file_content, "hello")
self.assertTrue(self.target.fs.exists(self.filepath))
self.assertFalse(self.target.fs.isdir(self.filepath))
def test_context_manager(self):
with self.target.open('r') as f:
file_content = f.read()
self.assertEqual(file_content, "hello")
class TestRemoteFilesystem(unittest.TestCase):
def setUp(self):
self.fs = RemoteFileSystem(working_ssh_host)
self.root = '/tmp/luigi-remote-test'
self.directory = self.root + '/dir'
self.filepath = self.directory + '/file'
self.target = RemoteTarget(
self.filepath,
working_ssh_host,
)
self.fs.remote_context.check_output(['rm', '-rf', self.root])
self.addCleanup(self.fs.remote_context.check_output, ['rm', '-rf', self.root])
def test_mkdir(self):
self.assertFalse(self.fs.isdir(self.directory))
self.assertRaises(MissingParentDirectory, self.fs.mkdir, self.directory, parents=False)
self.fs.mkdir(self.directory)
self.assertTrue(self.fs.isdir(self.directory))
# Shouldn't throw
self.fs.mkdir(self.directory)
self.assertRaises(FileAlreadyExists, self.fs.mkdir, self.directory, raise_if_exists=True)
def test_list(self):
with self.target.open('w'):
pass
self.assertEquals([self.target.path], list(self.fs.listdir(self.directory)))
class TestGetAttrRecursion(unittest.TestCase):
def test_recursion_on_delete(self):
target = RemoteTarget("/etc/this/does/not/exist", working_ssh_host)
with self.assertRaises(RemoteCalledProcessError):
with target.open('w') as fh:
fh.write("test")
class TestRemoteTargetAtomicity(unittest.TestCase, target_test.FileSystemTargetTestMixin):
path = '/tmp/luigi_remote_atomic_test.txt'
ctx = RemoteContext(working_ssh_host)
def create_target(self, format=None):
return RemoteTarget(self.path, working_ssh_host, format=format)
def _exists(self, path):
try:
self.ctx.check_output(["test", "-e", path])
except subprocess.CalledProcessError as e:
if e.returncode == 1:
return False
else:
raise
return True
def assertCleanUp(self, tp):
self.assertFalse(self._exists(tp))
def setUp(self):
self.ctx.check_output(["rm", "-rf", self.path])
self.local_file = '/tmp/local_luigi_remote_atomic_test.txt'
if os.path.exists(self.local_file):
os.remove(self.local_file)
def tearDown(self):
self.ctx.check_output(["rm", "-rf", self.path])
if os.path.exists(self.local_file):
os.remove(self.local_file)
def test_put(self):
f = open(self.local_file, 'w')
f.write('hello')
f.close()
t = RemoteTarget(self.path, working_ssh_host)
t.put(self.local_file)
self.assertTrue(self._exists(self.path))
def test_get(self):
self.ctx.check_output(["echo -n 'hello' >", self.path])
t = RemoteTarget(self.path, working_ssh_host)
t.get(self.local_file)
f = open(self.local_file, 'r')
file_content = f.read()
self.assertEqual(file_content, 'hello')
class TestRemoteTargetCreateDirectories(TestRemoteTargetAtomicity):
path = '/tmp/%s/xyz/luigi_remote_atomic_test.txt' % random.randint(0, 999999999)
class TestRemoteTargetRelative(TestRemoteTargetAtomicity):
path = 'luigi_remote_atomic_test.txt'
|
blzr/enigma2 | refs/heads/develop | lib/python/Screens/PictureInPicture.py | 3 | from Screens.Screen import Screen
from Screens.Dish import Dishpip
from enigma import ePoint, eSize, eRect, eServiceCenter, getBestPlayableServiceReference, eServiceReference, eTimer
from Components.SystemInfo import SystemInfo
from Components.VideoWindow import VideoWindow
from Components.Sources.StreamService import StreamServiceList
from Components.config import config, ConfigPosition, ConfigSelection
from Tools import Notifications
from Screens.MessageBox import MessageBox
MAX_X = 720
MAX_Y = 576
pip_config_initialized = False
PipPigModeEnabled = False
PipPigModeTimer = eTimer()
def timedStopPipPigMode():
from Screens.InfoBar import InfoBar
if InfoBar.instance and InfoBar.instance.session:
if SystemInfo["hasPIPVisibleProc"]:
open(SystemInfo["hasPIPVisibleProc"], "w").write("1")
elif hasattr(InfoBar.instance.session, "pip"):
InfoBar.instance.session.pip.relocate()
global PipPigModeEnabled
PipPigModeEnabled = False
PipPigModeTimer.callback.append(timedStopPipPigMode)
def PipPigMode(value):
from Screens.InfoBar import InfoBar
if InfoBar.instance and InfoBar.instance.session and hasattr(InfoBar.instance.session, "pip") and config.av.pip_mode.value != "external":
if value:
PipPigModeTimer.stop()
global PipPigModeEnabled
if not PipPigModeEnabled:
if SystemInfo["hasPIPVisibleProc"]:
open(SystemInfo["hasPIPVisibleProc"], "w").write("0")
else:
import skin
x, y, w, h = skin.parameters.get("PipHidePosition", (16, 16, 16, 16))
pip = InfoBar.instance.session.pip
pip.move(x, y, doSave=False)
pip.resize(w, h, doSave=False)
PipPigModeEnabled = True
else:
PipPigModeTimer.start(100, True)
class PictureInPictureZapping(Screen):
skin = """<screen name="PictureInPictureZapping" flags="wfNoBorder" position="50,50" size="90,26" title="PiPZap" zPosition="-1">
<eLabel text="PiP-Zap" position="0,0" size="90,26" foregroundColor="#00ff66" font="Regular;26" />
</screen>"""
class PictureInPicture(Screen):
def __init__(self, session):
global pip_config_initialized
Screen.__init__(self, session)
self["video"] = VideoWindow()
self.pipActive = session.instantiateDialog(PictureInPictureZapping)
self.dishpipActive = session.instantiateDialog(Dishpip)
self.currentService = None
self.currentServiceReference = None
self.choicelist = [("standard", _("Standard"))]
if SystemInfo["VideoDestinationConfigurable"]:
self.choicelist.append(("cascade", _("Cascade PiP")))
self.choicelist.append(("split", _("Splitscreen")))
self.choicelist.append(("byside", _("Side by side")))
self.choicelist.append(("bigpig", _("Big PiP")))
if SystemInfo["HasExternalPIP"]:
self.choicelist.append(("external", _("External PiP")))
if not pip_config_initialized:
config.av.pip = ConfigPosition(default=[510, 28, 180, 135], args=(MAX_X, MAX_Y, MAX_X, MAX_Y))
config.av.pip_mode = ConfigSelection(default="standard", choices=self.choicelist)
pip_config_initialized = True
self.onLayoutFinish.append(self.LayoutFinished)
def __del__(self):
del self.pipservice
self.setExternalPiP(False)
self.setSizePosMainWindow()
if hasattr(self, "dishpipActive") and self.dishpipActive is not None:
self.dishpipActive.setHide()
def relocate(self):
x = config.av.pip.value[0]
y = config.av.pip.value[1]
w = config.av.pip.value[2]
h = config.av.pip.value[3]
self.move(x, y)
self.resize(w, h)
def LayoutFinished(self):
self.onLayoutFinish.remove(self.LayoutFinished)
self.relocate()
self.setExternalPiP(config.av.pip_mode.value == "external")
def move(self, x, y, doSave=True):
if doSave:
config.av.pip.value[0] = x
config.av.pip.value[1] = y
config.av.pip.save()
w = config.av.pip.value[2]
h = config.av.pip.value[3]
if config.av.pip_mode.value == "cascade":
x = MAX_X - w
y = 0
elif config.av.pip_mode.value == "split":
x = MAX_X / 2
y = 0
elif config.av.pip_mode.value == "byside":
x = MAX_X / 2
y = MAX_Y / 4
elif config.av.pip_mode.value in "bigpig external":
x = 0
y = 0
self.instance.move(ePoint(x, y))
def resize(self, w, h, doSave=True):
if doSave:
config.av.pip.value[2] = w
config.av.pip.value[3] = h
config.av.pip.save()
if config.av.pip_mode.value == "standard":
self.instance.resize(eSize(*(w, h)))
self["video"].instance.resize(eSize(*(w, h)))
self.setSizePosMainWindow()
elif config.av.pip_mode.value == "cascade":
self.instance.resize(eSize(*(w, h)))
self["video"].instance.resize(eSize(*(w, h)))
self.setSizePosMainWindow(0, h, MAX_X - w, MAX_Y - h)
elif config.av.pip_mode.value == "split":
self.instance.resize(eSize(*(MAX_X / 2, MAX_Y)))
self["video"].instance.resize(eSize(*(MAX_X / 2, MAX_Y)))
self.setSizePosMainWindow(0, 0, MAX_X / 2, MAX_Y)
elif config.av.pip_mode.value == "byside":
self.instance.resize(eSize(*(MAX_X / 2, MAX_Y / 2)))
self["video"].instance.resize(eSize(*(MAX_X / 2, MAX_Y / 2)))
self.setSizePosMainWindow(0, MAX_Y / 4, MAX_X / 2, MAX_Y / 2)
elif config.av.pip_mode.value in "bigpig external":
self.instance.resize(eSize(*(MAX_X, MAX_Y)))
self["video"].instance.resize(eSize(*(MAX_X, MAX_Y)))
self.setSizePosMainWindow()
def setSizePosMainWindow(self, x=0, y=0, w=0, h=0):
if SystemInfo["VideoDestinationConfigurable"]:
self["video"].instance.setFullScreenPosition(eRect(x, y, w, h))
def setExternalPiP(self, onoff):
if SystemInfo["HasExternalPIP"]:
open(SystemInfo["HasExternalPIP"], "w").write(onoff and "on" or "off")
def active(self):
self.pipActive.show()
def inactive(self):
self.pipActive.hide()
def getPosition(self):
return self.instance.position().x(), self.instance.position().y()
def getSize(self):
return self.instance.size().width(), self.instance.size().height()
def togglePiPMode(self):
self.setMode(config.av.pip_mode.choices[(config.av.pip_mode.index + 1) % len(config.av.pip_mode.choices)])
def setMode(self, mode):
config.av.pip_mode.value = mode
config.av.pip_mode.save()
self.setExternalPiP(config.av.pip_mode.value == "external")
self.relocate()
def getMode(self):
return config.av.pip_mode.value
def getModeName(self):
return self.choicelist[config.av.pip_mode.index][1]
def playService(self, service):
Notifications.RemovePopup("ZapPipError")
if service is None:
return False
ref = self.resolveAlternatePipService(service)
if ref:
if SystemInfo["CanNotDoSimultaneousTranscodeAndPIP"] and StreamServiceList:
self.pipservice = None
self.currentService = None
self.currentServiceReference = None
if not config.usage.hide_zap_errors.value:
Notifications.AddPopup(text="PiP...\n" + _("Connected transcoding, limit - no PiP!"), type=MessageBox.TYPE_ERROR, timeout=5, id="ZapPipError")
return False
if self.isPlayableForPipService(ref):
print "playing pip service", ref and ref.toString()
else:
if not config.usage.hide_zap_errors.value:
Notifications.AddPopup(text="PiP...\n" + _("No free tuner!"), type=MessageBox.TYPE_ERROR, timeout=5, id="ZapPipError")
return False
self.pipservice = eServiceCenter.getInstance().play(ref)
if self.pipservice and not self.pipservice.setTarget(1, True):
if hasattr(self, "dishpipActive") and self.dishpipActive is not None:
self.dishpipActive.startPiPService(ref)
self.pipservice.start()
self.currentService = service
self.currentServiceReference = ref
return True
else:
self.pipservice = None
self.currentService = None
self.currentServiceReference = None
if not config.usage.hide_zap_errors.value:
Notifications.AddPopup(text=_("Incorrect service type for Picture in Picture!"), type=MessageBox.TYPE_ERROR, timeout=5, id="ZapPipError")
return False
def getCurrentService(self):
return self.currentService
def getCurrentServiceReference(self):
return self.currentServiceReference
def isPlayableForPipService(self, service):
playingref = self.session.nav.getCurrentlyPlayingServiceReference()
if playingref is None or service == playingref:
return True
info = eServiceCenter.getInstance().info(service)
oldref = self.currentServiceReference or eServiceReference()
if info and info.isPlayable(service, oldref):
return True
return False
def resolveAlternatePipService(self, service):
if service and (service.flags & eServiceReference.isGroup):
oldref = self.currentServiceReference or eServiceReference()
return getBestPlayableServiceReference(service, oldref)
return service
|
glebysg/GC_server | refs/heads/master | vacs/migrations/0008_auto_20170710_0107.py | 1 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-10 01:07
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vacs', '0007_experiment_owner'),
]
operations = [
migrations.AlterField(
model_name='experiment',
name='replications',
field=models.TextField(blank=True),
),
]
|
MihaZelnik/Django-Unchained | refs/heads/master | src/project/manage.py | 1 | #!/usr/bin/env python
import os
import sys
def run():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
recognai/spaCy | refs/heads/master | spacy/lang/fa/lemmatizer/_nouns.py | 1 | # coding: utf8
from __future__ import unicode_literals
NOUNS = set("""
آ
آئیننامه
آب
آبادان
آبادانی
آبادی
آبانماه
آبدارخانه
آبرسانی
آبرنگ
آبرو
آبروی
آبزی
آبلمان
آبلمن
آبله
آبلیمو
آبیاری
آبانبار
آبخوری
آبشکن
آبفشان
آبمیوه
آبنبات
آبنباتی
آتالا
آتراو
آتش
آتشفشان
آتشبازی
آتشبیار
آتشسوزی
آتشنشانی
آتن
آتنی
آتیه
آثار
آثاری
آجر
آجرنوشته
آجیل
آجیپ
آحاد
آخ
آخرت
آخوند
آداب
آدانا
آدم
آدمی
آدمبزرگ
آدمخواری
آدمسوزی
آدوراشتری
آدولف
آذر
آذربایجان
آذرماه
آر
آرا
آرامش
آرامگاه
آرامگاهی
آرامسازی
آران
آرای
آرایش
آرایی
آرزو
آرزوی
آرش
آرشیو
آرمان
آرمسترانگ
آزاداندیش
آزادسازی
آزاده
آزادی
آزار
آزتک
آزردگی
آزمایش
آزمایشگاه
آزمایشی
آزگار
آسانی
آسایش
آستا
آستانه
آستانهٔ
آسم
آسمان
آسمانخراش
آسوشیتدپرس
آسپن
آسیا
آسیاب
آسیای
آسیب
آسیبی
آسیبدیدگی
آسیبپذیری
آشتیجویی
آشفتگی
آشنا
آشنای
آشنایی
آشناییزدایی
آشوب
آشوبی
آشور
آشپزخانه
آشپزخانهٔ
آشپزخونه
آشپزی
آشیرف
آغاز
آغازگر
آغازی
آغوش
آفت
آفتاب
آفتکش
آفریده
آفریده
آفریقا
آفریقای
آقا
آقابابایی
آقاخانی
آقازاده
آقای
آقتقای
آقچشمه
آلاباما
آلادیک
آلاینده
آلبرایت
آلبرت
آلترناتیو
آلترناتیوی
آلرژی
آلماتی
آلمان
آلمانی
آلودگی
آلومینیوم
آلیاژ
آماج
آمادگی
آمار
آمارگیری
آماری
آمد
آمدن
آمر
آمریکا
آمریکای
آمریکایی
آمفیزم
آمنه
آموخته
آموزش
آموزشگاه
آموزه
آموزگار
آن
آناماتیو
آنانی
آنتن
آنتپ
آنتیاکسیدان
آنتیبیوتیک
آندره
آنرا
آنزیمی
آنفلوانزا
آننبرگ
آنه
آنچه
آنژیوگرافی
آنکارا
آنیس
آنطرفتر
آهن
آهنگ
آهنگر
آهنگی
آهو
آهووشی
آهک
آوا
آواره
آوارگی
آواز
آوازی
آورد
آوردن
آوریل
آپا
آپادانا
آپادانای
آپارتمان
آپولو
آژانس
آژاکس
آژیر
آکادمی
آکروپلیس
آکسفورد
آکی
آکیاک
آگاه
آگاهی
آگهی
آی
آیت
آیتم
آیتی
آیتالله
آینده
آیندهٔ
آیندهای
آینه
آیه
آیوری
آیینه
آییننامه
آیبیای
آیوی
ا
ائتلاف
ائتلافی
ائمهٔ
اباظریف
ابایی
ابتدا
ابتدای
ابتلا
ابتکار
ابداع
ابر
ابرار
ابراز
ابراهیم
ابراهیمی
ابرحکومت
ابزار
ابزاری
ابطال
ابطحی
ابعاد
ابقا
ابلاغ
ابلیس
ابن
ابنسینا
ابهام
ابواأ
ابوالبشر
ابوالحسن
ابوالعلی
ابوالفضل
ابوالقاسم
ابوبکر
ابوت
ابوحنیف
ابوسفیان
ابوطالب
ابوقبیس
ابومحمد
ابومسلم
ابوچی
ابی
ابیطالب
اتاق
اتامبوتول
اتحاد
اتحادی
اتحادیه
اتخاذ
اتریش
اتصال
اتفاق
اتفاقی
اتل
اتلاف
اتم
اتمام
اتهام
اتوبان
اتود
اتومبیل
اتوکریتیک
اتوکشی
اتکا
اتکاء
اتکای
اتیل
اثاثکشی
اثبات
اثر
اثرگذار
اثرگذاری
اثری
اثیر
اجاره
اجازه
اجانب
اجتماع
اجتناب
اجداد
اجر
اجرا
اجرام
اجرای
اجزا
اجزاء
اجزای
اجساد
اجلاس
اجماع
اجویت
احادیث
احادیثی
احاله
احتراق
احترام
احتشامزاده
احتمال
احتیاج
احد
احداث
احرابیفر
احراز
احزاب
احساس
احساسی
احسان
احضار
احضاریهیی
احقاف
احقاق
احمد
احمدالحسن
احمدیان
احنف
احوال
احکام
احیاء
احیای
اخبار
اخباری
اخترشناس
اختصار
اختصاص
اختلاط
اختلاطی
اختلاف
اختلال
اختیار
اختیاری
اخذ
اخراج
اخلاف
اخلاق
اخوت
ادا
اداء
اداره
ادارهٔ
ادامه
ادامهٔ
ادامهدهنده
ادای
ادب
ادبا
ادبای
ادبایی
ادبیات
ادبدوستان
ادرار
ادراک
ادعا
ادعائی
ادعای
ادعایی
ادغام
ادوات
ادوار
ادوارد
ادویلر
ادگاردو
ادیان
ادیب
ادیبی
اذان
اذعان
اذهان
اذیت
ارائه
ارائهدهنده
ارادت
ارادتسالاری
اراده
ارادهٔ
اراده
ارادهای
اراسیموس
اراضی
اران
اراک
اراکی
ارایه
ارباب
ارتباط
ارتباطی
ارتش
ارتشبد
ارتفاع
ارتقا
ارتقاء
ارتقای
ارتکاب
ارجاع
ارجحیت
اردبیل
اردبیلی
اردستانی
اردهال
اردوگاه
اردیبهشت
ارز
ارزش
ارزشگرایی
ارزشزدایی
ارزشگرایی
ارزیابی
ارسال
ارشاد
ارضای
ارقام
ارقامی
ارلینگ
ارمغان
ارمنستان
اره
اره
ارومیه
اروپا
اروپای
ارکان
ارکستر
ارگ
ارگان
اریکه
ازاء
ازای
ازبکستان
ازدحام
ازدواج
ازدیاد
ازمنه
اس
اساتید
اسارت
اساس
اسامه
اسامی
اسب
اسباب
اسبویی
اسبی
اسبسواری
استاد
استادی
استاف
استان
استانبول
استاندار
استاندارد
استانداری
استبداد
استتار
استثمار
استثنا
استثنایی
استحاله
استحالهای
استحصال
استحضار
استحکام
استخدام
استخراج
استخوان
استدراک
استراتژی
استراتژیست
استراحت
استراسبورگ
استراق
استرالیا
استرداد
استشهاد
استطرادا
استعفا
استعفانامه
استعلام
استعمار
استعمال
استغفار
استفاده
استفادهٔ
استفراغ
استفسار
استقامت
استقامتی
استقبال
استقبالی
استقرار
استقلال
استل
استلحاق
استمرار
استناد
استنباط
استنفورد
استهلاک
استواری
استوانه
استکان
استکبار
استیفن
استیلایی
استیلی
اسحاق
اسد
اسدآباد
اسدالله
اسرائیل
اسرائیلی
اسرار
اسراف
اسراییل
اسری
اسفزاری
اسفند
اسفندیار
اسلاف
اسلام
اسلامگرا
اسلامی
اسلامآباد
اسلاید
اسلحه
اسلحهای
اسلم
اسلواک
اسم
اسماعیل
اسماعیلیان
اسمیت
اسناد
اسهال
اسوهٔ
اسپانیا
اسپانیائی
اسپانیایی
اسپری
اسپورتینگ
اسکات
اسکار
اسکان
اسکوربیت
اسکولاستی
اسیدپاشی
اسیر
اسیران
اش
اشاره
اشارهای
اشتباه
اشتباهی
اشتراک
اشتراکی
اشتغال
اشتیاق
اشخاص
اشرار
اشراری
اشراف
اشرافیگری
اشرفی
اشعار
اشعری
اشعه
اشک
اشکال
اشکالی
اشیا
اشیاء
اشیای
اشیایی
اصالت
اصحاب
اصحابِ
اصرار
اصطلاح
اصغر
اصفهان
اصفهانی
اصفیاء
اصل
اصلاح
اصلاحگرا
اصلاحگرایی
اصلاحخواهی
اصلاحطلب
اصلاحطلبی
اصناف
اصول
اضافه
اضطراب
اطاعت
اطاق
اطراف
اطرافیان
اطفال
اطلاع
اطلاعات
اطلاعاتی
اطلاعی
اطلاعیه
اطلاعیهٔ
اطلاعیهای
اطلاعرسانی
اطلاق
اطلس
اطمینان
اطمینانی
اظهار
اظهارنظر
اعتبار
اعتباری
اعتدال
اعتراض
اعتراضی
اعتراف
اعتصاب
اعتقاد
اعتقادی
اعتماد
اعتمادالدوله
اعتمادی
اعتنای
اعتنایی
اعتیاد
اعجاز
اعدام
اعراب
اعزام
اعضا
اعضاء
اعضای
اعطا
اعطاء
اعطای
اعظمی
اعلا
اعلام
اعلامیه
اعماق
اعمال
اعمالی
اغاز
اغتشاش
اغراض
اغراق
اغما
اغماء
اغماض
اف
افت
افتادن
افتادگی
افتتاح
افتخار
افترا
افتضاح
افراد
افرادی
افراسیابی
افراط
افراطیگری
افریقا
افزایش
افسارگسیختگی
افسانه
افسر
افسردگی
افسونزدایی
افشا
افشار
افشاگری
افشای
افضل
افطار
افطاری
افغانستان
افق
افکار
افکت
افبیای
اقامت
اقامتگاه
اقامه
اقبال
اقبالی
اقتدا
اقتدار
اقتصاد
اقتصادی
اقتضا
اقتضاأ
اقدام
اقدامی
اقرار
اقسام
اقشار
اقطاع
اقطاعی
اقلام
اقلیت
اقلیتی
اقلیدس
اقلیم
اقمار
اقناع
اقوال
اقوام
اقیانوس
اقیانوسیه
ال
الاالله
الاتحاد
الاحمد
الاهلی
البرادعی
التفات
التفاتی
التقاط
التهاب
التیام
الجابر
الجزیره
الحدید
الحسن
الحکمه
الحیات
الخیام
الرئیس
الریان
الزام
الزعبی
السلام
الصباح
الطاف
العبر
العجمی
العراقی
الف
القا
القادسیه
القای
الله
الماس
الماسی
المپیک
المیزان
النداوی
النصر
الهام
الهی
الهیات
الهیاری
الوحده
الوکره
الکتریک
الکل
الگو
الگوی
الگویی
الیاف
الیاف
الیجاه
الیگودرز
ام
امارات
امارت
امام
امامت
امامزاده
امامی
امان
امانت
امانتداری
امانتی
امانالله
اماکن
امت
امتحان
امتداد
امتناع
امتیاز
امتیازی
امتیازدهی
امتیازستانی
امثال
امدادیان
امر
امرا
امرار
امراض
امربهمعروف
امروز
امری
امریه
امریکا
امریکن
امضا
امضاء
امضاکننده
امضای
املاح
املاک
امنیت
امنیتی
امهات
امواج
اموال
اموالی
امور
امپراتوری
امپراطوری
امکان
امکانات
امکانی
امیال
امید
امیدرضا
امیدواری
امیر
امیرارسلان
امیرخانی
امیرزادهای
امیرهوشنگ
امیل
امینیان
امیه
امسلمه
امکلثوم
انار
انبار
انبوهی
انبوهکاری
انبیا
انتخاب
انتخابات
انتخاباتی
انتشار
انتظار
انتظاری
انتظامی
انتقاد
انتقادی
انتقال
انتقام
انتها
انجام
انجمن
انجمنی
انجیل
انحراف
انحرافی
انحصار
انحطاط
انحلال
انداختن
اندازه
اندازهٔ
اندازهگیری
اندام
اندرز
اندرو
اندوخته
اندونزی
اندوه
اندکی
اندی
اندیشمند
اندیشه
اندیشهٔ
اندیشهای
اندیمشک
انذار
انرژی
انزجاری
انزوا
انزوای
انس
انسان
انسانی
انسانیت
انستیتو
انستیتوی
انسجام
انسداد
انشا
انشان
انشای
انصار
انصاری
انصاف
انصافی
انصراف
انضباط
انطباق
انعام
انعطاف
انعطافپذیری
انعقاد
انعکاس
انعکاسی
انفجار
انفرادی
انفصال
انفصالی
انفعال
انقضای
انقلاب
انقلابی
انواع
انور
انوری
انکار
انگشت
انگلستان
انگلیس
انگلیسی
انگور
انگیزش
انگیزه
انیتگرا
انیماتور
اهالی
اهانت
اهانتی
اهتزاز
اهتمام
اهداف
اهدافی
اهدایی
اهر
اهرم
اهل
اهمیت
اهمیتی
اهواز
اهورامزدا
او
اواخر
اواسط
اوایل
اوبر
اوتراپرادش
اوتی
اوتلوک
اوج
اوحدی
اوراق
اورامانات
اورانوس
اورنگآبادی
اورژانس
اوزاکای
اوسترهاوس
اوستلینگ
اوصاف
اوضاع
اوغورمومجو
اول
اولاد
اولویت
اولِ
اولی
اولیا
اوماتورمن
اوهام
اوهایو
اوپک
اُبی
اِرد
اپرا
اپسالا
اکاذیب
اکبر
اکبرآبادی
اکبرشاه
اکبری
اکتبر
اکتفا
اکتوف
اکثر
اکثریت
اکثریتی
اکرام
اکرتاس
اکرم
اکریلت
اکو
اکوادور
اگریا
اگزوز
اگلیپای
ای
ایاز
ایالت
ایام
ایتالیا
ایتالیایی
ایثار
ایثارگر
ایجاب
ایجاد
ایجادکننده
ایدز
ایده
ایر
ایراد
ایرادی
ایران
ایراندوست
ایرانسرا
ایرانسرای
ایرانشهر
ایرانمنش
ایرانی
ایرانشناسی
ایرج
ایرسوتر
ایرفرانس
ایرلاینز
ایرنا
ایرویز
ایزد
ایزونیازید
ایست
ایستادن
ایستادگی
ایستایی
ایستگاه
ایسنا
ایشان
ایفا
ایفای
ایل
ایلام
ایلدوفرانس
ایمان
ایمانی
ایمانزاده
ایمن
ایمنسازی
این
اینترنت
اینجانب
ایندیپندنت
اینسبورگ
اینستبوک
اینشوشینک
اینهمه
اینو
اینکا
اینکار
اینگونه
ایوان
ایوب
ایوکان
ایکولا
ب
باب
بابا
باباشمل
بابت
بابل
بابلسر
باجه
باخت
باختن
باد
بادالینگ
باده
بادهٔ
بادهای
بادگیری
بادی
بادرود
بار
باران
بارانی
بارداری
بارش
باره
بارها
بارگاه
بارگر
باری
بازار
بازارچه
بازاری
بازبین
بازتاب
بازجویی
بازخوانی
بازداشت
بازدهی
بازدید
بازدیدکننده
بازرس
بازرسی
بازرگان
بازرگانی
بازسازی
بازشماری
بازشناسی
بازمانده
بازنشستگی
بازنمایی
بازنگری
بازپرس
بازگرداندن
بازگشت
بازگو
بازی
بازیکن
بازیگر
بازیگری
بازی
بازپرسی
باستانی
باستانشناس
باستانشناسی
باسکول
باشت
باشگاه
باطری
باطن
باعث
باغ
باغبان
باغبانی
باغچه
باغی
بافت
باقر
باقری
باقی
بال
بالش
بالشتک
بالغ
بالندگی
بام
بامداد
باند
بانو
بانوی
بانک
بانکوک
بانکی
بانگ
باهنر
باور
باورمندان
باورپذیری
باوری
باژ
باکتری
باکتریولوژی
بایرامپور
بایپس
باروی
بتا
بتی
بجنورد
بحث
بحثی
بحر
بحران
بحرانسازی
بخار
بخارا
بخارست
بخت
بختیاری
بختالنصر
بخش
بخشش
بخشنامه
بخشندهٔ
بخشی
بخشیدن
بد
بدان
بدبختی
بدبینی
بدخشان
بدخطی
بدر
بدرفتاری
بدرقه
بدعت
بدل
بدلسازی
بدلسازی
بدن
بدنهٔ
بده
بدهی
بدهی
بدو
بدگویی
بذر
بر
برآورد
برائت
برابر
برابری
برادر
برادرزادهٔ
برادرزن
برادرم
برادری
برازش
برانداز
براندازی
براندز
براندنبرگ
برانگیختن
برتری
برج
برخاست
برخورد
برخورداری
برخوردی
برخی
برد
برداشت
برداشتن
برداشتی
بردباری
بردباریِ
بردن
بردهفروش
بررسی
برزنی
برزیل
برزیلی
برش
برف
برق
برقراری
برقی
برقرسانی
برن
برنامه
برنامهٔ
برنامه
برنامهای
برنامهریزان
برنامهریزی
برنامهساز
برنامهسازی
برنج
برنده
برنز
بروجرد
بروز
برونشیت
بروکسل
برپایی
برچسب
برکت
برکناری
برکه
برگ
برگردانی
برگزاری
برگزارکننده
برگشت
برگشتن
برگهای
بری
بریتانیا
بریتیش
بریدن
بریزبن
بریستول
برینگ
برپاکننده
بز
بزرگ
بزرگتر
بزرگداشت
بزرگراه
بزرگسال
بزرگسالی
بزرگوار
بزرگی
بزرگتر
بزرگنمایی
بزهکاری
بساط
بساطی
بست
بستان
بستر
بستری
بستن
بستنی
بستنیفروشی
بسته
بستهبندی
بستگی
بسربنارطاث
بسط
بسکتبال
بسیاری
بسیج
بسیجی
بشر
بشری
بشریت
بصره
بصیرت
بصیرتی
بطن
بعث
بعدازظهر
بعدی
بعض
بعضی
بغداد
بغض
بغل
بقا
بقالی
بقای
بقایای
بقدری
بقیه
بقیهٔ
بقیه
بلاتکلیفی
بلایی
بلبل
بلخ
بلد
بلفاست
بلنت
بلندگو
بلندی
بلوار
بلور
بلوغ
بلومر
بلوچستان
بلوکباشی
بلژیک
بم
بمب
بمبگذاری
بن
بنا
بنادر
بنان
بناگوش
بنای
بنایی
بنت
بند
بندر
بندرعباس
بنده
بندهٔ
بنوت
بنگ
بنی
بنیاد
بنیادگرا
بنیان
بنیانگذار
بنیاعتماد
بنیامیه
بنیسعد
بنیضبه
بنیقریظه
بنیقینقاع
بنینظیر
بنیهاشم
بنبست
بنزیاد
بهار
بهارستان
بهاره
بهاری
بهانه
بهانهای
بهانهجویی
بهای
بهبود
بهبودسازی
بهبودی
بهترین
بهداری
بهداشت
بهره
بهرهای
بهرهبرداری
بهرهور
بهرهوری
بهرهگیری
بهزاد
بهزیستی
بهسازی
بهشت
بهشتی
بهمن
بهمنی
بهنام
بهینهسازی
بهبه
بهقدری
بهلیمو
بو
بواینگ
بواینزهرا
بوتان
بوته
بوداپست
بودجه
بودجویس
بودلر
بودن
بودن
بودنیام
بورس
بورلیهیلز
بورن
بورونوگرافی
بوستان
بوستانی
بوسنی
بوسه
بوشهر
بوغازایچی
بوق
بولوار
بومی
بوکس
بوکسور
بوی
بویراحمد
بُت
بُست
بُن
بِس
بِلاش
بچه
بچه
بچهای
بچگی
بکهام
بگلر
بی
بیااو
بیابان
بیان
بیانات
بیانگر
بیانی
بیانیه
بیانیهٔ
بیانیه
بیانیهای
بیانکننده
بیت
بیتی
بیتالمال
بیجار
بیجاپور
بیخ
بیداری
بیدل
بیدگل
بیراهه
بیرجند
بیرمنگام
بیرن
بیروت
بیزاری
بیست
بیعت
بیلهسوار
بیلی
بیم
بیمار
بیمارانی
بیمارستان
بیمارستانی
بیماری
بینم
بیننده
بیهار
بیهاری
بیهقی
بیهودگی
بیوه
بیچاره
بیژن
بیک
بیکاری
بیگ
بیگاری
بیگانه
بیگانهای
بیگانگی
بیگی
بیاحترامی
بیادبی
بیاطلاعی
بیاعتقادی
بیاعتمادی
بیاعتنائی
بیاعتنایی
بیایمانی
بیبندوباری
بیتابی
بیتحرکی
بیتفاوتی
بیتوجهی
بیثباتی
بیحرمتی
بیخبری
بیخیالی
بیدقتی
بیسواد
بیعدالتی
بیمیلی
بیهوشی
بیوزنی
بیپروایی
بیکار
بیکاری
ت
تأثیر
تأثیرپذیری
تأثیرگذاری
تأثیری
تأخیر
تأسف
تأسیس
تأسیسات
تأكید
تألیف
تأمل
تأملی
تأمینکنندهٔ
تأهل
تأکید
تأکیدی
تؤدیب
تؤسی
تئاتر
تئوری
تا
تااتر
تابستان
تابع
تابعیت
تابلو
تابلوی
تاتارستان
تاثیر
تاجر
تاجیک
تاجیکستان
تاجزاده
تار
تارَک
تاری
تاریخ
تاریخچه
تاریخشناس
تاریخنویس
تازه
تازهوارد
تازهواردشده
تازهکار
تازگی
تاسف
تاسوعا
تافت
تالار
تالش
تالک
تالی
تام
تان
تانک
تاهرت
تاهرتی
تاکهشیتا
تای
تایلند
تایمز
تایوان
تایپه
تایید
تب
تبادل
تباه
تباهی
تبت
تبدیل
تبراه
تبری
تبریز
تبریزی
تبریک
تبصره
تبع
تبعات
تبعه
تبعیت
تبعید
تبعیض
تبلیغ
تبلیغی
تبخال
تتبعات
تثبیت
تجار
تجارت
تجارتخانه
تجاوز
تجدید
تجدیدنظر
تجربه
تجربهٔ
تجربهای
تجسس
تجسم
تجلی
تجلیل
تجمع
تجمل
تجهیز
تجهیزات
تجویز
تحجر
تحدید
تحرک
تحریر
تحریف
تحریم
تحریک
تحصن
تحصنی
تحصیل
تحصیلات
تحصیلاتی
تحفه
تحقق
تحقیر
تحقیق
تحقیقی
تحلم
تحلیل
تحلیلگر
تحلیلی
تحلیلگر
تحمل
تحمیل
تحول
تحولی
تحویل
تحویلدار
تحکم
تحکیم
تخت
تخته
تختهسیاه
تختی
تخریب
تخصیص
تخطی
تخفیف
تخلص
تخلف
تخلفی
تخلیه
تخم
تخمدان
تخممرغ
تخیل
تدابیر
تدارک
تدارکات
تداعی
تداوم
تدبیر
تدبیری
تدریس
تذرو
تذهیبگران
تذکر
تذکره
تذکرهٔ
تذکرهای
تذکرهنویس
تذکرهنویسی
ترابری
ترابریای
تراز
ترازوی
تراش
ترانزیت
ترانساندانتال
ترانه
تراکتورسازی
تراکم
تربت
تربتی
تربتحیدریه
تربیت
تربیتبدنی
ترتیب
ترجمانی
ترجمه
ترجمهٔ
ترجیح
تردد
ترددکننده
تردید
تردیدی
ترز
ترس
ترسی
ترسیم
ترشح
ترفند
ترقه
ترقهسازی
ترقی
ترمیم
ترنتو
ترور
تروریست
تروریسم
ترویج
ترک
ترکمان
ترکمن
ترکمنستان
ترکی
ترکیب
ترکیبات
ترکیبی
ترکیه
تریاک
تریبون
تز
تزئین
تزریق
تساهل
تسبیح
تست
تسری
تسلط
تسلطی
تسلی
تسلیت
تسلیم
تسنن
تسهیلات
تشابه
تشبث
تشبه
تشبیه
تشخیص
تشدید
تشریح
تشریف
تشریفات
تشنج
تشنجزدایی
تشنه
تشنه
تشنگی
تشویش
تشویق
تشک
تشکر
تشکل
تشکچه
تشکیل
تشکیلات
تشکیک
تشیع
تصاحب
تصادف
تصاویر
تصاویری
تصحیح
تصدی
تصدیگری
تصرف
تصریح
تصفیه
تصلب
تصمیم
تصمیمی
تصمیمگیرنده
تصمیمگیری
تصور
تصوری
تصویب
تصویر
تصویربرداری
تصویرساز
تصویرسازی
تصویرگری
تصویری
تضاد
تضارب
تضرع
تضعیف
تضییع
تطبیق
تطمیع
تظاهر
تظاهرات
تظاهراتی
تعادل
تعارض
تعارضی
تعارف
تعاطف
تعالییی
تعامل
تعبیر
تعبیه
تعجب
تعداد
تعدادی
تعددگرایی
تعدیل
تعذیب
تعرفه
تعریف
تعریفی
تعزیه
تعطیلی
تعظیم
تعظیمی
تعقل
تعقیب
تعلق
تعلل
تعلیف
تعلیق
تعلیم
تعمیر
تعمیق
تعمیم
تعهد
تعهدی
تعویض
تعویق
تغذیه
تغلب
تغییر
تغییری
تفاخر
تفاسیر
تفاصیل
تفاله
تفاهم
تفاوت
تفاوتی
تفت
تفتیش
تفحص
تفرقه
تفریط
تفسیر
تفسیری
تفصیل
تفنگ
تفهیم
تفوق
تفکر
تقابل
تقاضا
تقاضای
تقاطع
تقبل
تقدیر
تقدیم
تقرب
تقسیم
تقسیمبندی
تقصیر
تقصیری
تقلب
تقلید
تقوای
تقویت
تقویم
تقویمی
تقی
تقیان
تلاش
تلاشی
تلافی
تلاقی
تلخیص
تلسکوپ
تلطیف
تلف
تلفات
تلفن
تلفیق
تلفیقی
تلقی
تلو
تلویزیون
تلگراف
تلآویو
تماس
تماسی
تماشا
تماشاگر
تماشای
تمام
تمامی
تمامیت
تمایل
تمبر
تمجید
تمدن
تمدنی
تمدید
تمرکز
تمرین
تمسک
تملقی
تمنا
تمهید
تمیزی
تن
تنافر
تناقض
تناوب
تنباکو
تنبیه
تندرو
تندروی
تندیس
تنزل
تنسی
تنسیق
تنش
تنشزدایی
تنظیم
تنه
تنهایی
تنهایی
تنوره
تنورهای
تنوع
تنگنا
تنگه
ته
تهاجم
تهدید
تهدیدی
تهذیب
تهران
تهمت
تهمینه
تهوع
تهیه
تهیهٔ
تهیهکننده
تهیهکنندهای
تو
توابع
توازن
توازی
تواضع
توافق
توافقنامهای
توافقنامه
توالی
توان
توانا
توانایی
توانایی
توانم
توبه
توجه
توجهی
توجیه
توده
تودهٔ
تودهای
تودی
تور
تورم
تورمن
تورنتو
توزیع
توزیعکننده
توس
توسعه
توسعهٔ
توسل
توسنی
توشهٔ
توصیف
توصیفی
توصیه
توصیه
توضیح
توضیحی
توطئه
توطئهای
توفیق
توقع
توقعی
توقف
توقیف
تولد
تولدی
تولستوی
تولی
تولید
تولیدات
تولیدکننده
توماس
تومان
تومور
تونس
تونل
توهم
توهمی
توپ
توکسمی
توکل
توکیو
تویسرکان
تویونن
تپش
تپه
تپهای
تکامل
تکان
تکثر
تکثرگرایی
تکثری
تکثیر
تکذیب
تکرار
تکلم
تکلیف
تکلیفی
تکمیل
تکنولوژی
تکنیک
تکه
تکهای
تکواندو
تکواندوکار
تکیه
تکتک
تکصدا
تگرگ
تگرگی
تگزاس
تی
تیتر
تیتراژ
تیر
تیرانداز
تیراندازی
تیراژ
تیرماه
تیره
تیرول
تیزهوشی
تیغ
تیغه
تیم
تیمور
تیمی
تیپ
تیاناف
تیانافآلفا
ثابتابنقره
ثالث
ثامن
ثانیه
ثبات
ثباتبخشی
ثبت
ثروت
ثروتمند
ثروتاندوزی
ثریا
ثعالبی
ثقفی
ثقل
ثقیلسازی
ثلث
ثمر
ثمره
ثواب
ثوابی
ثوربنمعن
ج
جا
جائی
جابجا
جابر
جابهجایی
جاده
جادو
جادوگر
جاذبه
جاذبهای
جار
جاسازی
جاسل
جاسوانت
جاسوس
جاسوسی
جام
جامدان
جامع
جامعه
جامعهٔ
جامعه
جامعهای
جامعهشناس
جامعهشناسی
جامعهیی
جامه
جامهٔ
جامی
جان
جانان
جانب
جانبدار
جانت
جاندار
جانور
جانِ
جانی
جاننثاری
جاهلیت
جاهلیتِ
جاوندبافی
جاکارتا
جای
جایزه
جایگاه
جایگاهی
جایی
جایجای
جبار
جبر
جبران
جبهه
جبههٔ
جحش
جد
جدار
جدال
جدایی
جدم
جدول
جدیت
جذابیت
جذب
جذبه
جرأت
جرائد
جرائم
جرات
جراتی
جراح
جراحت
جراحی
جرالد
جراید
جرایم
جرز
جرم
جرمی
جرگه
جریان
جریانی
جریانسازی
جریب
جریمه
جزء
جزئی
جزئیات
جزر
جزماندیشی
جزو
جزوه
جزیره
جزیرهٔ
جسارت
جسارتی
جست
جستجو
جستجوی
جسد
جشن
جشنواره
جشنوارهٔ
جعده
جعدهبنهبیره
جعفر
جعل
جغرافیایی
جفای
جفکوت
جلال
جلالی
جلالیزاده
جلب
جلد
جلسه
جلسهٔ
جلسهای
جلفا
جلو
جلودارزاده
جلوه
جلوهای
جلوگیری
جلوی
جلیل
جلیلی
جم
جماعت
جماعتی
جمال
جماهیر
جمجمه
جمشید
جمع
جمعه
جمعهٔ
جمعی
جمعیت
جمعآوری
جمعبندی
جمله
جملهٔ
جملهای
جمهور
جمهوری
جمهوریخواه
جمود
جمیل
جمیله
جناب
جنابعالی
جنابعالی
جناح
جناحِ
جناحی
جنازه
جناغ
جنایت
جنب
جنبش
جنبشی
جنبه
جنبهٔ
جنتی
جنتآباد
جنجال
جنجالآفرین
جنس
جنس
جنوب
جنوبی
جنگ
جنگل
جنگیدن
جنگآور
جهات
جهاد
جهالت
جهان
جهانبخش
جهانگرد
جهانگیر
جهانی
جهانیان
جهت
جهتدهی
جهتگیری
جهش
جهل
جهنم
جو
جوآیو
جواب
جوابگوی
جواد
جوار
جواز
جوامع
جوان
جوانانی
جوانترها
جوانمردی
جوانه
جوانی
جوایز
جوایزی
جودیری
جور
جوراب
جورج
جوری
جوسازی
جوش
جوشکاری
جولیانی
جولیو
جوی
جویبار
جوینده
جگر
جگرفروشی
جیب
جیغ
جیم
جیمز
حاتای
حاج
حاجت
حاجی
حادثه
حاسدان
حاشیه
حاصل
حاصلی
حاضر
حافظ
حافظا
حافظه
حافظهٔ
حافظیه
حال
حالت
حالتی
حالی
حالی
حامل
حامله
حاملگی
حامی
حاکم
حاکمان
حاکمی
حاکمیت
حاکمیتی
حبس
حبوبات
حبیب
حبیبی
حبیبالسیر
حج
حجاب
حجاریان
حجاز
حجازی
حجت
حجتی
حجتالاسلام
حجثالاسلام
حجر
حجربنعدی
حجم
حجهالحق
حجی
حد
حداد
حداقل
حداقلی
حدت
حدس
حدود
حدودی
حدی
حدیث
حذر
حذف
حراج
حراجی
حرارت
حراست
حرامزادگی
حرامزادگی
حربه
حرص
حرف
حرفم
حرفه
حرفی
حرفهای
حرمت
حرمتشکنی
حروف
حرکت
حرکتِ
حرکتی
حریر
حریری
حریف
حریفی
حریق
حریقی
حریم
حزب
حزبالله
حزبگرایی
حزن
حزنی
حس
حساب
حسادت
حساسیت
حساسیتی
حسب
حسرت
حسن
حسنویه
حسنک
حسنی
حسنظن
حسودان
حسی
حسینجانی
حسینی
حسینجان
حسینجانی
حشر
حشره
حشرهکش
حشیش
حصول
حصیر
حضرت
حضرتعالی
حضرمی
حضور
حضوری
حظ
حفاری
حفاظت
حفر
حفظ
حفظی
حق
حقارتی
حقانیت
حقایق
حقه
حقوق
حقوقدان
حقگویی
حقی
حقیقت
حقیقتی
حقخواه
حل
حلزون
حلفالفضول
حلقه
حلقهحلقهٔ
حلم
حله
حلیمهٔ
حماسه
حماسهٔ
حمام
حمایت
حمد
حمزه
حمل
حمله
حملهٔ
حموی
حمید
حمیدی
حوادث
حوادثی
حواس
حواله
حوالهٔ
حوالی
حوزه
حوزهٔ
حوش
حوصله
حوصله
حوض
حول
حومه
حک
حکام
حکایت
حکایتی
حکم
حکمت
حکمفرما
حکمی
حکمیت
حکومت
حکومتی
حکیم
حیا
حیات
حیاط
حیث
حیثیت
حیدریان
حیرت
حیطه
حیف
حیله
حیوان
خائن
خاتمه
خاتمهٔ
خاتمی
خادم
خارج
خارش
خاری
خازنی
خاستگاه
خاشاک
خاشاکی
خاص
خاصیت
خاطر
خاطرنشان
خاطره
خاطرهای
خاطری
خال
خالق
خامنهای
خامنهیی
خاماندیش
خان
خانان
خاندان
خانم
خانمی
خانه
خانهٔ
خانه
خانهای
خانهیی
خانواده
خانوادهٔ
خانواده
خانوادهای
خانوار
خاورمیانه
خاک
خاکستر
خاکی
خباره
خبر
خبرنگار
خبرنگاری
خبرچینان
خبرگزاری
خبری
ختم
خجالت
خدا
خداحافظ
خداحافظی
خداوند
خداوندی
خدای
خدشه
خدشهای
خدمت
خدمتکار
خدمه
خدیجه
خرابه
خرابی
خرابآباد
خرازی
خراسان
خراسانی
خرافاتی
خربس
خرج
خرد
خرداد
خردادماه
خردمند
خرده
خردهای
خردهسیارک
خردهسیارکی
خردهفرهنگ
خردهفروشی
خرزهره
خرس
خرم
خرما
خرمشهر
خرمن
خرمآباد
خروج
خروس
خروش
خروپف
خرید
خریدار
خریداری
خزان
خزانه
خزانهای
خزر
خزرآباد
خس
خسارت
خسارتی
خستگی
خسروجردی
خشت
خشم
خشونت
خشکسالی
خصال
خصایص
خصلت
خصوص
خصوصیسازی
خصومت
خط
خطا
خطاب
خطای
خطایایی
خطبا
خطبه
خطبهٔ
خطبهای
خطر
خطرِ
خطری
خطه
خطهٔ
خطوط
خطیب
خطیبی
خطمشی
خطکشی
خلاصه
خلاصهالاشعار
خلاصهای
خلاصهیی
خلاصی
خلاف
خلافت
خلاقیت
خلال
خلبان
خلخال
خلط
خلفا
خلق
خلقت
خلقالله
خلل
خلوت
خلوتگاه
خلیج
خلیجفارس
خلیفه
خلیل
خم
خمودی
خمیرمایه
خنجر
خنده
خنیاگر
خو
خواب
خواجه
خواربار
خوارج
خوارزمی
خواروبار
خواست
خواستار
خواسته
خواستهٔ
خواستگاری
خواص
خوان
خواندن
خواننده
خواهان
خواهر
خواهرزاده
خواهش
خواهشی
خواهنده
خوبی
خود
خودآگاهی
خودت
خودتو
خودداری
خودرو
خودروی
خودسانسوری
خودم
خودمو
خودکشی
خودکفایی
خودی
خودمشتمالی
خور
خوراکی
خورد
خوردن
خورده
خورشید
خورومی
خوزستان
خوشبین
خوشحالی
خوشرفتاری
خوشنویس
خوشنویسی
خوشی
خوشآمد
خوشآمدگویی
خوشخاطرگی
خوشچهره
خون
خونرسانی
خونریزی
خونسردی
خوک
خوی
خویش
خویشاوند
خویشاوندی
خویشتن
خیابان
خیال
خیام
خیامی
خیامینامه
خیانت
خیانتکار
خیبر
خیر
خیرخواه
خیرهسری
خیز
خیل
خیلی
خیمه
خیمهٔ
د
داخل
داد
داداش
دادرسی
دادستان
دادستانی
دادن
دادوستد
دادگاه
دادگستری
دار
دارالعباده
داران
دارایی
دارنده
دارو
داروخانه
داروسازی
داروی
دارویی
داریوش
داستان
داستانی
داستانپردازی
داستایوفسکی
داسی
داش
داشتن
داعیهٔ
داغ
داغولبازی
دال
دالکی
دام
داماد
دامان
دامداری
دامن
دامنه
دامپزشکی
دان
دانستن
دانستنی
دانش
دانشجوی
دانشمند
دانشنامه
دانشور
دانشکده
دانشگاه
دانشگاهیان
دانشآموخته
دانشآموز
دانشپژوه
دانشپژوهشی
دانمارک
دانه
دانیل
داود
داور
داوران
داوری
داوطلب
داوودی
دایرهٔ
دبستان
دبیر
دبیرخانه
دبیرستان
دبیرکل
دبیرکلی
دخالت
دخانیات
دختر
دختربچه
دختربچهای
دخترک
دخترکی
دختری
در
درآمد
دراج
درازا
درازمدت
درازگوش
درازگیسو
درامای
دراگا
درایت
درب
دربار
درج
درجه
درجهٔ
درخت
درختی
درخشش
درخشنده
درخشندگی
درخشیدن
درخواست
درد
دردسر
درس
درستکرداری
درستی
درسدن
درصد
درصدی
درم
درماتیت
درمان
درمانی
درمی
درندهای
دره
درهم
دروازه
دروازهٔ
دروازهبان
درود
دروس
دروغ
دروغگو
درون
درویشی
درک
درگاه
درگاهت
درگذشت
درگیری
دریا
دریافت
دریافتکننده
دریای
دریایی
دریچه
دربرگیرنده
دزد
دزدان
دزدی
دست
دستآورد
دستان
دستاورد
دستاویز
دستاویزی
دستبرد
دسترس
دسترسی
دستشویی
دستمایه
دستمزد
دسته
دستهبندی
دستهیی
دستور
دستورالعمل
دستوری
دستوک
دستکاری
دستگاه
دستگاهی
دستگیری
دستی
دستیابی
دستیار
دستیاری
دستاندرکار
دستدرازی
دشت
دشتی
دشمن
دشمنانِ
دشمنی
دشمنشناسی
دشنام
دعا
دعائی
دعای
دعایی
دعوا
دعوت
دعوتی
دغدغه
دغدغهای
دفاتر
دفاع
دفتر
دفع
دفعه
دفعالوقت
دفن
دقاقی
دقایقی
دقت
دقیقه
دل
دلار
دلارفروش
دلال
دلالت
دلالی
دلاور
دلایل
دلایلی
دلبستگی
دلتا
دلتنگی
دلخواه
دلسوزانی
دلسوزی
دلشدهٔ
دلفان
دلمو
دلگشائی
دلگشایی
دلی
دلیل
دلیلی
دم
دماوند
دمای
دمب
دمشق
دموکرات
دموکراسی
دمکرات
دمکراسی
دمی
دمیدن
دمیدنی
دنبال
دنباله
دنباله
دنبالهرو
دنبالهسازی
دندان
دندانپزشک
دندانپزشکی
دندانپزشک
دنیا
دنیای
دنیایی
دنیزلی
دنیس
ده
دهاتی
دهان
دهانه
دهانی
دهدشت
دهل
دهلی
دهلینو
دهن
دهنه
دهه
دههٔ
دهکده
دهکدهٔ
دهکدهای
دهی
دهتومانی
دو
دوازده
دوام
دوبله
دوحه
دوحهٔ
دود
دودکش
دور
دوران
دوراندیشی
دوراهی
دوربین
دورنمای
دوره
دورهٔ
دورهای
دوروئی
دوروبری
دورود
دوری
دوز
دوست
دوستدار
دوستی
دوسنگی
دوش
دوشنبه
دوغ
دولت
دولتمرد
دولتی
دولتآباد
دولتمحمد
دومینیکن
دومخردادی
دونده
دوندهای
دوندگی
دونوآی
دوهزار
دوپاردیو
دوچرخهسوار
دوچرخهسواری
دوک
دوگلاس
دویدن
دویست
دویچلند
دوگنبدان
دژ
دکارت
دکان
دکتر
دکترا
دکترای
دکتری
دکن
دکور
دگرگونی
دگمه
دی
دیابت
دیار
دیالوگ
دیانت
دیباچهٔ
دیتر
دید
دیدار
دیداری
دیدارکننده
دیدن
دیده
دیدهٔ
دیدگانی
دیدگاه
دیدگاهی
دیرباز
دیرمر
دیروز
دیسک
دیسکو
دینار
دیندار
دینداری
دین
دینخواهی
دینداری
دینستیز
دیه
دیهی
دیو
دیوار
دیواره
دیوان
دیولافوا
دیوی
دیوید
دیکتاتور
دیگر
دیگری
دیانای
ذخار
ذخایر
ذخیره
ذراع
ذرت
ذره
ذرهای
ذغال
ذلتپذیری
ذهن
ذهنی
ذهنیت
ذهنیتی
ذوب
ذوبآهن
ذوق
ذکر
ذکری
ذیل
ر
رأس
رأى
رأىدهنده
رأیای
رؤفت
رئوس
رئیس
رئیسه
رئیسالوزراأ
رئیسجمهور
رئیسجمهوری
رئیس
را
رابرت
رابطه
راجستان
راحتی
رادیو
رادیوی
رادیکال
رادیکالیسم
راز
رازقندی
راس
راستا
راستای
راستایی
راستی
راستگرا
راشد
راشدی
راغ
راغب
رامشگر
راندن
رانندگی
راه
راهب
راهبرد
راهرو
راهسازی
راهنمائی
راهنمای
راهنمایی
راهپیمایی
راهکار
راهکاری
راهگشا
راهگشایی
راهی
راهیابی
راهآهن
راهاندازی
راهحل
راهحلی
راهپیمایی
راهیابی
راوس
راولپندی
راویندرا
رای
رایانه
رایانی
رایزنی
رایس
رایسهای
رایسجمهوری
رایدهنده
رایگیری
رباط
رباعی
ربط
ربطی
ربع
ربنا
رتبه
رج
رجال
رجب
رجحان
رجوع
رحمت
رحیم
رحیمی
رخ
رخت
رختخواب
رخسار
رخشان
رخصت
رخوت
رخوتی
رد
رده
ردهبندی
ردیابی
ردیف
رزان
رزمنده
رسالت
رساله
رسالهٔ
رساندن
رسانه
رسانهای
رستم
رستمی
رستوران
رسم
رسمیت
رسوائی
رسوایی
رسوب
رسول
رسولاله
رسولزاده
رسوم
رسید
رسیدن
رسیدگی
رشت
رشته
رشتهٔ
رشتی
رشد
رشدی
رشوه
رشک
رشید
رصد
رصدخانه
رصدخانهٔ
رضا
رضاپور
رضای
رضایت
رضایتمندی
رضایی
رضاشاه
رطوبت
رعایت
رعب
رعد
رعنا
رعیت
رغبت
رفاه
رفت
رفتار
رفتاری
رفتن
رفرم
رفسنجانی
رفع
رفقا
رفیع
رفیق
رقابت
رقبای
رقم
رقمی
رقیب
رم
رمان
رمانتیسیزم
رمز
رمضان
رمضانی
رمیحی
رنج
رنجل
رنجی
رندی
رنگ
رنگینگچ
ره
رهاورد
رهبر
رهبری
رهنمایی
رهنمود
رهگشای
رو
روابط
رواج
رواق
روال
روان
روانشاد
روانشناس
روانشناسی
روانسازی
روانشناسی
رواک
روایت
روایتی
روبات
روبرو
روبنا
روتردام
روح
روحانی
روحانیت
روحی
روحیات
روحیه
روحافزایی
رود
رودبار
رودخانه
رودربایستی
رودلف
روده
رودکی
رور
روز
روزبه
روزمرگی
روزنامه
روزنامهٔ
روزنامه
روزنامهای
روزنامهنگار
روزه
روزه
روزهدار
روزهمو
روزگار
روزی
روس
روسای
روستا
روستای
روستایی
روسری
روسری
روسیاهی
روسیه
روش
روشنایی
روشنفکر
روشنفکرنما
روشنفکری
روشنگری
روشنی
روشی
روضثالشهدای
روضثالصفا
روغن
روغنی
روم
روماتیسم
رومانی
رومانو
رومه
رومو
رومیان
رومیزی
رونالدو
روند
روندگی
روندی
رونسار
رونق
روپیه
روی
رویا
رویابافی
رویارویی
رویای
رویت
رویتر
رویداد
رویش
رویه
رویکرد
رویکردی
رژیم
رژیمی
رکعت
رکن
رکود
رکورد
رگ
رگبار
رگه
ریا
ریاست
ریاستجمهوری
ریاضی
ریاضیات
ریاضیدانی
ریاضیدان
ریال
ریالی
ریتم
ریدکر
ریزش
ریزی
ریسندگی
ریسک
ریش
ریشتر
ریشه
ریشهیابی
رینو
رینگ
ریه
ریگ
ریگان
رییس
رییسجمهور
رییسجمهوری
زائر
زابل
زابورو
زادروز
زاده
زادگاه
زانو
زانوی
زاهدان
زاویه
زاگرس
زایمان
زباله
زبالهای
زبان
زبانزد
زبانآوری
زباندان
زبرو
زبونمو
زبیربنعبدالمطلب
زحمت
زحمتی
زخم
زخمی
زدن
زر
زراعت
زراعی
زراقی
زردآلو
زردی
زرنگی
زرنگبازی
زرورق
زرگری
زشتکاران
زشتی
زعفران
زعم
زل
زلزله
زلزلهای
زلف
زمام
زمامدار
زمان
زمانه
زمانی
زمانشناس
زمره
زمرهٔ
زمزمه
زمستان
زمینه
زمینهٔ
زمینهای
زمینهساز
زمینهسازی
زمینهیابی
زمینداری
زمینشناسی
زمینلرزه
زمینلرزهای
زن
زنانی
زناکار
زنبارگی
زنجان
زنجانی
زنجبار
زند
زندان
زندانی
زندهسازی
زندهیاد
زندگانی
زندگانی
زندگی
زندگینامهنویس
زندگی
زندیه
زنگ
زنی
زهد
زهر
زهره
زهرهوند
زهوار
زهیر
زوارهای
زوال
زوایای
زوجی
زودی
زور
زورآزمایی
زکات
زکی
زیاد
زیادهروی
زیادبنابیه
زیادبنربیه
زیارت
زیارتگاه
زیارتی
زیان
زیبای
زیبایی
زید
زیدی
زیر
زیرانداز
زیربنا
زیربنای
زیرساخت
زیرکی
زیرگذر
زیست
زیستن
زیستگاه
زیمنس
زینب
س
سؤال
سؤالاتی
سؤالی
سؤالانگیزی
سئول
سابقه
سابقه
ساتن
ساتیلایت
ساحت
ساحل
ساخت
ساختار
ساختمان
ساختمانی
ساختن
ساختهٔ
سادگی
سارا
سارق
ساروج
ساروق
ساری
ساز
سازش
سازمان
سازماندهی
سازمانی
سازماندهنده
سازنده
سازندگی
سازوکار
ساسانی
ساسانیان
ساعت
ساعتی
ساغری
ساق
ساقه
ساقی
سال
سالت
سالروز
سالمند
سالمندان
سالمونلا
سالمسازی
سالن
ساله
سالوسی
سالگرد
سالگواروسی
سالی
سامان
سانتیمتر
سانتیگراد
سانتیمتر
سانسور
سانگسونگ
سانتوش
سانلوییس
سانپااولو
ساوایانو
ساوت
ساوجی
ساوه
ساکن
سایر
ساینس
ساینسمانیتور
سایه
سایپا
سب
سبب
سبحانی
سبزعلی
سبزه
سبزهزار
سبزوار
سبزواری
سبزی
سبک
سبکی
سبیل
سبیل
ست
ستاد
ستاره
ستارهای
ستارهشناس
ستارهشناسان
ستارهشناسی
ستاری
ستایش
ستم
ستمدیده
ستمگر
ستمگری
ستون
سجادی
سجادنواز
سحر
سحری
سختی
سخن
سخندانی
سخنران
سخنرانی
سخنگو
سخنگوی
سخنگویی
سخنی
سخندانی
سد
سده
سر
سراج
سراسر
سراسیمه
سرامیک
سران
سرانجامی
سرانه
سرای
سرایت
سرب
سربار
سرباز
سربازان
سربازخانه
سربلندی
سربند
سربینه
سرتاسر
سرتراشی
سرحدیزاده
سرخرگ
سرخس
سرد
سرداب
سردار
سرداران
سردر
سردرد
سردرگمی
سردمدار
سردوشی
سردی
سررشته
سرزمین
سرسبزی
سرشان
سرشت
سرطان
سرطانشناسی
سرعت
سرقت
سرلوحه
سرما
سرماخوردگی
سرمای
سرمایه
سرمایهٔ
سرمایهدار
سرمایهداری
سرمایهسالاری
سرمایهگذار
سرمایهگذاری
سرمربی
سرمشق
سرمقاله
سرمه
سرمهدان
سرمسازی
سرنوشت
سرنگ
سرنیزه
سرهنگ
سرو
سروته
سرود
سرودن
سرودی
سرور
سروروی
سروسامان
سروش
سروصورت
سروکار
سرویس
سرپرست
سرپرستی
سرپیچی
سرچشمه
سرچشمه
سرکرده
سرکوب
سرکوبی
سرگذشت
سرگردانی
سرگرز
سرگرمی
سرگیجه
سری
سریال
سریالی
سریالسازی
سرمقالهٔ
سطح
سطحی
سطوح
سطور
سعادت
سعادتآباد
سعایت
سعد
سعدآباد
سعدی
سعدیه
سعه
سعودی
سعی
سعید
سعیدا
سعیدای
سعیدبنعاص
سعیدی
سعیدبنعاص
سفارت
سفارتخانه
سفارش
سفال
سفالگری
سفالینه
سفر
سفرا
سفرای
سفره
سفری
سفندارمذ
سفیر
سفینه
سقط
سقف
سقم
سقوط
سل
سلاح
سلاحی
سلام
سلامت
سلامتی
سلب
سلجوقی
سلستیس
سلسله
سلسلهٔ
سلسلهجبال
سلطان
سلطانپور
سلطنت
سلطنتی
سلطه
سلمان
سلمانی
سلمی
سلول
سلوک
سلک
سلیقه
سلیمانبنصرد
سم
سماور
سمبل
سمبلی
سمت
سمرقند
سمرقندی
سمسار
سمع
سمعک
سمفونیک
سمنان
سموم
سمیرا
سمیرامیس
سمینار
سمیه
سن
سنا
سناتور
سناریو
سناریوی
سناریویی
سنای
سنایی
سنبل
سنت
سنتزی
سنتی
سنجش
سنخی
سندی
سنندج
سنگ
سنگاپور
سنگر
سنگنگاره
سنی
سندیهگو
سه
سهام
سهروردی
سهم
سهمی
سهمیه
سهو
سهولت
سهیلا
سهیلی
سهساله
سهشنبه
سهماهه
سو
سوءاستفاده
سوءتفاهم
سوءقصد
سوءتغذیه
سوأ
سوأاستفاده
سوأتغذیه
سوأظنی
سوئد
سوئیس
سواحل
سواد
سوار
سوال
سوایس
سوبارو
سوبسید
سوخت
سوختن
سوختگی
سود
سودان
سودی
سوراخ
سوربن
سوره
سوریه
سوزاندن
سوزن
سوزندوزی
سوزوگداز
سوسک
سوسیالیست
سوسیالیسم
سوق
سولاوسی
سولقان
سوماویا
سونیا
سونیان
سوپردولوکس
سوژه
سوژهای
سوگند
سوی
سویس
سویی
سپاس
سپاسی
سپاه
سپاهان
سپتامبر
سپر
سپرده
سپردهگذار
سپری
سپنتا
سپنجی
سپیده
سپیدهدم
سکان
سکاندار
سکانس
سکانسی
سکته
سکتهٔ
سکنه
سکه
سکوت
سکولار
سکولاریزم
سکولاریسم
سکونت
سگ
سی
سیا
سیاحت
سیاره
سیارهای
سیاست
سیاستمدار
سیاستگذاری
سیاستی
سیاستگذار
سیانی
سیاهه
سیاهپوست
سیاهی
سیاهسرفه
سیاهچاله
سیاوش
سیب
سید
سیدالشهداأ
سیدنی
سیر
سیرهٔ
سیری
سیستان
سیستم
سیسم
سیسیل
سیصد
سیطره
سیفالله
سیل
سیلاب
سیلک
سیلی
سیما
سیمان
سیمای
سیمرغ
سیمپسن
سینائی
سینایی
سینس
سینما
سینمادوست
سینماگران
سینمای
سینه
سینوی
سینگ
سیوستانی
سیوطی
سیگار
سیگاری
سیام
سیانان
سیبیاس
ش
شئون
شاخ
شاخص
شاخصهٔ
شاخصی
شاخه
شاخهای
شاخی
شادابی
شادی
شازند
شاعر
شاعره
شاعری
شاغلام
شافعی
شالوده
شام
شامپانزه
شامگاه
شان
شانزده
شانس
شانه
شاه
شاهد
شاهرخ
شاهرود
شاهرودی
شاهزاده
شاهنامه
شاهنواز
شاهکار
شاهی
شاهمنصوری
شاپور
شاکی
شاکیان
شاگرد
شاگردی
شایستگی
شایعه
شایعهای
شایعهساز
شایعهپراکنی
شب
شباب
شباز
شبانی
شباهت
شباهتی
شبستان
شبنم
شبنمی
شبه
شبههای
شبهقارهٔ
شبکه
شبکهٔ
شبکهای
شبی
شببهخیر
شبنامه
شتاب
شتابزدگی
شتر
شتم
شجاعت
شجاعی
شجریان
شخص
شخصی
شخصیت
شخصیتی
شخصیتپردازی
شدت
شدن
شدگان
شراب
شرابی
شرابخوارگی
شرارت
شرافت
شرایط
شرایطی
شربت
شرح
شرحمااشکل
شرط
شرطی
شرف
شرفخانه
شرق
شرم
شروان
شروع
شرکای
شرکایی
شرکت
شرکتی
شرکتکننده
شریان
شریعتی
شریف
شریفینسب
شریک
شش
ششصد
شصت
شطرنج
شعائر
شعار
شعارگرایی
شعاری
شعب
شعبان
شعبدهبازی
شعبه
شعر
شعرا
شعرای
شعرایی
شعری
شعله
شعور
شغل
شغلی
شفافیت
شفیع
شفیعی
شفیق
شقایق
شلتاق
شلغم
شلمچه
شلوار
شلواری
شلیک
شما
شمار
شمارش
شماره
شمارهٔ
شمارهای
شماری
شمال
شمایل
شمد
شمردن
شمسی
شمشیر
شمشیرباز
شمشیربازان
شمشیربازی
شمشیرزن
شمع
شمعدانی
شمیرانات
شنا
شناخت
شناختن
شناساندن
شناسایی
شناور
شنبه
شنوایی
شنیدن
شنیده
شنیه
شنزار
شنیانگ
شهادت
شهامت
شهدای
شهر
شهرام
شهران
شهرت
شهردار
شهرداری
شهرستان
شهره
شهروند
شهروندان
شهرک
شهرکرد
شهری
شهریور
شهریزاده
شهوت
شهید
شهیدی
شو
شواهد
شوخی
شور
شورا
شورانگیز
شورای
شورایعالی
شورش
شوروی
شوسل
شوش
شوق
شولتز
شوهر
شوهری
شوک
شوکتی
شک
شکات
شکار
شکاف
شکافی
شکایت
شکایتی
شکر
شکست
شکستن
شکسته
شکفتگی
شکل
شکلات
شکلی
شکلبخشی
شکلگیری
شکم
شکن
شکنجه
شکوفائی
شکوفایی
شکوفه
شکوفهٔ
شکوه
شکوهیی
شکی
شگرد
شگفتی
شیخ
شیخنشین
شیر
شیراز
شیرازی
شیربها
شیردهی
شیرزن
شیری
شیرینی
شیرینزبانی
شیشاپانگما
شیشه
شیشهٔ
شیطان
شیطان
شیطنت
شیعه
شیفته
شیمیدرمانی
شینهوا
شیوع
شیوه
شیوهٔ
شیوهای
شیکاگو
ص
صابر
صاحب
صاحبنظر
صاحبمرده
صاحبنظر
صادرات
صادرکننده
صادق
صادقی
صادقیه
صافی
صالح
صالحی
صانع
صایب
صبا
صبح
صبحونه
صبحگاه
صبر
صبیحه
صحبت
صحت
صحرا
صحن
صحنه
صحنهٔ
صحنه
صحنهای
صخره
صد
صدا
صداقت
صداوسیما
صدای
صدایی
صدد
صددرصدی
صدر
صدرا
صدراعظم
صدق
صدقی
صدم
صدمه
صدمهای
صدور
صدیق
صدیقی
صراحت
صرف
صرفنظر
صرفه
صرفهجویی
صعود
صف
صفا
صفائیه
صفاییه
صفت
صفحه
صفحهٔ
صفر
صفوف
صفوی
صفویه
صفیری
صفیالله
صفبندی
صلابت
صلاح
صلاحدید
صلح
صنایع
صندلی
صندوق
صندوقچه
صندوقی
صنع
صنعا
صنعت
صنعتی
صنعتنفت
صنوفی
صنیع
صهیونیست
صهیونیسم
صور
صورت
صورتجلسه
صورتی
صوفی
صوفیه
صیانت
صیغه
صیلم
ضابطه
ضامن
ضایعات
ضبط
ضحاک
ضخامت
ضد
ضدارزش
ضدانقلابیگری
ضدتبخال
ضدویروس
ضدیت
ضدانقلاب
ضرایب
ضرب
ضربان
ضربه
ضربهای
ضربالمثل
ضرر
ضرورت
ضرورتی
ضریب
ضعف
ضعفا
ضلع
ضمانت
ضمیر
ضوابط
ضیاع
ضیافت
طابران
طاسی
طاغوت
طاق
طاقت
طاقچه
طاقنمایی
طالب
طالبان
طالبی
طاهر
طاهره
طاهریان
طاووس
طایفه
طب
طباطبایی
طبران
طبری
طبسی
طبع
طبقه
طبقهبندی
طبل
طبیب
طبیعت
طراح
طراحی
طراز
طراوت
طرح
طرحی
طرد
طرز
طرف
طرفدار
طرفداری
طرفی
طرق
طریق
طریقه
طریقی
طعم
طعن
طعنه
طغیان
طفره
طفله
طلا
طلاب
طلافروشی
طلاق
طلای
طلایه
طلب
طلبه
طلبگی
طلسم
طمانینه
طناب
طنز
طهران
طهرانی
طهماسب
طهماسبی
طواغیت
طور
طوری
طوس
طوسی
طول
طولموج
طی
طیف
ظاهر
ظاهرِ
ظرافت
ظرف
ظرفی
ظرفیت
ظروف
ظلم
ظلمات
ظن
ظهر
ظهور
ظهوری
ع
عابر
عاجزی
عادت
عادل
عارضه
عارضهای
عارف
عاشق
عاشورا
عاصبنواال
عالم
عالمی
عام
عامری
عامل
عامه
عامی
عایشه
عبادالله
عبادت
عبادتی
عبارت
عبارتی
عباس
عباسپور
عباسی
عباسیفرد
عباسعلی
عبدالباقی
عبدالحی
عبدالرحمان
عبدالرحمن
عبدالرحمنبنعثمان
عبدالله
عبداللهی
عبداللهبناُبی
عبداللهبنجعفر
عبداللهبنزبیر
عبداللهبنسلام
عبداللهبنعامر
عبداللهبنعباس
عبداللهبنعصام
عبداللهبنعمر
عبداللهبنمسعود
عبدالمطلب
عبدالواحد
عبور
عبید
عبیداللهبنعباس
عتبات
عتبی
عتیق
عثمان
عثمانی
عثمانیه
عج
عجایب
عجله
عجلهای
عجلاللهتعالیفرجهالشریف
عدالت
عدالتی
عدد
عددی
عدس
عدل
عدلیه
عدم
عدن
عدنان
عده
عدهای
عدهیی
عدی
عدیبنحاتم
عذاب
عذرخواهی
عراق
عرایض
عرب
عربستان
عربستانِ
عربشاهی
عربی
عرش
عرشه
عرصه
عرصهٔ
عرض
عرضه
عرف
عرفات
عرفان
عرق
عروج
عروس
عروسی
عروضی
عروق
عزت
عزتالله
عزل
عزلت
عزیز
عسل
عسلی
عسکری
عسگر
عسگری
عشایر
عشرت
عشرتطلبی
عشرتطلبی
عشق
عشقِ
عشقی
عشقآباد
عصا
عصبانیت
عصر
عضله
عضو
عضوی
عضویت
عطاأالله
عطاأالله
عطاالله
عطار
عطارد
عطر
عطردان
عطری
عطریانفر
عطش
عطف
عطفی
عظمت
عظیمآبادی
عفت
عفو
عفونت
عقاید
عقب
عقبماندگی
عقبگرد
عقد
عقدهٔ
عقرب
عقل
عقلای
عقود
عقیده
عقیدهٔ
عقیدهیی
عقیق
عقیلی
علائم
علائمی
علاالی
علاج
علاقمند
علاقمندی
علاقه
علاقهٔ
علاقه
علاقهای
علاقهمند
علامت
علامتی
علامه
علامی
علاوه
علایم
علایمی
علت
علتیابی
علف
علل
عللی
علم
علما
علمای
علمی
علوفه
علوم
علوی
علی
علیرضا
علیصدر
علیه
علیهمالسلام
علیهالسلام
علیابنابیطالب
علیاکبر
عمار
عماره
عمامه
عمان
عمر
عمرو
عمروبنحق
عمروبنعاص
عمروبنحمق
عمری
عمق
عمل
عملهٔ
عملکرد
عملی
عملیات
عموم
عمومیت
عموی
عناصر
عناصری
عنایت
عنایتالله
عنبر
عندلیب
عنصر
عنوان
عنوانی
عنکبوت
عهد
عهدشکنی
عهدنامهای
عهده
عهدهٔ
عوارض
عوارضی
عواطف
عواقب
عوالم
عوام
عوامل
عواملی
عوایق
عوض
عِرض
عکاس
عکاسان
عکاسی
عکس
عکسبرداری
عکسی
عیار
عیاش
عیب
عید
عیسی
عیش
عینک
غائله
غار
غارت
غارتگری
غاری
غالب
غباری
غدد
غده
غذا
غذاخوری
غذای
غذایی
غذقدونه
غر
غرامتی
غرب
غربی
غرس
غرش
غرض
غرضی
غرضورزی
غرقه
غروبی
غریب
غریبه
غریو
غزالی
غزل
غزیر
غضب
غضروف
غضنفر
غفران
غفلت
غفوری
غلامان
غلامرضا
غلامعلی
غلامزاده
غلبه
غلت
غلتیدن
غلط
غلطی
غلطگیری
غلظت
غله
غم
غنا
غنائم
غنای
غنیمت
غیاب
غیرخودی
غیرخودیاند
غیردولتی
غیرسیگاری
غیره
غیلان
فائزه
فاتح
فاجعه
فارابی
فارس
فارسی
فارغالتحصیل
فارنهایت
فاز
فاصله
فاصلهٔ
فاصلهگیری
فاضلاب
فاطمه
فاطمهٔ
فاطمی
فاطیمای
فاعل
فال
فامیل
فانوس
فاکس
فاکسنیوز
فایبرگلاس
فایده
فایل
فاینانس
فایننشال
فتح
فتحعلی
فتحی
فتحالله
فتحاللهی
فتنه
فتنهای
فتنهگری
فتوای
فتوکپی
فتیله
فجر
فحش
فحشاء
فحوای
فخرفروشی
فدا
فداکاری
فدای
فر
فرآورده
فرآوری
فرآیند
فرآیندی
فرات
فراخان
فراخوان
فرار
فرارسیدن
فراز
فراغی
فرامرز
فراموشی
فرانسه
فرانسوی
فرانک
فرانکفورت
فراهم
فراوانی
فراکسیون
فراگیری
فرایبورگ
فرایند
فرارسیدن
فرجی
فرحزاد
فرخداشت
فرد
فردریک
فردفرد
فردوسی
فردی
فردفرد
فرزاد
فرزدق
فرزند
فرزندان
فرزندی
فرسایش
فرستادن
فرسخ
فرش
فرشته
فرشچیان
فرصت
فرصتی
فرض
فرضیه
فرق
فرقه
فرقهگرایی
فرقی
فرم
فرما
فرمان
فرماندار
فرمانداری
فرمانده
فرماندهی
فرمانروا
فرمانروای
فرمایش
فرمول
فرمولی
فرناندز
فرنگ
فرنگی
فرهاد
فرهنگ
فرهنگسرای
فرهنگی
فرهنگسازی
فروتن
فرود
فرودنفر
فرودگاه
فروش
فروشنده
فروشگاه
فروغ
فروغی
فروند
فروپاشی
فرورفتن
فروپاشی
فرچه
فریاد
فریب
فریبرز
فریدونشهر
فزاری
فسا
فساد
فسادی
فستیوال
فسخ
فشار
فشردهای
فصل
فصلنامه
فصلنامهٔ
فصلنامه
فصلنامهٔ
فضا
فضائی
فضاحت
فضاسازی
فضانورد
فضانوردی
فضاپیمایی
فضای
فضایل
فضایی
فضل
فضلای
فضلا
فضولات
فضیلت
فعالان
فعالیت
فعل
فقدان
فقر
فقرای
فقره
فقه
فقیر
فقیه
فلات
فلان
فلجی
فلز
فلزاتی
فلس
فلسطینی
فلسفه
فلسفهٔ
فلفل
فلک
فلکالافلاک
فمینیسم
فن
فنا
فنجان
فنلاند
فنیک
فنیکی
فنآوری
فهر
فهرست
فهرستنگاری
فهری
فهم
فواید
فوت
فوتبال
فوتبالی
فوتسال
فور
فوران
فوریت
فوریه
فولاد
فوکو
فک
فکر
فکرشو
فکری
فیاضی
فیبر
فیتز
فیتزجرالد
فیتو
فیروز
فیروزآباد
فیروزه
فیزیک
فیشر
فیصله
فیض
فیضی
فیفا
فیلد
فیلسوف
فیلسوفی
فیلم
فیلمبرداری
فیلمساز
فیلمسازی
فیلمنامه
فیلمنامهای
فیلمی
فیلمساز
فیلیپ
فیالمعادلات
ق
قائدی
قائم
قائممقام
قاب
قابلیت
قاتل
قاتلان
قاجار
قاجاریه
قاره
قاسم
قاضی
قاطر
قاعده
قالب
قالی
قالیفروش
قالیفروشی
قامت
قانونمداری
قانونگذاری
قانونشکنی
قاهره
قاچاق
قاچاقچی
قایدی
قایق
قایل
قبادی
قبال
قبایل
قبر
قبرستان
قبضه
قبل
قبول
قبیل
قبیله
قبیلهٔ
قبیلهای
قتل
قحطی
قد
قدباء
قدح
قدحِ
قدحی
قدر
قدرت
قدرتی
قدرتطلبی
قدرتنمایی
قدردان
قدردانی
قدرشناسی
قدری
قدس
قدسی
قدم
قدما
قدمت
قرآن
قرآنسوزی
قرائت
قرائن
قرار
قرارداد
قراردادی
قربان
قربانی
قربانیان
قرص
قرض
قرعهکشی
قرقیزستان
قرمز
قرمزها
قرمزی
قرن
قرنطینه
قرهقاسملو
قرهقو
قریحه
قریش
قرینهای
قزاقستان
قساوت
قسطنطنیه
قسم
قسمت
قسمتی
قشر
قشلاق
قشم
قشنگی
قصاص
قصد
قصر
قصه
قصهٔ
قصور
قضائیه
قضاوت
قضای
قضایا
قضاییه
قضیه
قضیه
قضیهای
قضیهیی
قطار
قطب
قطر
قطرهٔ
قطع
قطعه
قطعهای
قطعیت
قعر
قفسه
قفقاز
قفل
قل
قلب
قلع
قلعه
قلعهای
قلقشندی
قلقلک
قلم
قلمرو
قلمزن
قله
قلک
قم
قمر
قمع
قمی
قنائی
قنات
قناتکنی
قناعت
قنبری
قند
قندهار
قندیلی
قهرمان
قهرمانی
قهرمانبازی
قهقههٔ
قهوهخانه
قهوهچی
قو
قواره
قواعد
قوام
قوای
قوت
قورت
قوزک
قوس
قوسی
قول
قوم
قوه
قوهٔ
قوچان
قویترین
قُرق
قیاس
قیام
قیامت
قید
قیروان
قیس
قیصر
قیم
قیمت
قیمتی
قیژقیژ
لااله
لاالهالاالله
لابلای
لابهلای
لاتنبرگ
لارپوبلیکا
لاری
لاریجانی
لازمه
لازمهٔ
لازمه
لاشه
لاله
لامبروس
لاپوشانی
لاپیداس
لاک
لاکتوز
لاکپشت
لای
لایحه
لایه
لاییسم
لب
لباس
لباسی
لبخند
لبخندکی
لبخندی
لبنان
لبنانی
لبنیات
لبه
لثه
لجاجت
لجن
لحاظ
لحاف
لحظه
لحظهٔ
لحظهای
لحظهیی
لحن
لحود
لذایذ
لذت
لذتی
لذتجویی
لرد
لرزش
لرزهنگاری
لرزیدن
لرستان
لزوم
لزکو
لسترنج
لسآنجلس
لشکر
لشکرکشی
لشگر
لطافت
لطف
لطفی
لطمه
لعل
لعن
لغزش
لغو
لفظ
لفظی
لقب
لقمه
لمس
لن
لندن
لنده
لنگرودی
لنگن
لنگه
لهجه
لهجهای
لهستان
لوئیس
لوازم
لواسان
لواسانات
لوبیا
لوت
لوتوس
لوح
لوسمی
لوسآلاموس
لوسآنجلس
لوفتهانزای
لول
لوله
لولهکشی
لولهگذاری
لوموند
لوور
لوییس
لچک
لکنت
لکه
لکهنو
لگد
لگن
لی
لیااونینگ
لیبرال
لیبرالیسم
لیبی
لیتر
لیث
لیس
لیست
لیستی
لیف
لیلا
لیورپول
لیونل
لیکک
لیگ
م
مآثر
مآخذ
مأدیان
مأذنزاده
مألف
مألفان
مألفه
مألفهای
مألفی
مأمنی
مأمور
مأموران
مأموریت
مأموریت
مأید
مؤسسه
مؤمن
مؤمنی
ما
مااشکل
مابقی
ماتمی
ماجرا
ماجرای
ماجرایی
ماد
مادام
مادر
مادری
ماده
مادهای
مادونقرمز
مادگی
مادیا
مادیات
مار
مارتا
مارجری
مارس
مارلیک
مارک
مارکس
ماری
ماریتسیوتوزی
ماریو
مازاد
مازندران
ماساچوست
ماست
ماشین
ماشینآلات
مافیا
مافیایی
مال
مالزی
مالش
مالک
مالکوم
مالکومایکس
مالکیت
مامور
مان
مانا
ماندن
مانع
مانور
مانی
مانیل
ماه
ماهنامه
ماهنامهٔ
ماهواره
ماهود
ماهگی
ماهی
ماهیت
ماوراأبنفش
ماکااو
ماکس
مایع
مایل
ماینوکسیدیل
ماینینگ
مایه
مایهٔ
مایکروسافت
مباحث
مبادرت
مبادله
مبارز
مبارزه
مبارک
مبارکه
مباشرت
مبالغ
مبالغی
مبانی
مبتلا
مبتکر
مبدأ
مبدل
مبصر
مبلغ
مبلغی
مبنا
مبنای
مبهم
متابولیسم
متارکه
متالورژی
متان
متانت
متحجر
متحد
متحدی
متخصص
متر
مترجم
مترسک
مترمربع
مترمکعب
متری
مترمربع
متصدی
متعرض
متفاوت
متفکر
متقاضی
متقیان
متمم
متن
متنی
متهم
متهمان
متوجه
متوسط
متولد
متولی
متکلم
مثابه
مثال
مثالی
مثانه
مثل
مثلث
مجارستان
مجازات
مجال
مجالس
مجامع
مجاهده
مجاورت
مجتبی
مجتمع
مجتهدان
مجرا
مجرای
مجرد
مجرم
مجروح
مجری
مجریه
مجریگری
مجسمه
مجل
مجلد
مجلس
مجلسی
مجله
مجمع
مجمعالشعرا
مجمعالشعرای
مجموع
مجموعه
مجموعهٔ
مجموعهای
مجموعهساز
مجوز
مجوزی
مجید
مجیدی
محاسبه
محاسن
محاسنی
محاصره
محافظت
محافظهکار
محافل
محافلی
محاق
محاکم
محاکمه
محاکمهٔ
محبت
محبتِ
محبوبه
محبوبیت
محبینیا
محتوا
محتوای
محتوی
محدوده
محدودیت
محدودیتی
محراب
محرر
محرم
محرمیت
محروق
محرومیت
محرومیتزدایی
محسن
محصول
محض
محضر
محفل
محقق
محل
محله
محلهای
محلول
محلی
محمد
محمدآباد
محمدرضا
محمدعلی
محمدی
محمدباقر
محمدجعفر
محملی
محمود
محمودیان
محموله
محمولهٔ
محور
محوریت
محوطه
محک
محکمات
محکمه
محکوم
محکومیت
محکومیتی
محیط
محیطی
مخابرات
مخابره
مخاطب
مخاطبی
مخالف
مخالفت
مخالفی
مختار
مختومقلی
مخلص
مخلوط
مخملباف
مد
مدائن
مداخل
مداخله
مدار
مدارس
مدارک
مدافعات
مدال
مدت
مدتها
مدتی
مدح
مدحکننده
مدد
مددجو
مدرسه
مدرسه
مدرسهای
مدرک
مدرکی
مدعا
مدعای
مدعی
مدعیات
مدل
مدلسازی
مدنیت
مدیترانه
مدیر
مدیرعامل
مدیره
مدیرکل
مدیریت
مدیرعامل
مدیرمسئول
مدیرمسوول
مدینه
مذاق
مذاکره
مذاکرهکننده
مذمت
مذهب
مرآت
مراتب
مراتع
مراجع
مراجعت
مراجعه
مراحل
مراد
مرادیان
مراسم
مراسمی
مراغه
مراقب
مراقبت
مرال
مراوده
مراودهای
مراوه
مراکز
مربی
مربیگری
مرتبه
مرتبهٔ
مرتضی
مرتع
مرتعداری
مرج
مرجع
مرحله
مرحلهٔ
مرحلهای
مرحوم
مرخصی
مرد
مرداد
مرداس
مردم
مردمان
مردمی
مردم
مردمسالاری
مردمشناسی
مرده
مردهای
مردی
مرز
مرزبندی
مرزی
مرعشی
مرغ
مرمت
مرمر
مروارید
مرواریددوزی
مروان
مروانبنحکم
مرور
مروری
مروی
مرکب
مرکبات
مرکز
مرکزی
مرکوری
مرگ
مری
مریخ
مریضی
مریم
مزار
مزارع
مزایا
مزایده
مزدوری
مزرعه
مزرعهای
مزهپرانی
مس
مسئله
مسئلهٔ
مسئلهای
مسئول
مسئولیت
مسئولیتپذیر
مسئولیتپذیری
مسائل
مسائلی
مسابقه
مسابقهٔ
مساجد
مساحت
مساحتی
مسافت
مسافر
مسافرت
مسالت
مساله
مسالهای
مسامحه
مسایل
مستان
مستشار
مستلزم
مستند
مستوجب
مستوفیالممالک
مستی
مسجد
مسجدجامعی
مسجدالنبی
مسعود
مسقط
مسلسل
مسلمان
مسلمانی
مسلمیان
مسلک
مسند
مسندی
مسواک
مسوول
مسکن
مسکو
مسیح
مسیحی
مسیر
مسیری
مشاجره
مشارالیه
مشارف
مشارکت
مشاغل
مشاهده
مشاهدهٔ
مشاهیر
مشاور
مشاوره
مشایعت
مشت
مشترک
مشترکات
مشتری
مشتق
مشتمال
مشخصات
مشخصه
مشرف
مشرق
مشروب
مشروح
مشروطیت
مشروعیت
مشروعیتی
مشعل
مشغله
مشهد
مشورت
مشک
مشکل
مشکلی
مشکوه
مشی
مشیب
مشیرالدوله
مصاحب
مصاحبه
مصاحبهای
مصادره
مصادیق
مصادیقی
مصاف
مصالح
مصالحه
مصباح
مصداق
مصدر
مصدق
مصر
مصرعی
مصرف
مصرفکننده
مصری
مصطفی
مصلحت
مصلحتسنجی
مصوبه
مصوبهای
مصونیت
مضیقه
مطالب
مطالبه
مطالبی
مطالعه
مطالعهٔ
مطالعهای
مطبخ
مطبوعات
مطبوعه
مطرحکننده
مطلب
مطلبی
مطلع
مطلقگرائی
مظان
مظاهر
مظلومیت
مظهری
معابدی
معابر
معادله
معادن
معارضه
معارف
معاش
معاشرت
معاصر
معالج
معالجه
معامله
معامله
معاند
معاون
معاونت
معاویه
معاینه
معبد
معبدی
معتاد
معتقد
معجزه
معدن
معدنچی
معده
معرض
معرف
معرفی
معرفی
معرکه
معشوق
معصومی
معضل
معضلی
معظمله
معلم
معلمی
معلولیت
معما
معماری
معمای
معمایی
معنا
معنائی
معنای
معنایی
معنویت
معنی
معیار
معیشت
مغازه
مغازهٔ
مغازهای
مغان
مغرب
مغربزمینیان
مغرض
مغز
مغول
مغیره
مغیرهبنشعبه
مفاخر
مفاد
مفاصل
مفاهمه
مفاهیم
مفاهیمی
مفرح
مفسده
مفهوم
مفهومی
مقابر
مقابل
مقابله
مقادیر
مقاطع
مقال
مقاله
مقالهٔ
مقاله
مقالهای
مقالهیی
مقام
مقامی
مقاومت
مقایسه
مقایسهٔ
مقبره
مقبولیت
مقتضیات
مقدار
مقداری
مقدسات
مقدم
مقدماتی
مقدمه
مقدمهٔ
مقدمهای
مقدمی
مقر
مقررات
مقصد
مقصر
مقصود
مقصودی
مقطع
مقطعی
مقلد
مقننه
مقنی
مقوله
مقولهای
مقیاس
مقیم
ملا
ملات
ملاحت
ملاحظه
ملاحظهای
ملاصدرا
ملاطفت
ملافیضی
ملاقات
ملامت
ملامتگری
ملامتی
ملاک
ملایمت
ملت
ملتی
ملل
ملودرام
ملوس
ملک
ملکشاه
ملکوم
ملکی
ملیان
ملینا
ملیگرا
ممانعت
ممر
مملکت
ممنوعیت
ممیز
ممیزی
من
منابر
منابع
منابعی
منادی
منازعت
منازل
مناسبات
مناسبت
مناسبتی
مناسک
مناطق
مناطقی
مناظر
منافع
مناقشه
منامه
منبر
منبع
منت
منتجبنیا
منتخب
منتخبالتواریخ
منتقد
منتقدان
منجم
منجمی
منجنیق
منحرف
منحنی
مندرجات
منزل
منزلت
منزله
منزلگاه
منسوجات
منش
منشأ
منشاء
منشی
منصور
منطق
منطقه
منطقهٔ
منطقهالبروج
منطقهای
منظر
منظره
منظور
منظوری
منظومه
منظومهای
منع
منم
منهای
منوچ
منویات
منِ
منچستر
منکر
منگستاو
منیژه
منییر
مه
مهاجر
مهاجرانی
مهاجرت
مهاجم
مهار
مهارت
مهارکننده
مهد
مهدی
مهر
مهربانی
مهرجویی
مهرماه
مهره
مهرهای
مهریه
مهلت
مهم
مهمان
مهمانی
مهمی
مهند
مهندس
مو
مواجهه
مواخذه
مواد
موادی
موارد
مواردی
موازات
مواضع
موافق
موافقت
موافقتنامه
موافقتی
مواقع
مواقعی
موانع
موبایل
موتلفه
موتورپمپ
موتیلیتی
موج
موجب
موجبات
موجود
موجودی
موجودیت
موجی
موجشکن
موحدی
مودودی
مورخ
مورخان
مورد
موردو
موردی
مورسیای
مورنینگ
موز
موزاایک
موزاییک
موزه
موزهٔ
موسائیان
موساد
موسسه
موسم
موسه
موسوی
موسی
موسیقی
موسیقیی
موش
موشی
موضع
موضعگیری
موضعگیری
موضوع
موضوعی
موعد
موعظه
موفقیت
موفقیتی
موقع
موقعی
موقعیت
مولانا
مولای
مولد
مولف
مولود
مومن
مونتاژ
مونترال
مونتی
مونس
مونسی
موی
مُهر
مک
مکاتب
مکاتبه
مکان
مکانی
مکانیسم
مکانیسمی
مکتب
مکث
مکر
مکرمی
مکرمیفر
مکزیک
مکزیکوسیتی
مکزیکوسیتی
مکعب
مکمل
مکنونات
مکه
می
میان
میاندوآب
میانه
میانهروی
میانهسالی
میاندورهای
میبد
میتراییسم
میخانه
میخانهٔ
میخانهای
میخوارگی
میخک
مید
میدان
میدانداری
میدلایست
میر
میرآبادی
میراث
میرزا
میرزای
میرشکرایی
میرعماد
میرفیضی
میرمحمدی
میز
میزان
میزانی
میزانالحکمه
میزبان
میزبانی
میزگرد
میزگردی
میشل
میشلر
میل
میلاد
میلان
میلانی
میلر
میله
میلیارد
میلیون
میلیلیتر
میلیمتر
میلیمتری
میمنت
مینودشت
میهمان
میهمانی
میهوی
میور
میوه
میکائیلی
میکده
میکرب
میکروب
میکروبیولوژی
میکروفون
میگرن
میدادند
میپرد
ناامنسازی
ناامیدی
نااوم
ناباوری
نابرابری
نابسامانی
نابغه
نابودی
ناتوانی
ناحیه
ناحیهٔ
ناحیهای
ناخشنودی
ناخن
نادانی
نادرستی
نادمان
نادیدنی
نار
ناراحتی
نارسایی
نارضایتی
نارو
ناز
ناسا
ناسزا
ناسیونال
ناشتائی
ناصبی
ناصح
ناصر
ناصرخسرو
ناصری
ناطق
ناظر
ناظری
نافرمانی
نالهٔ
نالوطی
نام
نامبرده
نامدار
نامردمی
نامزد
نامزدی
نامزذ
نامه
نامهٔ
نامه
نامهای
نامور
ناموس
نامگذاری
نامی
نامیدن
نان
نانتو
نانخور
ناهار
ناهماهنگی
ناهمسویی
ناهنجاری
ناوهکش
ناوگان
ناپایداری
ناپختگی
ناکارایی
ناکامی
ناکانوجو
نایب
نایبالزیاره
نایل
نبرد
نبهره
نبود
نبودن
نبوغ
نبوی
نبی
نتایج
نتایجی
نتردام
نتیجه
نتیجهٔ
نتیجهای
نثر
نجابت
نجات
نجار
نجف
نجمآبادی
نجوم
نجوی
نجیب
نحو
نحوه
نحوهٔ
نحوی
نخ
نخبه
نخستوزیر
نخستوزیری
نخل
نخلستان
نخود
نخیله
نداشتن
ندانمکاری
نذیر
نراقی
نرخ
نرده
نرسیدن
نرمش
نرمافزار
نرمافزاری
نرمتن
نروال
نروژ
نزدیکان
نزدیکی
نزول
نزولات
نسب
نسبت
نسبتی
نسخ
نسخه
نسخهٔ
نسخهبرداری
نسخهپیچی
نسخی
نسل
نسوج
نسوز
نسیم
نشاط
نشاطی
نشان
نشاندهنده
نشانه
نشانهٔ
نشانگر
نشانی
نشاندهنده
نشت
نشدن
نشر
نشریه
نشریهای
نشست
نشستی
نشویل
نصاب
نصاری
نصایح
نصب
نصرآبادی
نصرالله
نصرت
نصرتالله
نصرهالدوله
نصف
نصیب
نصیبی
نصیحت
نصیر
نصیری
نصیریان
نطفه
نطق
نطنز
نظارت
نظارتی
نظاره
نظافت
نظام
نظامی
نظر
نظرات
نظرسنجی
نظری
نظریات
نظریه
نظریهپرداز
نظریهپردازی
نظم
نظیر
نعل
نعمت
نغمهسرائی
نغمهپرداز
نفاق
نفایس
نفایسالمآثر
نفت
نفخ
نفر
نفرتی
نفره
نفری
نفس
نفسی
نفع
نفهمی
نفوذ
نفوذی
نفی
نقابی
نقار
نقاش
نقاشی
نقاشباشی
نقاط
نقبی
نقد
نقدی
نقدینگی
نقرس
نقره
نقش
نقشه
نقشهکشی
نقشی
نقص
نقض
نقطه
نقطهٔ
نقطهای
نقطهضعف
نقطهنظر
نقل
نقلمکان
نقوش
نم
نماد
نماز
نمازجمعه
نمازی
نمازجمعه
نمامی
نماندن
نمای
نمایاندن
نمایانگر
نمایش
نمایشنامه
نمایشنامهای
نمایشگاه
نمایشگاهی
نماینده
نمایندهٔ
نمایندهای
نمایندگی
نمایندگی
نمره
نمرهٔ
نمو
نمود
نموداری
نمودن
نمونه
نمونه
نمک
نمنم
ننه
ننگ
نه
نهاد
نهادن
نهادی
نهال
نهالکاری
نهاوندی
نهایت
نهصد
نهضت
نهضتی
نهمی
نهی
نهیازمنکر
نوآوری
نوآوری
نواب
نواحی
نوار
نواز
نوازش
نوازنده
نواله
نوامبر
نوبت
نوبخت
نوبه
نوجوان
نوجوانی
نود
نور
نورآباد
نورا
نورافشانی
نورافکن
نوربخش
نورنبرگ
نورپردازی
نوری
نوزاد
نوزادی
نوسان
نوش
نوشابهسازی
نوشتار
نوشتن
نوشته
نوشتهٔ
نوشهر
نوشیدن
نوع
نوعی
نوقان
نوقه
نولت
نوه
نوک
نوگرایی
نوید
نویدی
نویسنده
نویسندهٔ
نویسندهای
نُزهت
نپال
نژاد
نژادستیزی
نکته
نکتهٔ
نکتهای
نکردن
نکوهش
نگار
نگارش
نگارشگر
نگارنده
نگارندهٔ
نگاه
نگاهداری
نگاهی
نگرانی
نگرش
نگرشی
نگرفتن
نگه
نگهبان
نگهبانی
نگهدارنده
نگهدارندهٔ
نگهداری
نیاز
نیازاف
نیازی
نیافتن
نیام
نیایش
نیایشگاه
نیت
نیجریه
نیرو
نیروگاه
نیروی
نیری
نیزر
نیزه
نیزهبازی
نیستی
نیش
نیشابور
نیشابوری
نیشکر
نیل
نیلوفر
نیم
نیما
نیمایی
نیمه
نیمهانسان
نیمهحیوان
نیمکت
نیمکتی
نیمکره
نیمی
نیمرخ
نیوتن
نیوساینتیست
نیومکزیکو
نیویورک
نیچر
نیچه
نیکل
نیکوکار
نیکی
نیکنولت
ه
هادی
هارا
هارش
هاشمی
هاشمیپور
هافبک
هالدنی
هالهای
هالیوود
هامبورگ
هانت
هاوانا
هاوایی
هتل
هتک
هجده
هجرت
هجمه
هجوم
هخامنشی
هدایا
هدایای
هدایایی
هدایت
هدر
هدف
هدفِ
هدفگیری
هدیه
هدیهای
هر
هرات
هراس
هراسی
هربرت
هرج
هرقل
هرمز
هرمزگان
هرهریمسلکی
هروی
هرکدام
هرکس
هرکه
هزار
هزاره
هزارگان
هزینه
هزینهٔ
هزینهای
هشت
هشتاد
هشدار
هشیاری
هضم
هفت
هفتاد
هفتصد
هفته
هفتهٔ
هفتهای
هفتهنامه
هفتامامی
هفتتیر
هفتسنگ
هفتپیچ
هفده
هقهق
هلدنپلاتس
هلند
هلیکوباکتر
هلیکوپتر
هم
همائی
همان
همانی
هماهنگی
هماهنگکنندگی
همایش
همایی
همبستگی
همت
همتای
همخوانی
همدان
همدانی
همدردی
همدلی
همدیگر
همذاتپنداری
همراه
همراهی
همزیستی
همسانی
همسایه
همسایهای
همسخنی
همسر
همسویی
همشهری
همفکر
همفکری
همه
همهٔ
همه
همهاش
همهپرسی
هموطن
هموم
همومی
همکار
همکاری
همکلاسی
همگامی
همگان
همگرایی
همگی
همیشه
همین
هماندیشی
همخوانی
هممیهن
هند
هندسه
هندسهدان
هندسهدانی
هندشناسی
هندوستان
هندی
هندبال
هنر
هنرجو
هنردوست
هنرمند
هنرمندی
هنرنمایی
هنروری
هنرپیشه
هنرپیشهٔ
هنگامه
هنگکنگ
هنگگنگ
هوا
هواخواه
هوادار
هوانوردی
هواپیما
هواپیمای
هوای
هوتلودوش
هورس
هورمون
هوس
هوشیار
هوشیاری
هوشیمینه
هول
هوچیگر
هوگو
هویت
هویج
هُش
هژبر
هژیر
هکتار
هی
هیئت
هیئتی
هیئترئیسه
هیئتمدیره
هیات
هیاهو
هیتو
هیثم
هیجان
هیدرواستاتیک
هیدروژن
هیدروکربن
هیروهیتو
هیلاری
هیلملند
هیمالیا
هیپوکلسمی
هیچ
هیچکدام
هیچکس
هیچگونه
هیچی
هیچیک
هیچیک
هیسای
هقهق
و
وابسته
وابستگی
واتل
واجپایی
واحد
وادی
وارث
وارد
واردا
واردات
وارسی
وارو
واریز
واسط
واسطه
واسطی
واشنگتن
واشنگتندیسی
وافلکوفر
واقعه
واقعهای
واقعیت
واقعیتی
واقعگرایی
واقف
والتر
والنسیا
والی
والیبال
وام
واپسگرائی
واپسگرایی
واژه
واژهای
واکسن
واکسنی
واکنش
واکنشی
واگذاری
وجاهتی
وجدان
وجدان
وجه
وجهه
وجهٔ
وجهی
وجود
وجودی
وجوهی
وجیهالمله
وحدت
وحدتی
وحشت
وحی
وحید
وداع
ور
وراکروز
ورای
ورزش
ورزشکار
ورزشگاه
ورق
ورقه
ورلن
ورم
ورمیا
ورمیتک
ورود
وزارت
وزارتخانه
وزارتی
وزرا
وزرای
وزش
وزن
وزنه
وزوز
وزیر
وزیری
وسایل
وست
وسط
وسعت
وسعتی
وسوسه
وسکی
وسیله
وسیلهٔ
وسیلهیی
وصف
وصل
وصله
وضع
وضعی
وضعیت
وضعیتی
وضوح
وطن
وظایف
وظیفه
وظیفهای
وعاظ
وعده
وعده
وعظ
وفات
وفادار
وفاداری
وفاق
وقاص
وقایع
وقت
وقتی
وقف
وقفه
وقوع
وقوعی
وقوف
ولادت
ولایت
ولایتعهدی
ولت
ولخرجی
ولفگانگ
وله
ولی
ولید
ولیدبنعتبه
ولیعصر
ولیعهد
ولینگوتن
ولیزاده
ونزوالا
ونکوور
ونیز
ونجی
وهابزاده
وهله
وود
وولاتسیامیتا
وومرای
ووپکه
وکلایی
وکیل
وکیلی
وی
ویتال
ویتامین
ویتدال
ویتنام
ویداو
ویرانی
ویرجینیای
ویروس
ویروسی
ویزای
ویلای
ویلر
ویلما
ویلیام
ویچ
ویژوالبیسیک
ویژگی
ویکنز
ویجینت
پا
پابلو
پادشاه
پادشاهی
پارامتر
پارس
پارسال
پارسایی
پارلمان
پارهای
پارچه
پارک
پارکر
پارکینگ
پاریز
پاریزی
پاریس
پاس
پاسخ
پاسخگو
پاسخگوئی
پاسخگوی
پاسخگویی
پاسخی
پاسخدهنده
پاسدار
پاسداران
پاسداری
پاسکاری
پاسکال
پافشاری
پالرمو
پالو
پانزده
پانصد
پاوه
پاپ
پاپاکاستاس
پاچاجی
پاکدامنی
پاکسازی
پاکستان
پاکی
پاکنژاد
پاککننده
پاگرد
پای
پایان
پایانه
پایانهای
پایانی
پایاننامه
پایبندی
پایتخت
پایداری
پایه
پایهٔ
پایهگذاری
پایکوبی
پایگاه
پایی
پاییز
پایین
پایبندی
پتاسیم
پتانسیل
پتانسیلی
پتروشیمی
پتروپارس
پتو
پتی
پخش
پخشکننده
پدر
پدربزرگ
پدرشوهر
پدری
پدیدار
پدیده
پدیدهای
پذیرایی
پذیرش
پذیرفتن
پر
پرادش
پراگ
پرتاب
پرتغال
پرتغالی
پرتو
پرخاش
پرداخت
پرداختن
پرداختی
پردازش
پرده
پردهبرداری
پردهپوشی
پرستاری
پرستشگاه
پرسش
پرسشنامهای
پرسشگری
پرسششونده
پرسه
پرش
پرفسور
پرنده
پرندهای
پرهیز
پرو
پرواز
پروتئین
پرودی
پروردگار
پروردگارا
پرورش
پروستات
پروفسور
پرونده
پروژه
پروژهٔ
پروژهای
پروژهسازی
پرویز
پرچم
پرچمداری
پری
پریاسی
پریتچارد
پریودودنتیکس
پریوش
پز
پزشک
پزشکی
پس
پست
پسته
پسر
پسربچهای
پسرعموی
پسری
پسرعموی
پسیخانی
پسلرزه
پسمانده
پسپریروز
پشت
پشتوانه
پشتوانهٔ
پشتوانهای
پشتک
پشتکار
پشتیبانی
پشتبام
پشتنویس
پشتنویسی
پشم
پشنگه
پشه
پشیمانی
پف
پل
پلاتو
پلادیوم
پلانک
پلاک
پلدختر
پلنگ
پله
پلو
پلوتونیم
پلوتونیوم
پلکان
پلکانی
پلی
پلیس
پلیسی
پنالتی
پناه
پناهنده
پناهندگی
پناهگاه
پناهگاهی
پنبه
پنج
پنجاه
پنجره
پنجشنبه
پنجم
پنجه
پند
پنسیلوانیا
پنهانکاری
پنیر
پهلوان
پهلوی
پودر
پورتو
پوردو
پورمحمدی
پوریای
پورچالوای
پوست
پوستر
پوسته
پوسیدگی
پوشاک
پوشش
پوششی
پول
پوند
پوندی
پونک
پوکی
پویایی
پژواکی
پژوهش
پژوهشگر
پژوهشگری
پژوهشی
پکن
پگاه
پی
پیادهرو
پیاز
پیاله
پیام
پیامبر
پیامبری
پیامد
پیامی
پیامبرنده
پیتر
پیدائی
پیدایش
پیر
پیرازنیامید
پیراهن
پیراهنی
پیرترین
پیرزن
پیرمرد
پیرمردی
پیرنیا
پیرو
پیروزی
پیروی
پیری
پیشانی
پیشانی
پیشاهنگ
پیشاور
پیشبرد
پیشرفت
پیشنهاد
پیشه
پیشهٔ
پیشوای
پیشکسوت
پیشکش
پیشگاه
پیشگویی
پیشگیری
پیشی
پیشینه
پیشینی
پیشبینی
پیشتولید
پیشفرض
پیشقدم
پیشپرداخت
پیشکسوت
پیغام
پیغمبر
پیلوری
پیمان
پیمانی
پینگپنگ
پیوستن
پیوستگی
پیوند
پیچ
پیچیدگی
پیک
پیکار
پیکاسو
پیکان
پیکر
پیکره
پیکوگرم
پیگرد
پیگیری
پیگیریای
پیتیای
پیریزی
پیگیری
چادگان
چار
چارلز
چاره
چارهای
چارهجویی
چارچوب
چاقو
چاقی
چالدران
چالش
چانه
چانهزنی
چاه
چاهه
چاپ
چاپلوسی
چاپی
چای
چاینا
چتر
چخماق
چراغ
چراغگردان
چرام
چربی
چرخ
چرمی
چسب
چشم
چشمان
چشمداشت
چشمم
چشمه
چشمک
چشمی
چشمانداز
چشماندازی
چشمپوشی
چغابیت
چغازنبیل
چلوکباب
چلکوفسکی
چمخاله
چمدان
چمران
چمن
چنارود
چناری
چنان
چنبره
چند
چنددستی
چندی
چنگیز
چه
چهار
چهارشنبه
چهارصد
چهره
چهرهٔ
چهره
چهرهای
چهل
چهلم
چوآیو
چوب
چوبی
چوکا
چوکای
چویو
چپاول
چچن
چک
چکاد
چگونه
چگونگی
چی
چیدن
چیز
چیزی
چینی
چینتایپه
ژان
ژانر
ژانگ
ژاپن
ژاپنی
ژرار
ژن
ژنتیک
ژنرال
ژنو
ژوئن
ژوایه
ژوسپن
کاانات
کاباره
کابلی
کابوس
کابینه
کاج
کاخ
کادر
کار
کارآموز
کارآیی
کارابولو
کارایی
کاربرد
کاربری
کارتاخنا
کارخانه
کارخانهای
کارداران
کارش
کارشناس
کارشناسی
کارشکنی
کارفرما
کارفرمای
کارمند
کارمندی
کارنامه
کارنامهٔ
کاروان
کاروانی
کارولینای
کارپرداز
کارکرد
کارکردی
کارکنان
کارگاه
کارگر
کارگران
کارگردان
کارگردانی
کارگزار
کارگزارانم
کارگشایی
کاری
کاریستو
کاریکاتور
کاریکاتوریست
کارگه
کاسبرگ
کاسبی
کاستن
کاستی
کاسه
کاشان
کاشانه
کاشانی
کاشف
کاشی
کاظم
کاغذ
کاغذگر
کافر
کالا
کالای
کالبد
کالج
کالری
کالیفرنیا
کام
کامبیز
کامجویی
کامیون
کانادا
کانال
کانتیکت
کاندیدا
کانهآرایی
کانون
کانگورو
کانی
کانیمد
کاننای
کاهش
کاهی
کاوش
کاوشگر
کاوشگری
کاوه
کاووس
کاکس
کبری
کبودرآهنگ
کتاب
کتابت
کتابخانه
کتابخانه
کتابعلی
کتابچه
کتابی
کتابخوانی
کتب
کتمان
کتیبه
کثرت
کد
کدام
کدورت
کدکنی
کدکین
کدیور
کرانه
کرانهٔ
کراوات
کرب
کرباسچی
کرباسیان
کربلا
کربلای
کربلایی
کربن
کربوهیدرات
کرج
کرد
کردار
کردافشار
کردستان
کردن
کردگار
کرسی
کرم
کرمان
کرمانشاه
کرمانی
کرنش
کره
کرواسی
کروبی
کریس
کریستی
کریستینساینسمانیتور
کریم
کس
کسالت
کسان
کسانی
کسب
کسراییان
کسری
کسی
کش
کشاندن
کشاورزان
کشاورزی
کشت
کشتار
کشتزار
کشتزاری
کشتن
کشته
کشتهشده
کشتی
کشتیرانی
کشتیگیر
کشف
کشمکش
کشور
کشوری
کشکان
کشیدن
کشیش
کعب
کعبه
کف
کفار
کفاف
کفر
کفراج
کفش
کفن
کفوی
کلاس
کلاله
کلام
کلان
کلانتری
کلاه
کلاهبرداری
کلاهدوز
کلاوس
کلاژن
کلبعلی
کلت
کلسترول
کلسیم
کلم
کلمبیا
کلمه
کلمهٔ
کلمهای
کله
کلهر
کلهٔ
کلورادو
کلوپ
کلک
کلیات
کلید
کلیر
کلیسا
کلیسای
کلیشه
کلیشهای
کلیمن
کلیه
کلیهٔ
کلیگویی
کم
کمال
کمالبخشی
کمان
کمانه
کمبریج
کمبود
کمر
کمردرد
کمند
کمونیست
کمپ
کمپانی
کمک
کمکت
کمکی
کمکرسانی
کمککننده
کمیت
کمیته
کمیسر
کمفرهنگی
کملطفی
کممحبتی
کن
کنار
کناره
کنارهگیری
کناری
کنتراست
کنترل
کنتس
کنج
کندو
کندوان
کندی
کنسرسیوم
کنش
کنفرانس
کنفرانسی
کنوانسیون
کنکاش
کنگره
کنگرهٔ
کنگو
کنیت
کهنوج
کهنگی
کهکشان
کهکیلویه
کوالالامپور
کوبا
کوبه
کوبهرو
کوتاهی
کوتهنگری
کود
کودتا
کودتای
کودک
کودکانِ
کودکی
کور
کوران
کورس
کوره
کورو
کوزه
کوسه
کوسهای
کوشا
کوشش
کوششی
کوفه
کونگفوتوآ
کوه
کوهباچر
کوهدشت
کوهسار
کوهستان
کوهنورد
کوهنوردی
کوهی
کوپن
کوپنفروش
کوچ
کوچه
کوچک
کوکان
کوکاکولا
کوی
کویت
کویر
کپی
کپیبرداری
کی
کیارستمی
کیبیلا
کیتکت
کید
کیزو
کیزوابوچی
کیسه
کیش
کیف
کیفیت
کیلو
کیلومتر
کیلومتری
کیلووات
کیلوگرم
کیمیای
کینه
کینهای
کیهان
کیو
کیک
کیکاووس
کییف
گااو
گاتنر
گاز
گازرسانی
گازوایل
گازوییل
گالری
گالوپ
گالیله
گام
گاما
گامی
گاندی
گاه
گاو
گاگو
گبه
گجرات
گذاردن
گذاشتن
گذر
گذران
گذراندن
گذرگاهی
گذشت
گذشته
گذشتهٔ
گراتس
گرازنده
گرافیست
گرامیداشت
گراوور
گرایش
گربه
گرجستان
گرد
گردآوری
گرداب
گرداندن
گرداننده
گردشگران
گردشگری
گردن
گردنبند
گرده
گردهمایی
گردهمآیی
گردوغبار
گردونه
گرسنگی
گرفتاری
گرفتن
گرفتگی
گرم
گرما
گرمای
گرمخانه
گرنبر
گره
گرو
گروه
گروهک
گروهی
گروگان
گروگانگیر
گروگانگیری
گری
گریبان
گریبانگیر
گریز
گریزی
گریم
گریمی
گریه
گریپ
گز
گزارش
گزارشی
گزاره
گزاف
گزت
گزش
گزندگی
گزی
گزیدهٔ
گزینش
گستردگی
گسترش
گسل
گشایش
گشایشی
گشودن
گفتار
گفتن
گفته
گفتهٔ
گفتگو
گفتگوی
گفتگویی
گل
گلاب
گلایه
گلبرگ
گلبن
گلخانهای
گلدسته
گلدوزی
گلزاری
گلزنی
گلستان
گلشن
گله
گلوله
گلوی
گلپایگان
گلی
گلیم
گلآقا
گلمیخ
گمان
گمانه
گمانهٔ
گمانهزنی
گمرک
گناه
گناهی
گنبدکاووس
گنج
گنجاندن
گنجه
گنجهای
گنجی
گنجینه
گندم
گنگ
گواتر
گواتمالا
گوارش
گواه
گواهی
گوجه
گود
گور
گورباچف
گورستان
گورکانی
گورکانیان
گوری
گوزن
گوساله
گوستاروونوبوا
گوسفند
گوش
گوشت
گوشتِ
گوشزد
گوشزدکننده
گوشه
گوشهای
گوشهیی
گوشی
گول
گونه
گونهٔ
گونهای
گوها
گوهر
گوهرشادی
گوی
گویش
گوینده
گویی
گچ
گگونانی
گیاه
گیتی
گیر
گیرنده
گیسوان
گیلاس
گیلان
گینزا
گینس
گینه
یأس
یائسگی
یاد
یادآوری
یادداشت
یادداشتی
یادم
یادگار
یادگاری
یار
یارانه
یارانِ
یارای
یارگیری
یاری
یازده
یافت
یافتن
یافته
یاقوت
یاوهگویی
یتیم
یثرب
یحیی
یخچال
یداللهی
یزد
یزدانی
یزدگرد
یزدی
یزید
یزیدبنمعاویه
یش
یشم
یعقوب
یغما
یقه
یم
یمن
ین
یه
یهود
یهودی
یو
یورو
یوسفی
یوسفنیا
یوشکافیشر
یونان
یونانی
یونجه
یونس
یونسکو
یونیورس
یوکوهاما
یواسایتودی
یوسیالای
یک
یکایک
یکدیگر
یکسال
یکشنبه
یکصد
یکنواختی
یکه
یکهزار
یکپارچگی
یکی
یکپنجم
یکیک
یی
ای
""".split()) |
PySide/Shiboken | refs/heads/master | tests/samplebinding/modifiedvirtualmethods_test.py | 6 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of the Shiboken Python Bindings Generator project.
#
# Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
#
# Contact: PySide team <contact@pyside.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# version 2.1 as published by the Free Software Foundation. Please
# review the following information to ensure the GNU Lesser General
# Public License version 2.1 requirements will be met:
# http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
# #
# 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
'''Test cases for modified virtual methods.'''
import unittest
from sample import VirtualMethods, Str
class ExtendedVirtualMethods(VirtualMethods):
def __init__(self):
VirtualMethods.__init__(self)
self.name_called = False
self.sum0_called = False
self.sum1_called = False
self.sum2_called = False
self.sum3_called = False
self.sum4_called = False
self.sumThree_called = False
self.callMe_called = 0
self.multiplier = 12345
def sum0(self, a0, a1, a2):
self.sum0_called = True
return VirtualMethods.sumThree(self, a0, a1, a2) * self.multiplier
def sumThree(self, a0, a1, a2):
self.sumThree_called = True
return VirtualMethods.sumThree(self, a0, a1, a2) * self.multiplier
def sum1(self, a0, a1, a2):
self.sum1_called = True
return VirtualMethods.sum1(self, a0, a1, a2) * self.multiplier
def sum2(self, a0, a1):
self.sum2_called = True
return VirtualMethods.sum2(self, a0, a1) * self.multiplier
def sum3(self, a0, a1):
self.sum3_called = True
return VirtualMethods.sum3(self, a0, a1) * self.multiplier
def sum4(self, a0, a1):
self.sum4_called = True
return VirtualMethods.sum4(self, a0, a1) * self.multiplier
def name(self):
self.name_called = True
return Str('ExtendedVirtualMethods')
def callMe(self):
self.callMe_called += 1
def getMargins(self):
return tuple([m*2 for m in VirtualMethods.getMargins(self)])
class VirtualMethodsTest(unittest.TestCase):
'''Test case for modified virtual methods.'''
def setUp(self):
self.vm = VirtualMethods()
self.evm = ExtendedVirtualMethods()
def tearDown(self):
del self.vm
del self.evm
def testModifiedVirtualMethod0(self):
'''Renamed virtual method.'''
a0, a1, a2 = 2, 3, 5
result0 = self.vm.callSum0(a0, a1, a2)
result1 = self.vm.sumThree(a0, a1, a2)
self.assertEqual(result0, a0 + a1 + a2)
self.assertEqual(result0, result1)
self.assertRaises(AttributeError, getattr, self.vm, 'sum0')
def testReimplementedModifiedVirtualMethod0(self):
'''Override of a renamed virtual method.'''
a0, a1, a2 = 2, 3, 5
result0 = self.vm.callSum0(a0, a1, a2)
result1 = self.vm.sumThree(a0, a1, a2)
result2 = self.evm.callSum0(a0, a1, a2)
self.assertEqual(result0, result1)
self.assertEqual(result0 * self.evm.multiplier, result2)
self.assert_(self.evm.sumThree_called)
self.assertFalse(self.evm.sum0_called)
def testModifiedVirtualMethod1(self):
'''Virtual method with three arguments and the last one
changed to have the default value set to 1000.'''
a0, a1, a2 = 2, 3, 5
result0 = self.vm.sum1(a0, a1)
self.assertEqual(result0, a0 + a1 + 1000)
result1 = self.vm.sum1(a0, a1, a2)
result2 = self.vm.callSum1(a0, a1, a2)
self.assertEqual(result1, result2)
def testReimplementedModifiedVirtualMethod1(self):
'''Override of the virtual method with three arguments and
the last one changed to have the default value set to 1000.'''
a0, a1 = 2, 3
result0 = self.vm.sum1(a0, a1)
result1 = self.evm.callSum1(a0, a1, 1000)
self.assertEqual(result0 * self.evm.multiplier, result1)
self.assert_(self.evm.sum1_called)
def testModifiedVirtualMethod2(self):
'''Virtual method originally with three arguments, the last
one was removed and the default value set to 2000.'''
a0, a1 = 1, 2
result0 = self.vm.sum2(a0, a1)
self.assertEqual(result0, a0 + a1 + 2000)
result1 = self.vm.sum2(a0, a1)
result2 = self.vm.callSum2(a0, a1, 2000)
self.assertEqual(result1, result2)
self.assertRaises(TypeError, self.vm.sum2, 1, 2, 3)
def testReimplementedModifiedVirtualMethod2(self):
'''Override of the virtual method originally with three arguments,
the last one was removed and the default value set to 2000.'''
a0, a1 = 1, 2
ignored = 54321
result0 = self.vm.sum2(a0, a1)
result1 = self.evm.callSum2(a0, a1, ignored)
self.assertEqual(result0 * self.evm.multiplier, result1)
self.assert_(self.evm.sum2_called)
def testModifiedVirtualMethod3(self):
'''Virtual method originally with three arguments have the second
one removed and replaced by custom code that replaces it by the sum
of the first and the last arguments.'''
a0, a1 = 1, 2
result0 = self.vm.sum3(a0, a1)
self.assertEqual(result0, a0 + (a0 + a1) + a1)
result1 = self.vm.callSum3(a0, 10, a1)
self.assertNotEqual(result0, result1)
result2 = self.vm.callSum3(a0, a0 + a1, a1)
self.assertEqual(result0, result2)
self.assertRaises(TypeError, self.vm.sum3, 1, 2, 3)
def testReimplementedModifiedVirtualMethod3(self):
'''Override of the virtual method originally with three arguments
have the second one removed and replaced by custom code that
replaces it by the sum of the first and the last arguments.'''
a0, a1 = 1, 2
ignored = 54321
result0 = self.vm.sum3(a0, a1)
result1 = self.evm.callSum3(a0, ignored, a1)
self.assertEqual(result0 * self.evm.multiplier, result1)
self.assert_(self.evm.sum3_called)
def testModifiedVirtualMethod4(self):
'''Virtual method originally with three arguments, the
last one was removed and the default value set to 3000.'''
a0, a1 = 1, 2
default_value = 3000
result0 = self.vm.sum4(a0, a1)
self.assertEqual(result0, a0 + default_value + a1)
removed_arg_value = 100
result1 = self.vm.callSum4(a0, removed_arg_value, a1)
self.assertEqual(result1, a0 + removed_arg_value + a1)
self.assertRaises(TypeError, self.vm.sum4, 1, 2, 3)
def testReimplementedModifiedVirtualMethod4(self):
'''Override of the virtual method originally with three arguments,
the last one was removed and the default value set to 3000.
The method was modified with code injection on the binding override
(the one that receives calls from C++ with the original signature
and forwards it to Python overrides) that subtracts the value of the
second argument (removed in Python) from the value of the first
before sending them to Python.'''
a0, a1 = 1, 2
removed_arg_value = 2011
default_value = 3000
result = self.evm.callSum4(a0, removed_arg_value, a1)
self.assertEqual(result, (a0 - removed_arg_value + a1 + default_value) * self.evm.multiplier)
self.assert_(self.evm.sum4_called)
def testOverridenMethodResultModification(self):
'''Injected code modifies the result of a call to a virtual
method overridden in Python.'''
orig_name = self.vm.callName()
self.assertEqual(orig_name, 'VirtualMethods')
name = self.evm.callName()
self.assertEqual(name, 'PimpedExtendedVirtualMethods')
self.assertEqual(name, Str('PimpedExtendedVirtualMethods'))
self.assert_(self.evm.name_called)
def testInjectCodeCallsPythonVirtualMethodOverride(self):
'''When injected code calls the Python override by itself
no code for the method call should be generated.'''
self.evm.callCallMe()
self.assertEqual(self.evm.callMe_called, 1)
def testAllArgumentsRemoved(self):
values = (10, 20, 30, 40)
self.vm.setMargins(*values)
self.assertEquals(self.vm.getMargins(), values)
def testAllArgumentsRemovedCallVirtual(self):
values = (10, 20, 30, 40)
self.vm.setMargins(*values)
self.assertEquals(self.vm.callGetMargins(), values)
def testExtendedAllArgumentsRemoved(self):
values = (10, 20, 30, 40)
self.evm.setMargins(*values)
double = tuple([m*2 for m in values])
self.assertEquals(self.evm.getMargins(), double)
def testExtendedAllArgumentsRemovedCallVirtual(self):
values = (10, 20, 30, 40)
self.evm.setMargins(*values)
double = tuple([m*2 for m in values])
self.assertEquals(self.evm.callGetMargins(), double)
if __name__ == '__main__':
unittest.main()
|
GdZ/scriptfile | refs/heads/master | software/googleAppEngine/lib/python-gflags/tests/flags_modules_for_testing/module_baz.py | 139 | #!/usr/bin/env python
# Copyright (c) 2009, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Auxiliary module for testing gflags.py.
The purpose of this module is to test the behavior of flags that are defined
before main() executes.
"""
import gflags
FLAGS = gflags.FLAGS
gflags.DEFINE_boolean('tmod_baz_x', True, 'Boolean flag.')
|
Khanguy/ygo-ftk | refs/heads/master | script/c56673480.py | 1 | """Contract with Don Thousand"""
from script.card import Card
class c56673480(Card):
#TODO untested
def canActivate(self,game):
return not game.hasActivated(self)
def activate(self,game):
game.burn(1000)
def eff(self,game):
game.draw() |
itmard/pfont.ir | refs/heads/master | app/utilis/decorators.py | 3 | from functools import wraps
from flask import g, request, abort
def title(text):
def decorator_arg(f):
@wraps(f)
def decorator(*args, **kwargs):
g.title = text
return f(*args, **kwargs)
return decorator
return decorator_arg
def ajax_view(f):
"""
Response only to ajax request other wise abort 404
"""
@wraps(f)
def decorator(*args, **kwargs):
if request.headers.get('X_REQUESTED_WITH') == 'XMLHttpRequest':
return f(*args, **kwargs)
return abort(404)
return decorator |
jmerkow/VTK | refs/heads/master | ThirdParty/ZopeInterface/zope/interface/common/__init__.py | 438 | #
# This file is necessary to make this directory a package.
|
fanhero/thumbor | refs/heads/master | thumbor/filters/rotate.py | 7 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com thumbor@googlegroups.com
from thumbor.filters import BaseFilter, filter_method
class Filter(BaseFilter):
@filter_method(BaseFilter.Number)
def rotate(self, value):
if value % 90 == 0:
value = value % 360 # To optimize for engines
self.engine.rotate(value)
|
Milad-Rakhsha/chrono | refs/heads/develop | src/demos/python/core/demo_CH_functions.py | 4 | #------------------------------------------------------------------------------
# Name: using the ChFunction objects for specifying functions y=f(x)
# Purpose:
#
# Author: Radu Serban
#
# Created: 6/27/2020
# Copyright: (c) ProjectChrono 2019
#------------------------------------------------------------------------------
import pychrono as chrono
import os
import math
#------------------------------------------------------------------------------
# Define a custom function
class MyFunction(chrono.ChFunction):
def Get_y(self, x):
y = math.cos(math.pi * x)
return y
#------------------------------------------------------------------------------
print ('Demonstration of functions for y = f(x)')
# Create the output directory
out_dir = os.path.join(os.path.dirname(__file__), "Functions_demo")
if not os.path.exists(out_dir):
os.mkdir(out_dir)
print("Directory " , out_dir , " created ")
else:
print("Directory " , out_dir , " already exists")
# Ramp function
# -------------
f_ramp = chrono.ChFunction_Ramp()
f_ramp.Set_ang(0.1) # angular coefficient
f_ramp.Set_y0(0.1) # y value at x = 0
# Evaluate the function and its first derivative at a given value
y = f_ramp.Get_y(10)
yd = f_ramp.Get_y_dx(10)
print(' Ramp function f(10) = ', y, ', 1st derivative df/dx(10) = ', yd)
# Sine function
# -------------
f_sine = chrono.ChFunction_Sine()
f_sine.Set_amp(2) # amplitude
f_sine.Set_freq(1.5) # frequency
# Evaluate the function and its derivatives at 101 points in [0,2] and write to file
sine_file = open(out_dir + "/f_sine.out","w+")
for i in range(101):
x = i / 50.0
y = f_sine.Get_y(x)
yd = f_sine.Get_y_dx(x)
ydd = f_sine.Get_y_dxdx(x)
sine_file.write("%f %f %f %f\n" % (x, y, yd, ydd))
sine_file.close()
# Custom function
# ---------------
# Create a custom function for y = f(pi*x)
f_test = MyFunction()
# Evaluate the function and its derivatives at 101 points in [0,2] and write to file
test_file = open(out_dir + "/f_test.out", "w+")
for i in range(101):
x = i / 50.0
y = f_test.Get_y(x)
yd = f_test.Get_y_dx(x)
ydd = f_test.Get_y_dxdx(x)
test_file.write("%f %f %f %f\n" % (x, y, yd, ydd))
test_file.close()
# Function sequence
# -----------------
f_seq = chrono.ChFunction_Sequence()
f_const_acc1 = chrono.ChFunction_ConstAcc()
f_const_acc1.Set_end(0.5) # ramp length
f_const_acc1.Set_h(0.3) # ramp height
f_seq.InsertFunct(f_const_acc1, 0.5, 1, False, False, False, 0)
f_const = chrono.ChFunction_Const()
f_seq.InsertFunct(f_const, 0.4, 1, True, False, False, -1)
f_const_acc2 = chrono.ChFunction_ConstAcc()
f_const_acc2.Set_end(0.6) # ramp length
f_const_acc2.Set_av(0.3) # acceleration ends after 30% length
f_const_acc2.Set_aw(0.7) # deceleration starts after 70% length
f_const_acc2.Set_h(-0.2) # ramp height
f_seq.InsertFunct(f_const_acc2, 0.6, 1, True, False, False, -1)
f_seq.Setup();
# Evaluate the function and its derivatives at 101 points in [0,2] and write to file
seq_file = open(out_dir + "/f_seq.out", "w+")
for i in range(101):
x = i / 50.0
y = f_seq.Get_y(x)
yd = f_seq.Get_y_dx(x)
ydd = f_seq.Get_y_dxdx(x)
seq_file.write("%f %f %f %f\n" % (x, y, yd, ydd))
seq_file.close()
# Repeating sequence
# ------------------
f_part1 = chrono.ChFunction_Ramp()
f_part1.Set_ang(0.50)
f_part2 = chrono.ChFunction_Const()
f_part2.Set_yconst(1.0)
f_part3 = chrono.ChFunction_Ramp()
f_part3.Set_ang(-0.50)
f_seq = chrono.ChFunction_Sequence()
f_seq.InsertFunct(f_part1, 1.0, 1, True)
f_seq.InsertFunct(f_part2, 1.0, 1., True)
f_seq.InsertFunct(f_part3, 1.0, 1., True)
f_rep_seq = chrono.ChFunction_Repeat()
f_rep_seq.Set_fa(f_seq)
f_rep_seq.Set_window_length(3.0)
f_rep_seq.Set_window_start(0.0)
f_rep_seq.Set_window_phase(3.0)
# Evaluate the function and its derivatives at 101 points in [0,2] and write to file
rep_file = open(out_dir + "/f_rep.out", "w+")
for i in range(1001):
x = i / 50.0
y = f_rep_seq.Get_y(x)
yd = f_rep_seq.Get_y_dx(x)
ydd = f_rep_seq.Get_y_dxdx(x)
rep_file.write("%f %f %f %f\n" % (x, y, yd, ydd))
rep_file.close()
|
wreckJ/intellij-community | refs/heads/master | python/lib/Lib/site-packages/django/template/response.py | 71 | from django.http import HttpResponse
from django.template import loader, Context, RequestContext
class ContentNotRenderedError(Exception):
pass
class SimpleTemplateResponse(HttpResponse):
def __init__(self, template, context=None, mimetype=None, status=None,
content_type=None):
# It would seem obvious to call these next two members 'template' and
# 'context', but those names are reserved as part of the test Client API.
# To avoid the name collision, we use
# tricky-to-debug problems
self.template_name = template
self.context_data = context
# _is_rendered tracks whether the template and context has been baked into
# a final response.
self._is_rendered = False
# content argument doesn't make sense here because it will be replaced
# with rendered template so we always pass empty string in order to
# prevent errors and provide shorter signature.
super(SimpleTemplateResponse, self).__init__('', mimetype, status,
content_type)
def resolve_template(self, template):
"Accepts a template object, path-to-template or list of paths"
if isinstance(template, (list, tuple)):
return loader.select_template(template)
elif isinstance(template, basestring):
return loader.get_template(template)
else:
return template
def resolve_context(self, context):
"""Convert context data into a full Context object
(assuming it isn't already a Context object).
"""
if isinstance(context, Context):
return context
else:
return Context(context)
@property
def rendered_content(self):
"""Returns the freshly rendered content for the template and context
described by the TemplateResponse.
This *does not* set the final content of the response. To set the
response content, you must either call render(), or set the
content explicitly using the value of this property.
"""
template = self.resolve_template(self.template_name)
context = self.resolve_context(self.context_data)
content = template.render(context)
return content
def render(self):
"""Render (thereby finalizing) the content of the response.
If the content has already been rendered, this is a no-op.
Returns the baked response instance.
"""
if not self._is_rendered:
self._set_content(self.rendered_content)
return self
is_rendered = property(lambda self: self._is_rendered)
def __iter__(self):
if not self._is_rendered:
raise ContentNotRenderedError('The response content must be rendered before it can be iterated over.')
return super(SimpleTemplateResponse, self).__iter__()
def _get_content(self):
if not self._is_rendered:
raise ContentNotRenderedError('The response content must be rendered before it can be accessed.')
return super(SimpleTemplateResponse, self)._get_content()
def _set_content(self, value):
"Overrides rendered content, unless you later call render()"
super(SimpleTemplateResponse, self)._set_content(value)
self._is_rendered = True
content = property(_get_content, _set_content)
class TemplateResponse(SimpleTemplateResponse):
def __init__(self, request, template, context=None, mimetype=None,
status=None, content_type=None):
# self.request gets over-written by django.test.client.Client - and
# unlike context_data and template_name the _request should not
# be considered part of the public API.
self._request = request
super(TemplateResponse, self).__init__(
template, context, mimetype, status, content_type)
def resolve_context(self, context):
"""Convert context data into a full RequestContext object
(assuming it isn't already a Context object).
"""
if isinstance(context, Context):
return context
else:
return RequestContext(self._request, context)
|
MagicSolutions/django-form-designer | refs/heads/master | form_designer/contrib/exporters/__init__.py | 10 | from form_designer import settings
from form_designer.templatetags.friendly import friendly
from django.db.models import Count
from django.utils.translation import ugettext as _
from django.utils.encoding import smart_str
class ExporterBase(object):
def __init__(self, model):
self.model = model
@staticmethod
def is_enabled():
return True
@staticmethod
def export_format():
raise NotImplemented()
def init_writer(self):
raise NotImplemented()
def init_response(self):
raise NotImplemented()
def writerow(self, row):
raise NotImplemented()
def close(self):
pass
@classmethod
def export_view(cls, modeladmin, request, queryset):
return cls(modeladmin.model).export(request, queryset)
def export(self, request, queryset=None):
raise NotImplemented()
class FormLogExporterBase(ExporterBase):
def export(self, request, queryset=None):
self.init_response()
self.init_writer()
distinct_forms = queryset.aggregate(Count('form_definition', distinct=True))['form_definition__count']
include_created = settings.CSV_EXPORT_INCLUDE_CREATED
include_pk = settings.CSV_EXPORT_INCLUDE_PK
include_header = settings.CSV_EXPORT_INCLUDE_HEADER and distinct_forms == 1
include_form = settings.CSV_EXPORT_INCLUDE_FORM and distinct_forms > 1
if queryset.count():
fields = queryset[0].form_definition.get_field_dict()
if include_header:
header = []
if include_form:
header.append(_('Form'))
if include_created:
header.append(_('Created'))
if include_pk:
header.append(_('ID'))
# Form fields might have been changed and not match
# existing form logs anymore.
# Hence, use current form definition for header.
# for field in queryset[0].data:
# header.append(field['label'] if field['label'] else field['key'])
for field_name, field in fields.items():
header.append(field.label if field.label else field.key)
self.writerow([smart_str(cell, encoding=settings.CSV_EXPORT_ENCODING) for cell in header])
for entry in queryset:
row = []
if include_form:
row.append(entry.form_definition)
if include_created:
row.append(entry.created)
if include_pk:
row.append(entry.pk)
for item in entry.data:
value = friendly(item['value'], null_value=settings.CSV_EXPORT_NULL_VALUE)
value = smart_str(
value, encoding=settings.CSV_EXPORT_ENCODING)
row.append(value)
self.writerow(row)
self.close()
return self.response
|
williamvitorino3/pox-mesh | refs/heads/angler | pox/messenger/messenger_example.py | 1 | # Copyright 2011 James McCauley
#
# This file is part of POX.
#
# POX 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.
#
# POX 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 POX. If not, see <http://www.gnu.org/licenses/>.
from pox.core import core
from pox.messenger.messenger import *
class MessengerExample (object):
"""
Uma demonstração de mensageiro
A ideia é muito simples. Quando você cria um MessengerExample,
você diz a ele um nome que você está interessado dentro e
ele escuta core.messenger! MessageReceived. Se ele vê uma mensagem
com uma chave "Olá" onde o valor é o nome que você está interessado,
ele reivindica a conexão que a mensagem veio em e, em seguida,
escuta <thatConnection>! MessageReceived. Ele imprime mensagens sobre
essa conexão a partir de então. Se uma mensagem tem uma chave chamada
"bye" com o valor True, fecha a conexão.
Para experimentá-lo, faça o seguinte no interpretador POX:
POX> import pox.messenger.messenger_example
POX> pox.messenger.messenger_example.MessengerExample ("foo")
E então faça o seguinte a partir da linha de comando:
Bash $ echo '{"hello": "foo"} [1,2,3] "limpo"' | Nc localhost 7790
"""
"""
A demo of messenger.
The idea is pretty simple. When you create a MessengerExample, you tell it a
name you're interested in. It listens to core.messenger!MessageReceived. If
it sees a message with a "hello" key where the value is the name you're
interested in, it claims the connection that message came in on, and then
listens to <thatConnection>!MessageReceived. It prints out messages on that
connection from then on. If a message has a key named "bye" with the value
True, it closes the connection
To try it out, do the following in the POX interpreter:
POX> import pox.messenger.messenger_example
POX> pox.messenger.messenger_example.MessengerExample("foo")
And then do the following from the commandline:
bash$ echo '{"hello":"foo"}[1,2,3] "neat"' | nc localhost 7790
"""
def __init__ (self, targetName):
core.messenger.addListener(MessageReceived, self._handle_global_MessageReceived, weak=True)
self._targetName = targetName
def _handle_global_MessageReceived (self, event, msg):
"""
Trata as mensagens globais recebidas.
:param event: Evento que causa o lançamento do método.
:param msg: Mensagem recebida.
:return: Sem retorno.
"""
try:
n = msg['hello']
if n == self._targetName:
# It's for me!
event.con.read() # Consume the message
event.claim()
event.con.addListener(MessageReceived, self._handle_MessageReceived, weak=True)
print(self._targetName, "- started conversation with", event.con)
else:
print(self._targetName, "- ignoring", n)
except:
pass
def _handle_MessageReceived (self, event, msg):
"""
Trata as mensagens recebidas.
:param event: Evento que causa o lançamento do método.
:param msg: Mensagem recebida.
:return: Sem retorno.
"""
if event.con.isReadable():
r = event.con.read()
print(self._targetName, "-", r)
if type(r) is dict and r.get("bye",False):
print(self._targetName, "- GOODBYE!")
event.con.close()
if type(r) is dict and "echo" in r:
event.con.send({"echo": r["echo"]})
else:
print(self._targetName, "- conversation finished")
examples = {}
def launch(name = "example"):
"""
Adiciona valor no dicionário --examples
:param name: Posição da informação no dicionário de exemplos.
:return: Sem retorno.
"""
examples[name] = MessengerExample(name)
|
aleksandra-tarkowska/django | refs/heads/master | django/contrib/sites/tests.py | 19 | from __future__ import unicode_literals
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.http import HttpRequest
from django.test import TestCase, modify_settings, override_settings
from .middleware import CurrentSiteMiddleware
from .models import Site
from .requests import RequestSite
from .shortcuts import get_current_site
@modify_settings(INSTALLED_APPS={'append': 'django.contrib.sites'})
class SitesFrameworkTests(TestCase):
def setUp(self):
Site(id=settings.SITE_ID, domain="example.com", name="example.com").save()
def test_save_another(self):
# Regression for #17415
# On some backends the sequence needs reset after save with explicit ID.
# Test that there is no sequence collisions by saving another site.
Site(domain="example2.com", name="example2.com").save()
def test_site_manager(self):
# Make sure that get_current() does not return a deleted Site object.
s = Site.objects.get_current()
self.assertIsInstance(s, Site)
s.delete()
self.assertRaises(ObjectDoesNotExist, Site.objects.get_current)
def test_site_cache(self):
# After updating a Site object (e.g. via the admin), we shouldn't return a
# bogus value from the SITE_CACHE.
site = Site.objects.get_current()
self.assertEqual("example.com", site.name)
s2 = Site.objects.get(id=settings.SITE_ID)
s2.name = "Example site"
s2.save()
site = Site.objects.get_current()
self.assertEqual("Example site", site.name)
def test_delete_all_sites_clears_cache(self):
# When all site objects are deleted the cache should also
# be cleared and get_current() should raise a DoesNotExist.
self.assertIsInstance(Site.objects.get_current(), Site)
Site.objects.all().delete()
self.assertRaises(Site.DoesNotExist, Site.objects.get_current)
@override_settings(ALLOWED_HOSTS=['example.com'])
def test_get_current_site(self):
# Test that the correct Site object is returned
request = HttpRequest()
request.META = {
"SERVER_NAME": "example.com",
"SERVER_PORT": "80",
}
site = get_current_site(request)
self.assertIsInstance(site, Site)
self.assertEqual(site.id, settings.SITE_ID)
# Test that an exception is raised if the sites framework is installed
# but there is no matching Site
site.delete()
self.assertRaises(ObjectDoesNotExist, get_current_site, request)
# A RequestSite is returned if the sites framework is not installed
with self.modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'}):
site = get_current_site(request)
self.assertIsInstance(site, RequestSite)
self.assertEqual(site.name, "example.com")
def test_domain_name_with_whitespaces(self):
# Regression for #17320
# Domain names are not allowed contain whitespace characters
site = Site(name="test name", domain="test test")
self.assertRaises(ValidationError, site.full_clean)
site.domain = "test\ttest"
self.assertRaises(ValidationError, site.full_clean)
site.domain = "test\ntest"
self.assertRaises(ValidationError, site.full_clean)
class MiddlewareTest(TestCase):
def test_request(self):
""" Makes sure that the request has correct `site` attribute. """
middleware = CurrentSiteMiddleware()
request = HttpRequest()
middleware.process_request(request)
self.assertEqual(request.site.id, settings.SITE_ID)
|
LCfP/abm | refs/heads/dev | comparablemodels/GHW2008/ghwmodel.py | 2 | import numpy as np
import random
def ghw_model(seed, simulation_time, init_backward_simulated_time, chaos, risk_av_variance, dividends,
discount_rate, intensity_of_choice, fundamentalist_adaptive_parameter, chartist_adaptive_parameter,
bubble_sensitivity, fitness_memory_strenght, risk_adjustment, noise_std, init_price_dev_fundament,
init_type2_agents, init_type2_holdings):
"""
:param seed: integer
used to set the pseudo number generator for experiment reproduction
:param simulation_time: integer
Amount of periods over which the simulation takes place
:param init_backward_simulated_time: integer
Amount of pre-simulated periods
:param chaos:
:param risk_av_variance:
:param dividends:
:param discount_rate:
:param intensity_of_choice:
:param fundamentalist_adaptive_parameter:
:param chartist_adaptive_parameter:
:param bubble_sensitivity:
:param fitness_memory_strenght:
:param risk_adjustment:
:param noise_std:
:param init_price_dev_fundament:
:param init_type2_agents:
:param init_type2_holdings:
:return:
"""
random.seed(seed)
np.random.seed(seed)
"""
Set-up
"""
fundamental_price = dividends / discount_rate
fraction_type2 = [init_type2_agents for x in range(init_backward_simulated_time)]
returns = [0 for x in range(init_backward_simulated_time)]
price_deviation_from_fundamental = [init_price_dev_fundament for x in range(init_backward_simulated_time)]
accumulated_fitness1 = [0 for x in range(init_backward_simulated_time - 1)]
accumulated_fitness2 = [0 for x in range(init_backward_simulated_time - 1)]
share_holdings_type1 = [(1 - init_type2_holdings) for x in range(init_backward_simulated_time)]
share_holdings_type2 = [init_type2_holdings for x in range(init_backward_simulated_time)]
normalized_acc_fitness = [0 for x in range(init_backward_simulated_time)]
# TODO make this a function?
pricing_noise = noise_std * np.random.randn(simulation_time)
price = [fundamental_price + x for x in price_deviation_from_fundamental]
"""
Simulation
Process overview and scheduling
1. Update profits
2. Caclulate fitness
3. Switch strategies
4. Price forecasting
5. Price formation
6. Portfolio decisions
"""
for day in range(simulation_time):
# 1 update profits
profits_type1 = returns[-1] * share_holdings_type1[-1] - \
risk_adjustment * 0.5 * risk_av_variance * share_holdings_type1[-1]**2
profits_type2 = returns[-1] * share_holdings_type2[-1] - \
risk_adjustment * 0.5 * risk_av_variance * share_holdings_type2[-1]**2
# 2 Calculate fitness
accumulated_fitness1.append(profits_type1 + fitness_memory_strenght * accumulated_fitness1[-1])
accumulated_fitness2.append(profits_type2 + fitness_memory_strenght * accumulated_fitness2[-1])
normalized_fitness = np.exp(intensity_of_choice * accumulated_fitness1[-1]) + np.exp(intensity_of_choice * accumulated_fitness2[-1])
normalized_acc_fitness.append(normalized_fitness)
performance_measure = np.exp(intensity_of_choice * accumulated_fitness2[-1]) / normalized_fitness
if np.isnan(performance_measure):
performance_measure = 0.5
# 3 Switch strategies
fraction_type2.append(performance_measure * np.exp(-(price_deviation_from_fundamental[-1])** 2 / bubble_sensitivity))
# 4 Price forecasting
type1_forecast_price = fundamentalist_adaptive_parameter * (price_deviation_from_fundamental[-1])
type2_forecast_price = price_deviation_from_fundamental[-1] + \
chartist_adaptive_parameter * \
(price_deviation_from_fundamental[-1] - price_deviation_from_fundamental[-2])
# 5 Price formation
price_deviation_from_fundamental.append(1/(1+discount_rate) * (((1-fraction_type2[-1]) * type1_forecast_price +
fraction_type2[-1] * type2_forecast_price)
+ pricing_noise[day]))
price.append(price_deviation_from_fundamental[-1] + fundamental_price)
returns.append(price_deviation_from_fundamental[-1] - price_deviation_from_fundamental[-2])
# 6 Portfolio decision
share_holdings_type1.append((type1_forecast_price - price_deviation_from_fundamental[-1]) / risk_av_variance)
share_holdings_type2.append((type2_forecast_price - price_deviation_from_fundamental[-1]) / risk_av_variance)
return price_deviation_from_fundamental, price, returns, fraction_type2
|
knowledgecommonsdc/kcdc3 | refs/heads/master | kcdc3/apps/squirrel/migrations/0001_initial.py | 1 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Meeting'
db.create_table(u'squirrel_meeting', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('title', self.gf('django.db.models.fields.CharField')(max_length=200)),
('slug', self.gf('django.db.models.fields.SlugField')(unique=True, max_length=50)),
('status', self.gf('django.db.models.fields.CharField')(default='PUBLISHED', max_length=9)),
('date', self.gf('django.db.models.fields.DateTimeField')()),
('end_time', self.gf('django.db.models.fields.TimeField')(null=True, blank=True)),
('location', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='squirrel_location', null=True, on_delete=models.SET_NULL, to=orm['classes.Location'])),
('description', self.gf('django.db.models.fields.TextField')(blank=True)),
))
db.send_create_signal(u'squirrel', ['Meeting'])
# Adding model 'Meeting_Registration'
db.create_table(u'squirrel_meeting_registration', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='squirrel_user', null=True, to=orm['auth.User'])),
('meeting', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['squirrel.Meeting'], null=True)),
('date_registered', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
('cancelled', self.gf('django.db.models.fields.BooleanField')(default=False)),
('note', self.gf('django.db.models.fields.TextField')(blank=True)),
))
db.send_create_signal(u'squirrel', ['Meeting_Registration'])
def backwards(self, orm):
# Deleting model 'Meeting'
db.delete_table(u'squirrel_meeting')
# Deleting model 'Meeting_Registration'
db.delete_table(u'squirrel_meeting_registration')
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'classes.location': {
'Meta': {'object_name': 'Location'},
'access': ('django.db.models.fields.CharField', [], {'default': "'SEMIPUBLIC'", 'max_length': '11'}),
'address1': ('django.db.models.fields.CharField', [], {'max_length': '60', 'blank': 'True'}),
'address2': ('django.db.models.fields.CharField', [], {'max_length': '60', 'blank': 'True'}),
'city': ('django.db.models.fields.CharField', [], {'default': "'Washington'", 'max_length': '60', 'blank': 'True'}),
'hint': ('django.db.models.fields.CharField', [], {'max_length': '300', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'lat': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'lng': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'neighborhood': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'show_exact': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'state': ('django.db.models.fields.CharField', [], {'default': "'DC'", 'max_length': '2', 'blank': 'True'}),
'zip': ('django.db.models.fields.CharField', [], {'max_length': '5', 'blank': 'True'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'squirrel.meeting': {
'Meta': {'ordering': "['-date']", 'object_name': 'Meeting'},
'date': ('django.db.models.fields.DateTimeField', [], {}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'end_time': ('django.db.models.fields.TimeField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'squirrel_location'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['classes.Location']"}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}),
'status': ('django.db.models.fields.CharField', [], {'default': "'PUBLISHED'", 'max_length': '9'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
u'squirrel.meeting_registration': {
'Meta': {'ordering': "['date_registered']", 'object_name': 'Meeting_Registration'},
'cancelled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'date_registered': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'meeting': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['squirrel.Meeting']", 'null': 'True'}),
'note': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'squirrel_user'", 'null': 'True', 'to': u"orm['auth.User']"})
}
}
complete_apps = ['squirrel'] |
GuillaumeDerval/INGInious | refs/heads/master | frontend/plugins/task_file_managers/json_manager.py | 1 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2014-2015 Université Catholique de Louvain.
#
# This file is part of INGInious.
#
# INGInious 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.
#
# INGInious 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 INGInious. If not, see <http://www.gnu.org/licenses/>.
""" JSON task file manager. """
import collections
import json
from common.task_file_managers.abstract_manager import AbstractTaskFileManager
class TaskJSONFileManager(AbstractTaskFileManager):
""" Read and write task descriptions in JSON """
def _get_content(self, content):
return json.loads(content, object_pairs_hook=collections.OrderedDict)
@classmethod
def get_ext(cls):
return "json"
def _generate_content(self, data):
return json.dumps(data, sort_keys=False, indent=4, separators=(',', ': '))
def init(plugin_manager, _):
"""
Init the plugin. Configuration:
::
{
"plugin_module": "frontend.plugins.task_files_manager.json_manager"
}
"""
plugin_manager.add_task_file_manager(TaskJSONFileManager)
|
springdeveloper/roflcopters | refs/heads/master | src/webapp/fckeditor/editor/filemanager/connectors/py/connector.py | 92 | #!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorConnector( FCKeditorConnectorBase,
GetFoldersCommandMixin,
GetFoldersAndFilesCommandMixin,
CreateFolderCommandMixin,
UploadFileCommandMixin,
BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ):
"The Standard connector class."
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
s = ""
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.")
# Make sure we have valid inputs
for key in ("Command","Type","CurrentFolder"):
if not self.request.has_key (key):
return
# Get command, resource type and current folder
command = self.request.get("Command")
resourceType = self.request.get("Type")
currentFolder = getCurrentFolder(self.request.get("CurrentFolder"))
# Check for invalid paths
if currentFolder is None:
return self.sendError(102, "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendError( 1, 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendError( 1, 'Invalid type specified' )
# Setup paths
if command == "QuickUpload":
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
else:
self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType]
self.webUserFilesFolder = Config.FileTypesPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
if (command == "FileUpload"):
return self.uploadFile(resourceType, currentFolder)
# Create Url
url = combinePaths( self.webUserFilesFolder, currentFolder )
# Begin XML
s += self.createXmlHeader(command, resourceType, currentFolder, url)
# Execute the command
selector = {"GetFolders": self.getFolders,
"GetFoldersAndFiles": self.getFoldersAndFiles,
"CreateFolder": self.createFolder,
}
s += selector[command](resourceType, currentFolder)
s += self.createXmlFooter()
return s
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorConnector()
data = conn.doResponse()
for header in conn.headers:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
|
enkripsi/gyp | refs/heads/master | test/make_global_settings/env-wrapper/gyptest-wrapper.py | 229 | #!/usr/bin/env python
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies *_wrapper in environment.
"""
import os
import sys
import TestGyp
test_format = ['ninja']
os.environ['CC_wrapper'] = 'distcc'
os.environ['LINK_wrapper'] = 'distlink'
os.environ['CC.host_wrapper'] = 'ccache'
test = TestGyp.TestGyp(formats=test_format)
old_env = dict(os.environ)
os.environ['GYP_CROSSCOMPILE'] = '1'
test.run_gyp('wrapper.gyp')
os.environ.clear()
os.environ.update(old_env)
if test.format == 'ninja':
cc_expected = ('cc = ' + os.path.join('..', '..', 'distcc') + ' ' +
os.path.join('..', '..', 'clang'))
cc_host_expected = ('cc_host = ' + os.path.join('..', '..', 'ccache') + ' ' +
os.path.join('..', '..', 'clang'))
ld_expected = 'ld = ../../distlink $cc'
if sys.platform != 'win32':
ldxx_expected = 'ldxx = ../../distlink $cxx'
if sys.platform == 'win32':
ld_expected = 'link.exe'
test.must_contain('out/Default/build.ninja', cc_expected)
test.must_contain('out/Default/build.ninja', cc_host_expected)
test.must_contain('out/Default/build.ninja', ld_expected)
if sys.platform != 'win32':
test.must_contain('out/Default/build.ninja', ldxx_expected)
test.pass_test()
|
andrewwong97/path-hero | refs/heads/master | pathhero/main/forms.py | 1 | from __future__ import unicode_literals
from django import forms
from .models import Building
class LocationForm(forms.Form):
start = forms.ModelChoiceField(queryset=Building.objects.order_by('name'), label='Start')
end = forms.ModelChoiceField(queryset=Building.objects.order_by('name'), label='End')
class MidpointForm(forms.Form):
mid = forms.ModelChoiceField(queryset=Building.objects.order_by('name'), label='Mid', required=False)
|
xianjunzhengbackup/Cloud-Native-Python | refs/heads/master | env/lib/python3.6/site-packages/werkzeug/contrib/fixers.py | 104 | # -*- coding: utf-8 -*-
"""
werkzeug.contrib.fixers
~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 0.5
This module includes various helpers that fix bugs in web servers. They may
be necessary for some versions of a buggy web server but not others. We try
to stay updated with the status of the bugs as good as possible but you have
to make sure whether they fix the problem you encounter.
If you notice bugs in webservers not fixed in this module consider
contributing a patch.
:copyright: Copyright 2009 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
try:
from urllib import unquote
except ImportError:
from urllib.parse import unquote
from werkzeug.http import parse_options_header, parse_cache_control_header, \
parse_set_header
from werkzeug.useragents import UserAgent
from werkzeug.datastructures import Headers, ResponseCacheControl
class CGIRootFix(object):
"""Wrap the application in this middleware if you are using FastCGI or CGI
and you have problems with your app root being set to the cgi script's path
instead of the path users are going to visit
.. versionchanged:: 0.9
Added `app_root` parameter and renamed from `LighttpdCGIRootFix`.
:param app: the WSGI application
:param app_root: Defaulting to ``'/'``, you can set this to something else
if your app is mounted somewhere else.
"""
def __init__(self, app, app_root='/'):
self.app = app
self.app_root = app_root
def __call__(self, environ, start_response):
# only set PATH_INFO for older versions of Lighty or if no
# server software is provided. That's because the test was
# added in newer Werkzeug versions and we don't want to break
# people's code if they are using this fixer in a test that
# does not set the SERVER_SOFTWARE key.
if 'SERVER_SOFTWARE' not in environ or \
environ['SERVER_SOFTWARE'] < 'lighttpd/1.4.28':
environ['PATH_INFO'] = environ.get('SCRIPT_NAME', '') + \
environ.get('PATH_INFO', '')
environ['SCRIPT_NAME'] = self.app_root.strip('/')
return self.app(environ, start_response)
# backwards compatibility
LighttpdCGIRootFix = CGIRootFix
class PathInfoFromRequestUriFix(object):
"""On windows environment variables are limited to the system charset
which makes it impossible to store the `PATH_INFO` variable in the
environment without loss of information on some systems.
This is for example a problem for CGI scripts on a Windows Apache.
This fixer works by recreating the `PATH_INFO` from `REQUEST_URI`,
`REQUEST_URL`, or `UNENCODED_URL` (whatever is available). Thus the
fix can only be applied if the webserver supports either of these
variables.
:param app: the WSGI application
"""
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
for key in 'REQUEST_URL', 'REQUEST_URI', 'UNENCODED_URL':
if key not in environ:
continue
request_uri = unquote(environ[key])
script_name = unquote(environ.get('SCRIPT_NAME', ''))
if request_uri.startswith(script_name):
environ['PATH_INFO'] = request_uri[len(script_name):] \
.split('?', 1)[0]
break
return self.app(environ, start_response)
class ProxyFix(object):
"""This middleware can be applied to add HTTP proxy support to an
application that was not designed with HTTP proxies in mind. It
sets `REMOTE_ADDR`, `HTTP_HOST` from `X-Forwarded` headers. While
Werkzeug-based applications already can use
:py:func:`werkzeug.wsgi.get_host` to retrieve the current host even if
behind proxy setups, this middleware can be used for applications which
access the WSGI environment directly.
If you have more than one proxy server in front of your app, set
`num_proxies` accordingly.
Do not use this middleware in non-proxy setups for security reasons.
The original values of `REMOTE_ADDR` and `HTTP_HOST` are stored in
the WSGI environment as `werkzeug.proxy_fix.orig_remote_addr` and
`werkzeug.proxy_fix.orig_http_host`.
:param app: the WSGI application
:param num_proxies: the number of proxy servers in front of the app.
"""
def __init__(self, app, num_proxies=1):
self.app = app
self.num_proxies = num_proxies
def get_remote_addr(self, forwarded_for):
"""Selects the new remote addr from the given list of ips in
X-Forwarded-For. By default it picks the one that the `num_proxies`
proxy server provides. Before 0.9 it would always pick the first.
.. versionadded:: 0.8
"""
if len(forwarded_for) >= self.num_proxies:
return forwarded_for[-self.num_proxies]
def __call__(self, environ, start_response):
getter = environ.get
forwarded_proto = getter('HTTP_X_FORWARDED_PROTO', '')
forwarded_for = getter('HTTP_X_FORWARDED_FOR', '').split(',')
forwarded_host = getter('HTTP_X_FORWARDED_HOST', '')
environ.update({
'werkzeug.proxy_fix.orig_wsgi_url_scheme': getter('wsgi.url_scheme'),
'werkzeug.proxy_fix.orig_remote_addr': getter('REMOTE_ADDR'),
'werkzeug.proxy_fix.orig_http_host': getter('HTTP_HOST')
})
forwarded_for = [x for x in [x.strip() for x in forwarded_for] if x]
remote_addr = self.get_remote_addr(forwarded_for)
if remote_addr is not None:
environ['REMOTE_ADDR'] = remote_addr
if forwarded_host:
environ['HTTP_HOST'] = forwarded_host
if forwarded_proto:
environ['wsgi.url_scheme'] = forwarded_proto
return self.app(environ, start_response)
class HeaderRewriterFix(object):
"""This middleware can remove response headers and add others. This
is for example useful to remove the `Date` header from responses if you
are using a server that adds that header, no matter if it's present or
not or to add `X-Powered-By` headers::
app = HeaderRewriterFix(app, remove_headers=['Date'],
add_headers=[('X-Powered-By', 'WSGI')])
:param app: the WSGI application
:param remove_headers: a sequence of header keys that should be
removed.
:param add_headers: a sequence of ``(key, value)`` tuples that should
be added.
"""
def __init__(self, app, remove_headers=None, add_headers=None):
self.app = app
self.remove_headers = set(x.lower() for x in (remove_headers or ()))
self.add_headers = list(add_headers or ())
def __call__(self, environ, start_response):
def rewriting_start_response(status, headers, exc_info=None):
new_headers = []
for key, value in headers:
if key.lower() not in self.remove_headers:
new_headers.append((key, value))
new_headers += self.add_headers
return start_response(status, new_headers, exc_info)
return self.app(environ, rewriting_start_response)
class InternetExplorerFix(object):
"""This middleware fixes a couple of bugs with Microsoft Internet
Explorer. Currently the following fixes are applied:
- removing of `Vary` headers for unsupported mimetypes which
causes troubles with caching. Can be disabled by passing
``fix_vary=False`` to the constructor.
see: http://support.microsoft.com/kb/824847/en-us
- removes offending headers to work around caching bugs in
Internet Explorer if `Content-Disposition` is set. Can be
disabled by passing ``fix_attach=False`` to the constructor.
If it does not detect affected Internet Explorer versions it won't touch
the request / response.
"""
# This code was inspired by Django fixers for the same bugs. The
# fix_vary and fix_attach fixers were originally implemented in Django
# by Michael Axiak and is available as part of the Django project:
# http://code.djangoproject.com/ticket/4148
def __init__(self, app, fix_vary=True, fix_attach=True):
self.app = app
self.fix_vary = fix_vary
self.fix_attach = fix_attach
def fix_headers(self, environ, headers, status=None):
if self.fix_vary:
header = headers.get('content-type', '')
mimetype, options = parse_options_header(header)
if mimetype not in ('text/html', 'text/plain', 'text/sgml'):
headers.pop('vary', None)
if self.fix_attach and 'content-disposition' in headers:
pragma = parse_set_header(headers.get('pragma', ''))
pragma.discard('no-cache')
header = pragma.to_header()
if not header:
headers.pop('pragma', '')
else:
headers['Pragma'] = header
header = headers.get('cache-control', '')
if header:
cc = parse_cache_control_header(header,
cls=ResponseCacheControl)
cc.no_cache = None
cc.no_store = False
header = cc.to_header()
if not header:
headers.pop('cache-control', '')
else:
headers['Cache-Control'] = header
def run_fixed(self, environ, start_response):
def fixing_start_response(status, headers, exc_info=None):
headers = Headers(headers)
self.fix_headers(environ, headers, status)
return start_response(status, headers.to_wsgi_list(), exc_info)
return self.app(environ, fixing_start_response)
def __call__(self, environ, start_response):
ua = UserAgent(environ)
if ua.browser != 'msie':
return self.app(environ, start_response)
return self.run_fixed(environ, start_response)
|
zstackio/zstack-woodpecker | refs/heads/master | integrationtest/vm/multihosts/volumes/paths/path89.py | 2 | import zstackwoodpecker.test_state as ts_header
TestAction = ts_header.TestAction
def path():
return dict(initial_formation="template2",\
path_list=[[TestAction.create_volume, "volume1", "=scsi,shareable"], \
[TestAction.attach_volume, "vm1", "volume1"], \
[TestAction.create_volume, "volume2", "=scsi,shareable"], \
[TestAction.attach_volume, "vm1", "volume2"], \
[TestAction.create_volume, "volume3", "=scsi,shareable"], \
[TestAction.attach_volume, "vm1", "volume3"], \
[TestAction.create_volume, "volume4", "=scsi,shareable"], \
[TestAction.attach_volume, "vm1", "volume4"], \
[TestAction.create_volume, "volume5", "=scsi,shareable"], \
[TestAction.attach_volume, "vm1", "volume5"], \
[TestAction.create_volume, "volume6", "=scsi,shareable"], \
[TestAction.attach_volume, "vm1", "volume6"], \
[TestAction.create_volume, "volume7", "=scsi,shareable"], \
[TestAction.attach_volume, "vm1", "volume7"], \
[TestAction.create_volume, "volume8", "=scsi,shareable"], \
[TestAction.attach_volume, "vm1", "volume8"], \
[TestAction.detach_volume, "volume1", "vm1"], \
[TestAction.detach_volume, "volume2", "vm1"], \
[TestAction.detach_volume, "volume3", "vm1"], \
[TestAction.detach_volume, "volume4", "vm1"], \
[TestAction.detach_volume, "volume5", "vm1"], \
[TestAction.detach_volume, "volume6", "vm1"], \
[TestAction.detach_volume, "volume7", "vm1"], \
[TestAction.detach_volume, "volume8", "vm1"], \
[TestAction.clone_vm, "vm1", "vm2", "full"], \
[TestAction.stop_vm, "vm2"], \
[TestAction.ps_migrate_volume, "vm2-root"], \
[TestAction.resize_data_volume, "volume1", 5*1024*1024], \
[TestAction.delete_volume, "volume1"], \
[TestAction.migrate_vm, "vm1"], \
[TestAction.migrate_vm, "vm1"], \
[TestAction.resize_data_volume, "volume2", 5*1024*1024], \
[TestAction.delete_volume, "volume2"], \
[TestAction.stop_vm, "vm1"], \
[TestAction.reinit_vm, "vm1"], \
[TestAction.create_volume_snapshot, "volume3", 'snapshot1'], \
[TestAction.start_vm, "vm1"], \
[TestAction.reboot_vm, "vm1"]])
|
RichardLitt/wyrd-django-dev | refs/heads/master | django/db/backends/oracle/client.py | 645 | import os
import sys
from django.db.backends import BaseDatabaseClient
class DatabaseClient(BaseDatabaseClient):
executable_name = 'sqlplus'
def runshell(self):
conn_string = self.connection._connect_string()
args = [self.executable_name, "-L", conn_string]
if os.name == 'nt':
sys.exit(os.system(" ".join(args)))
else:
os.execvp(self.executable_name, args)
|
cryptostorm/namecoin | refs/heads/namecoinq | client/jsonrpc/__init__.py | 67 |
"""
Copyright (c) 2007 Jan-Klaas Kollhof
This file is part of jsonrpc.
jsonrpc 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 software 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 software; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""
from jsonrpc.json import loads, dumps, JSONEncodeException, JSONDecodeException
from jsonrpc.proxy import ServiceProxy, JSONRPCException
from jsonrpc.serviceHandler import ServiceMethod, ServiceHandler, ServiceMethodNotFound, ServiceException
from jsonrpc.cgiwrapper import handleCGI
from jsonrpc.modpywrapper import handler |
nhippenmeyer/django | refs/heads/master | django/db/models/aggregates.py | 161 | """
Classes to represent the definitions of aggregate functions.
"""
from django.core.exceptions import FieldError
from django.db.models.expressions import Func, Value
from django.db.models.fields import FloatField, IntegerField
__all__ = [
'Aggregate', 'Avg', 'Count', 'Max', 'Min', 'StdDev', 'Sum', 'Variance',
]
class Aggregate(Func):
contains_aggregate = True
name = None
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
# Aggregates are not allowed in UPDATE queries, so ignore for_save
c = super(Aggregate, self).resolve_expression(query, allow_joins, reuse, summarize)
if not summarize:
expressions = c.get_source_expressions()
for index, expr in enumerate(expressions):
if expr.contains_aggregate:
before_resolved = self.get_source_expressions()[index]
name = before_resolved.name if hasattr(before_resolved, 'name') else repr(before_resolved)
raise FieldError("Cannot compute %s('%s'): '%s' is an aggregate" % (c.name, name, name))
c._patch_aggregate(query) # backward-compatibility support
return c
@property
def input_field(self):
return self.source_expressions[0]
@property
def default_alias(self):
expressions = self.get_source_expressions()
if len(expressions) == 1 and hasattr(expressions[0], 'name'):
return '%s__%s' % (expressions[0].name, self.name.lower())
raise TypeError("Complex expressions require an alias")
def get_group_by_cols(self):
return []
def _patch_aggregate(self, query):
"""
Helper method for patching 3rd party aggregates that do not yet support
the new way of subclassing. This method will be removed in Django 1.10.
add_to_query(query, alias, col, source, is_summary) will be defined on
legacy aggregates which, in turn, instantiates the SQL implementation of
the aggregate. In all the cases found, the general implementation of
add_to_query looks like:
def add_to_query(self, query, alias, col, source, is_summary):
klass = SQLImplementationAggregate
aggregate = klass(col, source=source, is_summary=is_summary, **self.extra)
query.aggregates[alias] = aggregate
By supplying a known alias, we can get the SQLAggregate out of the
aggregates dict, and use the sql_function and sql_template attributes
to patch *this* aggregate.
"""
if not hasattr(self, 'add_to_query') or self.function is not None:
return
placeholder_alias = "_XXXXXXXX_"
self.add_to_query(query, placeholder_alias, None, None, None)
sql_aggregate = query.aggregates.pop(placeholder_alias)
if 'sql_function' not in self.extra and hasattr(sql_aggregate, 'sql_function'):
self.extra['function'] = sql_aggregate.sql_function
if hasattr(sql_aggregate, 'sql_template'):
self.extra['template'] = sql_aggregate.sql_template
class Avg(Aggregate):
function = 'AVG'
name = 'Avg'
def __init__(self, expression, **extra):
output_field = extra.pop('output_field', FloatField())
super(Avg, self).__init__(expression, output_field=output_field, **extra)
def as_oracle(self, compiler, connection):
if self.output_field.get_internal_type() == 'DurationField':
expression = self.get_source_expressions()[0]
from django.db.backends.oracle.functions import IntervalToSeconds, SecondsToInterval
return compiler.compile(
SecondsToInterval(Avg(IntervalToSeconds(expression)))
)
return super(Avg, self).as_sql(compiler, connection)
class Count(Aggregate):
function = 'COUNT'
name = 'Count'
template = '%(function)s(%(distinct)s%(expressions)s)'
def __init__(self, expression, distinct=False, **extra):
if expression == '*':
expression = Value(expression)
super(Count, self).__init__(
expression, distinct='DISTINCT ' if distinct else '', output_field=IntegerField(), **extra)
def __repr__(self):
return "{}({}, distinct={})".format(
self.__class__.__name__,
self.arg_joiner.join(str(arg) for arg in self.source_expressions),
'False' if self.extra['distinct'] == '' else 'True',
)
def convert_value(self, value, expression, connection, context):
if value is None:
return 0
return int(value)
class Max(Aggregate):
function = 'MAX'
name = 'Max'
class Min(Aggregate):
function = 'MIN'
name = 'Min'
class StdDev(Aggregate):
name = 'StdDev'
def __init__(self, expression, sample=False, **extra):
self.function = 'STDDEV_SAMP' if sample else 'STDDEV_POP'
super(StdDev, self).__init__(expression, output_field=FloatField(), **extra)
def __repr__(self):
return "{}({}, sample={})".format(
self.__class__.__name__,
self.arg_joiner.join(str(arg) for arg in self.source_expressions),
'False' if self.function == 'STDDEV_POP' else 'True',
)
def convert_value(self, value, expression, connection, context):
if value is None:
return value
return float(value)
class Sum(Aggregate):
function = 'SUM'
name = 'Sum'
def as_oracle(self, compiler, connection):
if self.output_field.get_internal_type() == 'DurationField':
expression = self.get_source_expressions()[0]
from django.db.backends.oracle.functions import IntervalToSeconds, SecondsToInterval
return compiler.compile(
SecondsToInterval(Sum(IntervalToSeconds(expression)))
)
return super(Sum, self).as_sql(compiler, connection)
class Variance(Aggregate):
name = 'Variance'
def __init__(self, expression, sample=False, **extra):
self.function = 'VAR_SAMP' if sample else 'VAR_POP'
super(Variance, self).__init__(expression, output_field=FloatField(), **extra)
def __repr__(self):
return "{}({}, sample={})".format(
self.__class__.__name__,
self.arg_joiner.join(str(arg) for arg in self.source_expressions),
'False' if self.function == 'VAR_POP' else 'True',
)
def convert_value(self, value, expression, connection, context):
if value is None:
return value
return float(value)
|
openstack/glance | refs/heads/master | glance/common/exception.py | 1 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""Glance exception subclasses"""
import six
import six.moves.urllib.parse as urlparse
from glance.i18n import _
_FATAL_EXCEPTION_FORMAT_ERRORS = False
class RedirectException(Exception):
def __init__(self, url):
self.url = urlparse.urlparse(url)
class GlanceException(Exception):
"""
Base Glance Exception
To correctly use this class, inherit from it and define
a 'message' property. That message will get printf'd
with the keyword arguments provided to the constructor.
"""
message = _("An unknown exception occurred")
def __init__(self, message=None, *args, **kwargs):
if not message:
message = self.message
try:
if kwargs:
message = message % kwargs
except Exception:
if _FATAL_EXCEPTION_FORMAT_ERRORS:
raise
else:
# at least get the core message out if something happened
pass
self.msg = message
super(GlanceException, self).__init__(message)
def __unicode__(self):
# NOTE(flwang): By default, self.msg is an instance of Message, which
# can't be converted by str(). Based on the definition of
# __unicode__, it should return unicode always.
return six.text_type(self.msg)
class MissingCredentialError(GlanceException):
message = _("Missing required credential: %(required)s")
class BadAuthStrategy(GlanceException):
message = _("Incorrect auth strategy, expected \"%(expected)s\" but "
"received \"%(received)s\"")
class NotFound(GlanceException):
message = _("An object with the specified identifier was not found.")
class BadStoreUri(GlanceException):
message = _("The Store URI was malformed.")
class Duplicate(GlanceException):
message = _("An object with the same identifier already exists.")
class Conflict(GlanceException):
message = _("An object with the same identifier is currently being "
"operated on.")
class StorageQuotaFull(GlanceException):
message = _("The size of the data %(image_size)s will exceed the limit. "
"%(remaining)s bytes remaining.")
class AuthBadRequest(GlanceException):
message = _("Connect error/bad request to Auth service at URL %(url)s.")
class AuthUrlNotFound(GlanceException):
message = _("Auth service at URL %(url)s not found.")
class AuthorizationFailure(GlanceException):
message = _("Authorization failed.")
class NotAuthenticated(GlanceException):
message = _("You are not authenticated.")
class UploadException(GlanceException):
message = _('Image upload problem: %s')
class Forbidden(GlanceException):
message = _("You are not authorized to complete %(action)s action.")
class ForbiddenPublicImage(Forbidden):
message = _("You are not authorized to complete this action.")
class ProtectedImageDelete(Forbidden):
message = _("Image %(image_id)s is protected and cannot be deleted.")
class ProtectedMetadefNamespaceDelete(Forbidden):
message = _("Metadata definition namespace %(namespace)s is protected"
" and cannot be deleted.")
class ProtectedMetadefNamespacePropDelete(Forbidden):
message = _("Metadata definition property %(property_name)s is protected"
" and cannot be deleted.")
class ProtectedMetadefObjectDelete(Forbidden):
message = _("Metadata definition object %(object_name)s is protected"
" and cannot be deleted.")
class ProtectedMetadefResourceTypeAssociationDelete(Forbidden):
message = _("Metadata definition resource-type-association"
" %(resource_type)s is protected and cannot be deleted.")
class ProtectedMetadefResourceTypeSystemDelete(Forbidden):
message = _("Metadata definition resource-type %(resource_type_name)s is"
" a seeded-system type and cannot be deleted.")
class ProtectedMetadefTagDelete(Forbidden):
message = _("Metadata definition tag %(tag_name)s is protected"
" and cannot be deleted.")
class Invalid(GlanceException):
message = _("Data supplied was not valid.")
class InvalidSortKey(Invalid):
message = _("Sort key supplied was not valid.")
class InvalidSortDir(Invalid):
message = _("Sort direction supplied was not valid.")
class InvalidPropertyProtectionConfiguration(Invalid):
message = _("Invalid configuration in property protection file.")
class InvalidSwiftStoreConfiguration(Invalid):
message = _("Invalid configuration in glance-swift conf file.")
class InvalidFilterOperatorValue(Invalid):
message = _("Unable to filter using the specified operator.")
class InvalidFilterRangeValue(Invalid):
message = _("Unable to filter using the specified range.")
class InvalidOptionValue(Invalid):
message = _("Invalid value for option %(option)s: %(value)s")
class ReadonlyProperty(Forbidden):
message = _("Attribute '%(property)s' is read-only.")
class ReservedProperty(Forbidden):
message = _("Attribute '%(property)s' is reserved.")
class AuthorizationRedirect(GlanceException):
message = _("Redirecting to %(uri)s for authorization.")
class ClientConnectionError(GlanceException):
message = _("There was an error connecting to a server")
class ClientConfigurationError(GlanceException):
message = _("There was an error configuring the client.")
class MultipleChoices(GlanceException):
message = _("The request returned a 302 Multiple Choices. This generally "
"means that you have not included a version indicator in a "
"request URI.\n\nThe body of response returned:\n%(body)s")
class LimitExceeded(GlanceException):
message = _("The request returned a 413 Request Entity Too Large. This "
"generally means that rate limiting or a quota threshold was "
"breached.\n\nThe response body:\n%(body)s")
def __init__(self, *args, **kwargs):
self.retry_after = (int(kwargs['retry']) if kwargs.get('retry')
else None)
super(LimitExceeded, self).__init__(*args, **kwargs)
class ServiceUnavailable(GlanceException):
message = _("The request returned 503 Service Unavailable. This "
"generally occurs on service overload or other transient "
"outage.")
def __init__(self, *args, **kwargs):
self.retry_after = (int(kwargs['retry']) if kwargs.get('retry')
else None)
super(ServiceUnavailable, self).__init__(*args, **kwargs)
class ServerError(GlanceException):
message = _("The request returned 500 Internal Server Error.")
class UnexpectedStatus(GlanceException):
message = _("The request returned an unexpected status: %(status)s."
"\n\nThe response body:\n%(body)s")
class InvalidContentType(GlanceException):
message = _("Invalid content type %(content_type)s")
class BadRegistryConnectionConfiguration(GlanceException):
message = _("Registry was not configured correctly on API server. "
"Reason: %(reason)s")
class BadDriverConfiguration(GlanceException):
message = _("Driver %(driver_name)s could not be configured correctly. "
"Reason: %(reason)s")
class MaxRedirectsExceeded(GlanceException):
message = _("Maximum redirects (%(redirects)s) was exceeded.")
class InvalidRedirect(GlanceException):
message = _("Received invalid HTTP redirect.")
class NoServiceEndpoint(GlanceException):
message = _("Response from Keystone does not contain a Glance endpoint.")
class RegionAmbiguity(GlanceException):
message = _("Multiple 'image' service matches for region %(region)s. This "
"generally means that a region is required and you have not "
"supplied one.")
class WorkerCreationFailure(GlanceException):
message = _("Server worker creation failed: %(reason)s.")
class SchemaLoadError(GlanceException):
message = _("Unable to load schema: %(reason)s")
class InvalidObject(GlanceException):
message = _("Provided object does not match schema "
"'%(schema)s': %(reason)s")
class ImageSizeLimitExceeded(GlanceException):
message = _("The provided image is too large.")
class FailedToGetScrubberJobs(GlanceException):
message = _("Scrubber encountered an error while trying to fetch "
"scrub jobs.")
class ImageMemberLimitExceeded(LimitExceeded):
message = _("The limit has been exceeded on the number of allowed image "
"members for this image. Attempted: %(attempted)s, "
"Maximum: %(maximum)s")
class ImagePropertyLimitExceeded(LimitExceeded):
message = _("The limit has been exceeded on the number of allowed image "
"properties. Attempted: %(attempted)s, Maximum: %(maximum)s")
class ImageTagLimitExceeded(LimitExceeded):
message = _("The limit has been exceeded on the number of allowed image "
"tags. Attempted: %(attempted)s, Maximum: %(maximum)s")
class ImageLocationLimitExceeded(LimitExceeded):
message = _("The limit has been exceeded on the number of allowed image "
"locations. Attempted: %(attempted)s, Maximum: %(maximum)s")
class SIGHUPInterrupt(GlanceException):
message = _("System SIGHUP signal received.")
class RPCError(GlanceException):
message = _("%(cls)s exception was raised in the last rpc call: %(val)s")
class TaskException(GlanceException):
message = _("An unknown task exception occurred")
class BadTaskConfiguration(GlanceException):
message = _("Task was not configured properly")
class ImageNotFound(NotFound):
message = _("Image with the given id %(image_id)s was not found")
class TaskNotFound(TaskException, NotFound):
message = _("Task with the given id %(task_id)s was not found")
class InvalidTaskStatus(TaskException, Invalid):
message = _("Provided status of task is unsupported: %(status)s")
class InvalidTaskType(TaskException, Invalid):
message = _("Provided type of task is unsupported: %(type)s")
class InvalidTaskStatusTransition(TaskException, Invalid):
message = _("Status transition from %(cur_status)s to"
" %(new_status)s is not allowed")
class ImportTaskError(TaskException, Invalid):
message = _("An import task exception occurred")
class TaskAbortedError(ImportTaskError):
message = _("Task was aborted externally")
class DuplicateLocation(Duplicate):
message = _("The location %(location)s already exists")
class InvalidParameterValue(Invalid):
message = _("Invalid value '%(value)s' for parameter '%(param)s': "
"%(extra_msg)s")
class InvalidImageStatusTransition(Invalid):
message = _("Image status transition from %(cur_status)s to"
" %(new_status)s is not allowed")
class MetadefDuplicateNamespace(Duplicate):
message = _("The metadata definition namespace=%(namespace_name)s"
" already exists.")
class MetadefDuplicateObject(Duplicate):
message = _("A metadata definition object with name=%(object_name)s"
" already exists in namespace=%(namespace_name)s.")
class MetadefDuplicateProperty(Duplicate):
message = _("A metadata definition property with name=%(property_name)s"
" already exists in namespace=%(namespace_name)s.")
class MetadefDuplicateResourceType(Duplicate):
message = _("A metadata definition resource-type with"
" name=%(resource_type_name)s already exists.")
class MetadefDuplicateResourceTypeAssociation(Duplicate):
message = _("The metadata definition resource-type association of"
" resource-type=%(resource_type_name)s to"
" namespace=%(namespace_name)s"
" already exists.")
class MetadefDuplicateTag(Duplicate):
message = _("A metadata tag with name=%(name)s"
" already exists in namespace=%(namespace_name)s."
" (Please note that metadata tag names are"
" case insensitive).")
class MetadefForbidden(Forbidden):
message = _("You are not authorized to complete this action.")
class MetadefIntegrityError(Forbidden):
message = _("The metadata definition %(record_type)s with"
" name=%(record_name)s not deleted."
" Other records still refer to it.")
class MetadefNamespaceNotFound(NotFound):
message = _("Metadata definition namespace=%(namespace_name)s"
" was not found.")
class MetadefObjectNotFound(NotFound):
message = _("The metadata definition object with"
" name=%(object_name)s was not found in"
" namespace=%(namespace_name)s.")
class MetadefPropertyNotFound(NotFound):
message = _("The metadata definition property with"
" name=%(property_name)s was not found in"
" namespace=%(namespace_name)s.")
class MetadefResourceTypeNotFound(NotFound):
message = _("The metadata definition resource-type with"
" name=%(resource_type_name)s, was not found.")
class MetadefResourceTypeAssociationNotFound(NotFound):
message = _("The metadata definition resource-type association of"
" resource-type=%(resource_type_name)s to"
" namespace=%(namespace_name)s,"
" was not found.")
class MetadefTagNotFound(NotFound):
message = _("The metadata definition tag with"
" name=%(name)s was not found in"
" namespace=%(namespace_name)s.")
class InvalidDataMigrationScript(GlanceException):
message = _("Invalid data migration script '%(script)s'. A valid data "
"migration script must implement functions 'has_migrations' "
"and 'migrate'.")
|
thekingofkings/urban-flow-analysis | refs/heads/master | python/FeatureUtils.py | 2 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 04 21:37:44 2015
@author: Hongjian
Package name: featureUtil
various functions for generating feature matrices/vectors
"""
from Crime import Tract
import numpy as np
import csv
from openpyxl import load_workbook
import heapq
import pickle
import os
here = os.path.dirname(os.path.abspath(__file__))
def generate_corina_features(region='ca', leaveOut=-1):
"""
Generate the features recommended by Corina.
parameter region taks 'ca' or 'tract'
Return values are field description, value array
"""
if region == 'ca':
f = open(here + '/../data/Chicago_demographics.csv', 'r')
c = csv.reader(f)
header = c.next()
fields = ['totpop00_sum', 'popden00', 'pprpovW00', 'Dis46pf0', 'Stb26pf0', 'Divers5f00',
'pnhblWc0', 'phispWc0']
fields_dsp = ['total population', 'population density', 'poverty index',
'disadvantage index', 'residential stability',
'ethnic diversity', 'pct black', 'pct hispanic']
hidx = []
for fd in fields:
hidx.append(header.index(fd))
C = np.zeros((77, len(hidx)))
for i, row in enumerate(c):
for j, k in enumerate(hidx):
C[i][j] = float(row[k])
if leaveOut > 0:
C = np.delete(C, leaveOut-1, 0)
return fields_dsp, C
elif region == 'tract':
from pandas import read_stata
r = read_stata('../data/SE2000_AG20140401_MSAcmsaID.dta')
cnt = 0
header = ['pop00', 'ppov00', 'disadv00', 'pdensmi00', 'hetero00', 'phisp00', 'pnhblk00']
fields_dsp = ['total population', 'poverty index', 'disadvantage index',
'population density', 'ethnic diversity', 'pct hispanic', 'pct black']
ST = {}
for row in r.iterrows():
tract = row[1]
if tract['statetrim'] == '17' and tract['countrim'] == '031':
cnt += 1
tl = []
tid = long('17031' + tract['tracttrim'])
for h in header:
tl.append(tract[h])
ST[tid] = tl
return fields_dsp, ST
def generate_geographical_SpatialLag():
"""
Generate the spatial lag from the geographically adjacent regions.
"""
ts = Tract.createAllTractObjects()
ordkey = sorted(ts)
centers = [ts[k].polygon.centroid for k in ordkey]
W = np.zeros((len(centers), len(centers)))
for i, src in enumerate(centers):
for j, dst in enumerate(centers):
if src != dst:
W[i][j] = 1 / src.distance(dst)
return W, ordkey
def generate_geographical_SpatialLag_ca(knearest=True, leaveOut=-1):
"""
Generate the distance matrix for CA pairs.
If knearest is true, then select the 6-nearest neighboring CAs.
Else, return the distance to all other CAs.
leaveOut will select the CA and remove it. take value from 1 to 77
"""
cas = Tract.createAllCAObjects()
centers = []
iset = range(1, 78)
if leaveOut > 0:
iset.remove(leaveOut)
for i in iset:
centers.append(cas[i].polygon.centroid)
W = np.zeros( (len(iset),len(iset)) )
for i, src in enumerate(centers):
for j, dst in enumerate(centers):
if src != dst:
W[i][j] = 1 / src.distance(dst)
# find n-largest (n=6)
if knearest == True:
threshold = heapq.nlargest(6, W[i,:])[-1]
for j in range(len(W[i,:])):
W[i][j] = 0 if W[i][j] < threshold else W[i][j]
return W
def get_centroid_ca():
cas = Tract.createAllCAObjects()
centers = []
for i in range(1, 78):
ctd = cas[i].polygon.centroid
centers.append([ctd.x, ctd.y])
return centers
def generate_GWR_weight(h = 1):
"""
Generate the GWR weighting matrix with exponential function.
"""
cas = Tract.createAllCAObjects()
centers = []
for i in range(1, 78):
centers.append(cas[i].polygon.centroid)
gamma = np.ones((len(centers), len(centers)))
for i, src in enumerate(centers):
for j, dst in enumerate(centers):
if i != j:
gamma[i][j] = np.exp(-0.5 * src.distance(dst)**2 / h**2)
return gamma
def generate_geo_graph_embedding_src():
flow = generate_geographical_SpatialLag_ca()
row, column = flow.shape
with open("multi-view-learning/geo.od", 'w') as fout:
for i in range(row):
for j in range(column):
if flow[i,j] > 0:
fout.write('{0} {1} {2}\n'.format(i, j, flow[i,j]))
def generate_transition_SocialLag(year = 2010, lehd_type=0, region='ca', leaveOut=-1, normalization='source'):
"""
Generate the spatial lag matrix from the transition flow connected CAs.
0 - #total jobs
1 - #jobs age under 29,
2 - #jobs age from 30 to 54,
3 - #jobs above 55,
4 - #jobs earning under $1250/month,
5 - #jobs earnings from $1251 to $3333/month,
6 - #jobs above $3333/month,
7 - #jobs in goods producing,
8 - #jobs in trade transportation,
9 - #jobs in other services
"""
if region == 'ca':
ts = Tract.createAllCAObjects()
fn = here + '/../data/chicago_ca_od_{0}.csv'.format(year)
elif region == 'tract':
ts = Tract.createAllTractObjects()
fn = here + '/../data/chicago_od_tract_{0}.csv'.format(year)
ordkey = sorted(ts.keys())
listIdx = {}
fin = open(fn)
for line in fin:
ls = line.split(",")
srcid = int(ls[0][5:])
dstid = int(ls[1][5:])
val = int(ls[2 + lehd_type])
if srcid in listIdx:
listIdx[srcid][dstid] = val
else:
listIdx[srcid] = {}
listIdx[srcid][dstid] = val
fin.close()
if leaveOut > 0:
ordkey.remove(leaveOut)
W = np.zeros( (len(ts),len(ts)) )
for srcid in ordkey:
if srcid in listIdx:
sdict = listIdx[srcid]
if leaveOut in sdict:
del sdict[leaveOut]
for dstid, val in sdict.items():
W[ordkey.index(srcid)][ordkey.index(dstid)] = val
else:
W[ordkey.index(srcid)] = np.zeros( (1,len(ts)) )
# update diagonal as 0
# if normalization != 'none':
# for i in range(len(W)):
# W[i,i] = 0
# first make all self-factor 0
assert W.dtype == "float64"
# normalization section
if normalization == 'source':
# source mean the residence
W = np.transpose(W)
sW = np.sum(W, axis=1, keepdims=True)
W = W / sW
assert abs( np.sum(W[1,]) - 1 ) < 0.0000000001 and W.dtype == "float64"
elif normalization == 'destination': #
# destination mean workplace
sW = np.sum(W, axis=1)
sW = sW.reshape((len(sW),1))
W = W / sW
elif normalization == 'pair':
sW = W + np.transpose(W)
sW = np.sum(sW)
W = W / sW
# by default, the output is the workplace-to-residence count matrix
return W
import pandas as pd
def retrieve_health_data():
"""
get health data
"""
h = pd.read_stata("../data/ChiCas77_PubHealthScale_ForNSFproject.dta")
return h['phlth12vc2alpha'].values, h['phlth10novcAlpha'].values
def retrieve_crime_count(year, col=['total'], region='ca'):
"""
Retrieve the crime count in a vector
Input:
year - the year to retrieve
col - the type of crime
region - ca or tract
Output:
if region == 'ca': Y is a column vector of size (77,1)
"""
if region == 'ca':
Y =np.zeros( (77,1) )
with open(here + '/../data/chicago-crime-ca-level-{0}.csv'.format(year)) as fin:
header = fin.readline().strip().split(",")
crime_idx = []
for c in col:
if c in header:
i = header.index(c)
crime_idx.append(i)
for line in fin:
ls = line.split(",")
idx = int(ls[0])
val = 0
for i in crime_idx:
val += int(ls[i])
Y[idx-1] = val
return Y
elif region == 'tract':
Y = {}
with open(here + '/../data/chicago-crime-tract-level-{0}.csv'.format(year)) as fin:
header = fin.readline().strip().split(",")
crime_idx = []
for c in col:
i = header.index(c)
crime_idx.append(i)
for line in fin:
ls = line.split(",")
tid = int(ls[0])
val = 0
for i in crime_idx:
val += int(ls[i])
Y[tid] = val
return Y
def retrieve_income_features():
"""
read the xlsx file: ../data/chicago-ca-income.xlsx
Three kinds of features we can generate:
1. population count in each category
2. probability distribution over all categories (normalize by population)
3. Grouped mean, variance
"""
wb = load_workbook(here + "/../data/chicago-ca-income.xlsx")
ws = wb.active
header = ws['l3':'aa3']
header = [c.value for c in tuple(header)[0]]
bins = [5000, 12500, 17500, 22500, 27500, 32500, 37500, 42500, 47500, 55000, 67500,
87500, 112500, 137500, 175000, 300000]
# bins = range(1,17)
l = len(header)
I = np.zeros((77,l))
stats_header = ['income mean', 'std var']
stats = np.zeros((77,2)) # mean, variance
total = np.zeros( (77,1) )
for idx, row in enumerate(ws.iter_rows('k4:aa80')):
for j, c in enumerate(row):
if j == 0:
total[idx] = float(c.value)
else:
I[idx][j-1] = c.value # / total
stats[idx][0] = np.dot(bins, I[idx][:]) / total[idx]
stats[idx][1] = np.sqrt( np.dot(I[idx][:], (bins - stats[idx][0])**2) / total[idx] )
# return header, I
return stats_header + ['population'], np.concatenate((stats, total), axis=1)
def retrieve_education_features():
"""
read the xlsx file: ../data/chicago-ca-education.xlsx
"""
wb = load_workbook(here + "/../data/chicago-ca-education.xlsx")
ws = wb.active
header = ws['k3':'n3']
header = [c.value for c in tuple(header)[0]]
bins = range(1,5)
l = len(header)
E = np.zeros((77,l))
stats_header = ['education level', 'std var']
stats = np.zeros((77,2))
for i, row in enumerate(ws.iter_rows('j4:n80')):
total = 0
for j, c in enumerate(row):
if j == 0:
total = float(c.value)
else:
E[i][j-1] = c.value # / total
stats[i][0] = np.dot(E[i][:], bins) / total
stats[i][1] = np.sqrt( np.dot(E[i][:], (bins - stats[i][0])**2) / total)
return stats_header, stats
def retrieve_race_features():
"""
read the xlsx file: ../data/chicago-ca-race.xlsx
"""
wb = load_workbook(here + "/../data/chicago-ca-race.xlsx")
ws = wb.active
header = ws['j2':'p2']
header = [c.value for c in tuple(header)[0]]
l = len(header)
R = np.zeros((77,l))
bins = range(1,8)
stats_header = ['race level', 'std var']
stats = np.zeros((77,2))
for i, row in enumerate(ws.iter_rows('j4:p80')):
total = 0
for c in row:
total += float(c.value)
for j, c in enumerate(row):
R[i][j] = c.value # / total
stats[i][0] = np.dot(R[i][:], bins) / total
stats[i][1] = np.sqrt( np.dot(R[i][:], (bins - stats[i][0])**2) / total)
return stats_header, stats
# return header, R
def retrieve_averge_house_price():
with open(here + "/../data/ca-average-house-price.pickle", 'r') as fin:
avg_price = pickle.load(fin)
res = []
for idx in range(77):
res.append(avg_price[idx+1])
return np.array(res)
def generateDotFile(s, threshold=400, fileName='taxiflow'):
"""
generate dot file
The dot file is used by graphviz to visualize graph
"""
nodes = set()
with open('{0}.dot'.format(fileName), 'w') as fout:
fout.write('digraph taxiChicago {\n')
for i, row in enumerate(s):
for j, ele in enumerate(row):
if ele > threshold:
if i not in nodes:
fout.write('{0} [label="{1}"];\n'.format(i, i+1))
nodes.add(i)
if j not in nodes:
fout.write('{0} [label="{1}"];\n'.format(j, j+1))
nodes.add(j)
fout.write('{0} -> {1} [label="{2:.3f}"];\n'.format(i,j, ele) )
fout.write('}\n')
import subprocess
subprocess.call(['dot ', '-Tpdf', '-o{0}.pdf'.format(fileName), '{0}.dot'.format(fileName)])
import unittest
class TestFeatureUtils(unittest.TestCase):
def test_generate_GWR_weight(self):
gamma = generate_GWR_weight(0.5)
for i in range(20):
np.testing.assert_almost_equal(gamma[i,i], 1.)
assert np.amax(gamma) <= 1
print np.amin(gamma)
def generate_binary_crime_label():
y = retrieve_crime_count(2013)
threshold = np.median(y)
label = [1 if ele >= threshold else 0 for ele in y]
F = generate_corina_features()
from sklearn import svm, tree
from sklearn.model_selection import cross_val_score
clf1 = svm.SVC()
scores1 = cross_val_score(clf1, F[1], label, cv=10)
print scores1.mean(), scores1
clf2 = tree.DecisionTreeClassifier()
scores2 = cross_val_score(clf2, F[1], label, cv=10)
print scores2.mean(), scores2
pickle.dump(label, open("crime-label", 'w'))
return y, label, F[1]
def generate_binary_demo_label():
D = generate_corina_features()
demolabel = {}
for i, d in enumerate(D[0]):
F = D[1][:,i]
thrsd = np.median(F)
label= [1 if ele >= thrsd else 0 for ele in F]
demolabel[d] = label
pickle.dump(demolabel, open("demo-label", "w"))
return demolabel, D
def generate_lehd_label():
f = generate_transition_SocialLag(2010, 0, 'ca', -1, 'None')
r = []
for i in range(77):
home = np.sum(f[:,i])
work = np.sum(f[i,:])
r.append(home/work)
avg = np.median(r)
label = []
cnt = [0,0]
for i in r:
if i >= avg:
label.append(1)
cnt[1] += 1
else:
label.append(0)
cnt[0] += 1
for idx, i in enumerate(r):
print idx+1, i, '\t', label[idx]
print cnt
pickle.dump(label, open("lehd-label", "w"))
return f, label
def visualizeGangRelatedCrime():
"""
In the following crime categories, the region 47 has much higher crime rate
than its peers 44, 45, 48. Actually 47 is among the top 3.
"""
focal = [43,44,46,47]
C = generate_corina_features()
popul = C[1][:,0].reshape(C[1].shape[0],1)
violentCrime = "BURGLARY,INTIMIDATION,KIDNAPPING"
violentCrime = violentCrime.split(",")
Y = retrieve_crime_count(year=2013, col=violentCrime, region='ca')
Y = np.divide(Y, popul) * 10000
Y = Y.reshape((77,))
np.savetxt("../R/crime-rate-ca.csv", Y, delimiter=",")
Yidx = np.argsort(Y)[::-1]
for i in focal:
print i, popul[i], Y[i], np.where(Yidx == i)
import subprocess
os.chdir("../R")
t = subprocess.check_output(["Rscript", "nodalFeature_plot.R", "crime"])
print t
return Y
if __name__ == '__main__':
import sys
if len(sys.argv) > 1:
if sys.argv[1] == 'test':
unittest.main()
elif sys.argv[1] == 'binarylabel':
y, l, f = generate_binary_crime_label()
l, D = generate_binary_demo_label()
elif sys.argv[1] == 'LEHDlabel':
l = generate_lehd_label()
else:
# generate_geo_graph_embedding_src()
# t = generate_transition_SocialLag(2013, 0, "tract", -1, "none")
# with open("lehd-tract-2013.pickle", "w") as fout:
# pickle.dump(t.T, fout)
y = visualizeGangRelatedCrime()
# from taxiFlow import getTaxiFlow
# s = getTaxiFlow(usePercentage=False)
# generateDotFile(s, 5000)
# for year in range(2002, 2014):
# t = generate_transition_SocialLag(year=year, lehd_type=0, region='ca',
# leaveOut=-1, normalization='none')
# np.savetxt("{0}-social-row-matrix.csv".format(year), t, delimiter=",")
# generateDotFile(t, 0.08, 'sociallag')
# h = retrieve_health_data()
|
FRidh/Sea | refs/heads/master | Sea/adapter/base/__init__.py | 2 |
from Base import Base
from ViewProviderBase import ViewProviderBase |
puneetgkaur/backup_sugar_shell_for_cordova | refs/heads/master | src/jarabe/journal/listview.py | 1 | # Copyright (C) 2009, Tomeu Vizoso
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import logging
from gettext import gettext as _
import time
from gi.repository import GLib
from gi.repository import GObject
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import Pango
from sugar3.graphics import style
from sugar3.graphics.icon import Icon, CellRendererIcon
from sugar3 import util
from sugar3 import profile
from jarabe.journal.listmodel import ListModel
from jarabe.journal.palettes import ObjectPalette, BuddyPalette
from jarabe.journal import model
from jarabe.journal import misc
from jarabe.journal import journalwindow
UPDATE_INTERVAL = 300
class TreeView(Gtk.TreeView):
__gtype_name__ = 'JournalTreeView'
def __init__(self):
Gtk.TreeView.__init__(self)
self.set_headers_visible(False)
self.set_enable_search(False)
self.add_events(Gdk.EventMask.BUTTON_PRESS_MASK |
Gdk.EventMask.TOUCH_MASK |
Gdk.EventMask.BUTTON_RELEASE_MASK)
def do_size_request(self, requisition):
# HACK: We tell the model that the view is just resizing so it can
# avoid hitting both D-Bus and disk.
tree_model = self.get_model()
if tree_model is not None:
tree_model.view_is_resizing = True
try:
Gtk.TreeView.do_size_request(self, requisition)
finally:
if tree_model is not None:
tree_model.view_is_resizing = False
class BaseListView(Gtk.Bin):
__gtype_name__ = 'JournalBaseListView'
__gsignals__ = {
'clear-clicked': (GObject.SignalFlags.RUN_FIRST, None, ([])),
'selection-changed': (GObject.SignalFlags.RUN_FIRST, None, ([int])),
}
def __init__(self, journalactivity, enable_multi_operations=False):
self._query = {}
self._journalactivity = journalactivity
self._enable_multi_operations = enable_multi_operations
self._model = None
self._progress_bar = None
self._last_progress_bar_pulse = None
self._scroll_position = 0.
Gtk.Bin.__init__(self)
self.connect('map', self.__map_cb)
self.connect('unmap', self.__unmap_cb)
self.connect('destroy', self.__destroy_cb)
self._scrolled_window = Gtk.ScrolledWindow()
self._scrolled_window.set_policy(Gtk.PolicyType.NEVER,
Gtk.PolicyType.AUTOMATIC)
self.add(self._scrolled_window)
self._scrolled_window.show()
self.tree_view = TreeView()
selection = self.tree_view.get_selection()
selection.set_mode(Gtk.SelectionMode.NONE)
self.tree_view.props.fixed_height_mode = True
self._scrolled_window.add(self.tree_view)
self.tree_view.show()
self.cell_title = None
self.cell_icon = None
self._title_column = None
self.sort_column = None
self._add_columns()
self.enable_drag_and_copy()
# Auto-update stuff
self._fully_obscured = True
self._updates_disabled = False
self._dirty = False
self._refresh_idle_handler = None
self._update_dates_timer = None
self._backup_selected = None
model.created.connect(self.__model_created_cb)
model.updated.connect(self.__model_updated_cb)
model.deleted.connect(self.__model_deleted_cb)
def enable_drag_and_copy(self):
self.tree_view.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK,
[('text/uri-list', 0, 0),
('journal-object-id', 0, 0)],
Gdk.DragAction.COPY)
def disable_drag_and_copy(self):
self.tree_view.unset_rows_drag_source()
def __model_created_cb(self, sender, signal, object_id):
if self._is_new_item_visible(object_id):
self._set_dirty()
def __model_updated_cb(self, sender, signal, object_id):
if self._is_new_item_visible(object_id):
self._set_dirty()
def __model_deleted_cb(self, sender, signal, object_id):
if self._is_new_item_visible(object_id):
self._set_dirty()
def _is_new_item_visible(self, object_id):
"""Check if the created item is part of the currently selected view"""
if self._query['mountpoints'] == ['/']:
return not object_id.startswith('/')
else:
return object_id.startswith(self._query['mountpoints'][0])
def _add_columns(self):
if self._enable_multi_operations:
cell_select = Gtk.CellRendererToggle()
cell_select.connect('toggled', self.__cell_select_toggled_cb)
cell_select.props.activatable = True
cell_select.props.xpad = style.DEFAULT_PADDING
cell_select.props.indicator_size = style.zoom(26)
column = Gtk.TreeViewColumn()
column.props.sizing = Gtk.TreeViewColumnSizing.FIXED
column.props.fixed_width = style.GRID_CELL_SIZE
column.pack_start(cell_select, True)
column.set_cell_data_func(cell_select, self.__select_set_data_cb)
self.tree_view.append_column(column)
cell_favorite = CellRendererFavorite(self.tree_view)
cell_favorite.connect('clicked', self._favorite_clicked_cb)
column = Gtk.TreeViewColumn()
column.props.sizing = Gtk.TreeViewColumnSizing.FIXED
column.props.fixed_width = cell_favorite.props.width
column.pack_start(cell_favorite, True)
column.set_cell_data_func(cell_favorite, self.__favorite_set_data_cb)
self.tree_view.append_column(column)
self.cell_icon = CellRendererActivityIcon(self._journalactivity,
self.tree_view)
column = Gtk.TreeViewColumn()
column.props.sizing = Gtk.TreeViewColumnSizing.FIXED
column.props.fixed_width = self.cell_icon.props.width
column.pack_start(self.cell_icon, True)
column.add_attribute(self.cell_icon, 'file-name',
ListModel.COLUMN_ICON)
column.add_attribute(self.cell_icon, 'xo-color',
ListModel.COLUMN_ICON_COLOR)
self.tree_view.append_column(column)
self.cell_title = Gtk.CellRendererText()
self.cell_title.props.ellipsize = style.ELLIPSIZE_MODE_DEFAULT
self.cell_title.props.ellipsize_set = True
self._title_column = Gtk.TreeViewColumn()
self._title_column.props.sizing = Gtk.TreeViewColumnSizing.FIXED
self._title_column.props.expand = True
self._title_column.props.clickable = True
self._title_column.pack_start(self.cell_title, True)
self._title_column.add_attribute(self.cell_title, 'markup',
ListModel.COLUMN_TITLE)
self.tree_view.append_column(self._title_column)
for column_index in [ListModel.COLUMN_BUDDY_1,
ListModel.COLUMN_BUDDY_2,
ListModel.COLUMN_BUDDY_3]:
buddies_column = Gtk.TreeViewColumn()
buddies_column.props.sizing = Gtk.TreeViewColumnSizing.FIXED
self.tree_view.append_column(buddies_column)
cell_icon = CellRendererBuddy(self.tree_view,
column_index=column_index)
buddies_column.pack_start(cell_icon, True)
buddies_column.props.fixed_width += cell_icon.props.width
buddies_column.add_attribute(cell_icon, 'buddy', column_index)
buddies_column.set_cell_data_func(cell_icon,
self.__buddies_set_data_cb)
cell_progress = Gtk.CellRendererProgress()
cell_progress.props.ypad = style.GRID_CELL_SIZE / 4
buddies_column.pack_start(cell_progress, True)
buddies_column.add_attribute(cell_progress, 'value',
ListModel.COLUMN_PROGRESS)
buddies_column.set_cell_data_func(cell_progress,
self.__progress_data_cb)
cell_text = Gtk.CellRendererText()
cell_text.props.xalign = 1
# Measure the required width for a date in the form of "10 hours, 10
# minutes ago"
timestamp = time.time() - 10 * 60 - 10 * 60 * 60
date = util.timestamp_to_elapsed_string(timestamp)
date_width = self._get_width_for_string(date)
self.sort_column = Gtk.TreeViewColumn()
self.sort_column.props.sizing = Gtk.TreeViewColumnSizing.FIXED
self.sort_column.props.fixed_width = date_width
self.sort_column.set_alignment(1)
self.sort_column.props.resizable = True
self.sort_column.props.clickable = True
self.sort_column.pack_start(cell_text, True)
self.sort_column.add_attribute(cell_text, 'text',
ListModel.COLUMN_TIMESTAMP)
self.tree_view.append_column(self.sort_column)
def _get_width_for_string(self, text):
# Add some extra margin
text = text + 'aaaaa'
widget = Gtk.Label(label='')
context = widget.get_pango_context()
layout = Pango.Layout(context)
layout.set_text(text, len(text))
width, height_ = layout.get_pixel_size()
return width
def do_size_allocate(self, allocation):
self.set_allocation(allocation)
self.get_child().size_allocate(allocation)
def do_size_request(self, requisition):
requisition.width, requisition.height = \
self.get_child().size_request()
def __destroy_cb(self, widget):
if self._model is not None:
self._model.stop()
def __buddies_set_data_cb(self, column, cell, tree_model,
tree_iter, data):
buddy = tree_model.do_get_value(tree_iter, cell._model_column_index)
if buddy is None:
cell.props.visible = False
return
# FIXME workaround for pygobject bug, see
# https://bugzilla.gnome.org/show_bug.cgi?id=689277
#
# add_attribute with 'buddy' attribute in the cell should take
# care of setting it.
cell.props.buddy = buddy
progress = tree_model[tree_iter][ListModel.COLUMN_PROGRESS]
cell.props.visible = progress >= 100
def __progress_data_cb(self, column, cell, tree_model,
tree_iter, data):
progress = tree_model[tree_iter][ListModel.COLUMN_PROGRESS]
cell.props.visible = progress < 100
def __favorite_set_data_cb(self, column, cell, tree_model,
tree_iter, data):
favorite = tree_model[tree_iter][ListModel.COLUMN_FAVORITE]
if favorite:
cell.props.xo_color = profile.get_color()
else:
cell.props.xo_color = None
def _favorite_clicked_cb(self, cell, path):
row = self._model[path]
metadata = model.get(row[ListModel.COLUMN_UID])
if not model.is_editable(metadata):
return
if metadata.get('keep', 0) == '1':
metadata['keep'] = '0'
else:
metadata['keep'] = '1'
model.write(metadata, update_mtime=False)
def __select_set_data_cb(self, column, cell, tree_model, tree_iter,
data):
uid = tree_model[tree_iter][ListModel.COLUMN_UID]
if uid is None:
return
cell.props.active = self._model.is_selected(uid)
def __cell_select_toggled_cb(self, cell, path):
tree_iter = self._model.get_iter(path)
uid = self._model[tree_iter][ListModel.COLUMN_UID]
self._model.set_selected(uid, not cell.get_active())
self.emit('selection-changed', len(self._model.get_selected_items()))
def update_with_query(self, query_dict):
logging.debug('ListView.update_with_query')
if 'order_by' not in query_dict:
query_dict['order_by'] = ['+timestamp']
if query_dict['order_by'] != self._query.get('order_by'):
property_ = query_dict['order_by'][0][1:]
cell_text = self.sort_column.get_cells()[0]
self.sort_column.set_attributes(cell_text,
text=getattr(
ListModel, 'COLUMN_' +
property_.upper(),
ListModel.COLUMN_TIMESTAMP))
self._query = query_dict
self.refresh(new_query=True)
def refresh(self, new_query=False):
logging.debug('ListView.refresh query %r', self._query)
self._stop_progress_bar()
window = self.get_toplevel().get_window()
if window is not None:
window.set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH))
GObject.idle_add(self._do_refresh, new_query)
def _do_refresh(self, new_query=False):
if self._model is not None:
if new_query:
self._backup_selected = None
else:
self._backup_selected = self._model.get_selected_items()
self._model.stop()
self._dirty = False
self._model = ListModel(self._query)
self._model.connect('ready', self.__model_ready_cb)
self._model.connect('progress', self.__model_progress_cb)
self._model.setup()
window = self.get_toplevel().get_window()
if window is not None:
window.set_cursor(None)
def __model_ready_cb(self, tree_model):
self._stop_progress_bar()
self._scroll_position = self.tree_view.props.vadjustment.props.value
logging.debug('ListView.__model_ready_cb %r', self._scroll_position)
x11_window = self.tree_view.get_window()
if x11_window is not None:
# prevent glitches while later vadjustment setting, see #1235
self.tree_view.get_bin_window().hide()
# if the selection was preserved, restore it
if self._backup_selected is not None:
tree_model.restore_selection(self._backup_selected)
self.emit('selection-changed', len(self._backup_selected))
# Cannot set it up earlier because will try to access the model
# and it needs to be ready.
self.tree_view.set_model(self._model)
self.tree_view.props.vadjustment.props.value = self._scroll_position
self.tree_view.props.vadjustment.value_changed()
if x11_window is not None:
# prevent glitches while later vadjustment setting, see #1235
self.tree_view.get_bin_window().show()
if len(tree_model) == 0:
documents_path = model.get_documents_path()
if self._is_query_empty():
if self._query['mountpoints'] == ['/']:
self._show_message(_('Your Journal is empty'))
elif documents_path and self._query['mountpoints'] == \
[documents_path]:
self._show_message(_('Your documents folder is empty'))
else:
self._show_message(_('The device is empty'))
else:
self._show_message(_('No matching entries'),
show_clear_query=self._can_clear_query())
else:
self._clear_message()
def _can_clear_query(self):
return True
def __map_cb(self, widget):
logging.debug('ListView.__map_cb %r', self._scroll_position)
self.tree_view.props.vadjustment.props.value = self._scroll_position
self.tree_view.props.vadjustment.value_changed()
self.set_is_visible(True)
def __unmap_cb(self, widget):
self._scroll_position = self.tree_view.props.vadjustment.props.value
logging.debug('ListView.__unmap_cb %r', self._scroll_position)
self.set_is_visible(False)
def _is_query_empty(self):
# FIXME: This is a hack, we shouldn't have to update this every time
# a new search term is added.
return not (self._query.get('query') or self._query.get('mime_type') or
self._query.get('keep') or self._query.get('mtime') or
self._query.get('activity'))
def __model_progress_cb(self, tree_model):
if self._progress_bar is None:
self._start_progress_bar()
if time.time() - self._last_progress_bar_pulse > 0.05:
self._progress_bar.pulse()
self._last_progress_bar_pulse = time.time()
def _start_progress_bar(self):
alignment = Gtk.Alignment.new(xalign=0.5, yalign=0.5,
xscale=0.5, yscale=0)
self.remove(self.get_child())
self.add(alignment)
alignment.show()
self._progress_bar = Gtk.ProgressBar()
self._progress_bar.props.pulse_step = 0.01
self._last_progress_bar_pulse = time.time()
alignment.add(self._progress_bar)
self._progress_bar.show()
def _stop_progress_bar(self):
if self._progress_bar is None:
return
self.remove(self.get_child())
self.add(self._scrolled_window)
self._progress_bar = None
def _show_message(self, message, show_clear_query=False):
self.remove(self.get_child())
background_box = Gtk.EventBox()
background_box.modify_bg(Gtk.StateType.NORMAL,
style.COLOR_WHITE.get_gdk_color())
self.add(background_box)
alignment = Gtk.Alignment.new(0.5, 0.5, 0.1, 0.1)
background_box.add(alignment)
box = Gtk.VBox()
alignment.add(box)
icon = Icon(pixel_size=style.LARGE_ICON_SIZE,
icon_name='activity-journal',
stroke_color=style.COLOR_BUTTON_GREY.get_svg(),
fill_color=style.COLOR_TRANSPARENT.get_svg())
box.pack_start(icon, expand=True, fill=False, padding=0)
label = Gtk.Label()
color = style.COLOR_BUTTON_GREY.get_html()
label.set_markup('<span weight="bold" color="%s">%s</span>' % (
color, GLib.markup_escape_text(message)))
box.pack_start(label, expand=True, fill=False, padding=0)
if show_clear_query:
button_box = Gtk.HButtonBox()
button_box.set_layout(Gtk.ButtonBoxStyle.CENTER)
box.pack_start(button_box, False, True, 0)
button_box.show()
button = Gtk.Button(label=_('Clear search'))
button.connect('clicked', self.__clear_button_clicked_cb)
button.props.image = Icon(icon_name='dialog-cancel',
pixel_size=style.SMALL_ICON_SIZE)
button_box.pack_start(button, expand=True, fill=False, padding=0)
background_box.show_all()
def __clear_button_clicked_cb(self, button):
self.emit('clear-clicked')
def _clear_message(self):
if self.get_child() == self._scrolled_window:
return
self.remove(self.get_child())
self.add(self._scrolled_window)
self._scrolled_window.show()
def update_dates(self):
if not self.tree_view.get_realized():
return
visible_range = self.tree_view.get_visible_range()
if visible_range is None:
return
logging.debug('ListView.update_dates')
path, end_path = visible_range
tree_model = self.tree_view.get_model()
while True:
cel_rect = self.tree_view.get_cell_area(path,
self.sort_column)
x, y = self.tree_view.convert_tree_to_widget_coords(cel_rect.x,
cel_rect.y)
self.tree_view.queue_draw_area(x, y, cel_rect.width,
cel_rect.height)
if path == end_path:
break
else:
next_iter = tree_model.iter_next(tree_model.get_iter(path))
path = tree_model.get_path(next_iter)
def _set_dirty(self):
if self._fully_obscured or self._updates_disabled:
self._dirty = True
else:
self.refresh()
def disable_updates(self):
self._updates_disabled = True
def enable_updates(self):
self._updates_disabled = False
if self._dirty:
self.refresh()
def set_is_visible(self, visible):
if visible != self._fully_obscured:
return
logging.debug('canvas_visibility_notify_event_cb %r', visible)
if visible:
self._fully_obscured = False
if self._dirty:
self.refresh()
if self._update_dates_timer is None:
logging.debug('Adding date updating timer')
self._update_dates_timer = \
GObject.timeout_add_seconds(UPDATE_INTERVAL,
self.__update_dates_timer_cb)
else:
self._fully_obscured = True
if self._update_dates_timer is not None:
logging.debug('Remove date updating timer')
GObject.source_remove(self._update_dates_timer)
self._update_dates_timer = None
def __update_dates_timer_cb(self):
self.update_dates()
return True
def get_model(self):
return self._model
def select_all(self):
self.get_model().select_all()
self.tree_view.queue_draw()
self.emit('selection-changed', len(self._model.get_selected_items()))
def select_none(self):
self.get_model().select_none()
self.tree_view.queue_draw()
self.emit('selection-changed', len(self._model.get_selected_items()))
class ListView(BaseListView):
__gtype_name__ = 'JournalListView'
__gsignals__ = {
'detail-clicked': (GObject.SignalFlags.RUN_FIRST, None,
([object])),
'volume-error': (GObject.SignalFlags.RUN_FIRST, None,
([str, str])),
'title-edit-started': (GObject.SignalFlags.RUN_FIRST, None,
([])),
'title-edit-finished': (GObject.SignalFlags.RUN_FIRST, None,
([])),
}
def __init__(self, journalactivity, enable_multi_operations=False):
BaseListView.__init__(self, journalactivity, enable_multi_operations)
self._is_dragging = False
self.tree_view.connect('drag-begin', self.__drag_begin_cb)
self.tree_view.connect('button-release-event',
self.__button_release_event_cb)
self.cell_title.connect('edited', self.__cell_title_edited_cb)
self.cell_title.connect('editing-canceled', self.__editing_canceled_cb)
self.cell_icon.connect('clicked', self.__icon_clicked_cb)
self.cell_icon.connect('detail-clicked', self.__detail_clicked_cb)
self.cell_icon.connect('volume-error', self.__volume_error_cb)
cell_detail = CellRendererDetail(self.tree_view)
cell_detail.connect('clicked', self.__detail_cell_clicked_cb)
column = Gtk.TreeViewColumn()
column.props.sizing = Gtk.TreeViewColumnSizing.FIXED
column.props.fixed_width = cell_detail.props.width
column.pack_start(cell_detail, True)
self.tree_view.append_column(column)
def is_dragging(self):
return self._is_dragging
def __drag_begin_cb(self, widget, drag_context):
self._is_dragging = True
def __button_release_event_cb(self, tree_view, event):
try:
if self._is_dragging:
return
finally:
self._is_dragging = False
pos = tree_view.get_path_at_pos(int(event.x), int(event.y))
if pos is None:
return
path, column, x_, y_ = pos
if column != self._title_column:
return
row = self.tree_view.get_model()[path]
metadata = model.get(row[ListModel.COLUMN_UID])
self.cell_title.props.editable = model.is_editable(metadata)
if self.cell_title.props.editable:
self.emit('title-edit-started')
tree_view.set_cursor_on_cell(path, column, self.cell_title,
start_editing=True)
def __detail_cell_clicked_cb(self, cell, path):
row = self.tree_view.get_model()[path]
self.emit('detail-clicked', row[ListModel.COLUMN_UID])
def __detail_clicked_cb(self, cell, uid):
self.emit('detail-clicked', uid)
def __volume_error_cb(self, cell, message, severity):
self.emit('volume-error', message, severity)
def __icon_clicked_cb(self, cell, path):
row = self.tree_view.get_model()[path]
metadata = model.get(row[ListModel.COLUMN_UID])
misc.resume(metadata,
alert_window=journalwindow.get_journal_window())
def __cell_title_edited_cb(self, cell, path, new_text):
row = self._model[path]
metadata = model.get(row[ListModel.COLUMN_UID])
metadata['title'] = new_text
model.write(metadata, update_mtime=False)
self.cell_title.props.editable = False
self.emit('title-edit-finished')
def __editing_canceled_cb(self, cell):
self.cell_title.props.editable = False
self.emit('title-edit-finished')
class CellRendererFavorite(CellRendererIcon):
__gtype_name__ = 'JournalCellRendererFavorite'
def __init__(self, tree_view):
CellRendererIcon.__init__(self, tree_view)
self.props.width = style.GRID_CELL_SIZE
self.props.height = style.GRID_CELL_SIZE
self.props.size = style.SMALL_ICON_SIZE
self.props.icon_name = 'emblem-favorite'
self.props.mode = Gtk.CellRendererMode.ACTIVATABLE
prelit_color = profile.get_color()
self.props.prelit_stroke_color = prelit_color.get_stroke_color()
self.props.prelit_fill_color = prelit_color.get_fill_color()
class CellRendererDetail(CellRendererIcon):
__gtype_name__ = 'JournalCellRendererDetail'
def __init__(self, tree_view):
CellRendererIcon.__init__(self, tree_view)
self.props.width = style.GRID_CELL_SIZE
self.props.height = style.GRID_CELL_SIZE
self.props.size = style.SMALL_ICON_SIZE
self.props.icon_name = 'go-right'
self.props.mode = Gtk.CellRendererMode.ACTIVATABLE
self.props.stroke_color = style.COLOR_TRANSPARENT.get_svg()
self.props.fill_color = style.COLOR_BUTTON_GREY.get_svg()
self.props.prelit_stroke_color = style.COLOR_TRANSPARENT.get_svg()
self.props.prelit_fill_color = style.COLOR_BLACK.get_svg()
class CellRendererActivityIcon(CellRendererIcon):
__gtype_name__ = 'JournalCellRendererActivityIcon'
__gsignals__ = {
'detail-clicked': (GObject.SignalFlags.RUN_FIRST, None,
([str])),
'volume-error': (GObject.SignalFlags.RUN_FIRST, None,
([str, str])),
}
def __init__(self, journalactivity, tree_view):
self._journalactivity = journalactivity
self._show_palette = True
CellRendererIcon.__init__(self, tree_view)
self.props.width = style.GRID_CELL_SIZE
self.props.height = style.GRID_CELL_SIZE
self.props.size = style.STANDARD_ICON_SIZE
self.props.mode = Gtk.CellRendererMode.ACTIVATABLE
self.tree_view = tree_view
def create_palette(self):
if not self._show_palette:
return None
if self._journalactivity.get_list_view().is_dragging():
return None
tree_model = self.tree_view.get_model()
metadata = tree_model.get_metadata(self.props.palette_invoker.path)
palette = ObjectPalette(self._journalactivity, metadata, detail=True)
palette.connect('detail-clicked',
self.__detail_clicked_cb)
palette.connect('volume-error',
self.__volume_error_cb)
return palette
def __detail_clicked_cb(self, palette, uid):
self.emit('detail-clicked', uid)
def __volume_error_cb(self, palette, message, severity):
self.emit('volume-error', message, severity)
def set_show_palette(self, show_palette):
self._show_palette = show_palette
show_palette = GObject.property(type=bool, default=True,
setter=set_show_palette)
class CellRendererBuddy(CellRendererIcon):
__gtype_name__ = 'JournalCellRendererBuddy'
def __init__(self, tree_view, column_index):
CellRendererIcon.__init__(self, tree_view)
self.props.width = style.STANDARD_ICON_SIZE
self.props.height = style.STANDARD_ICON_SIZE
self.props.size = style.STANDARD_ICON_SIZE
self.props.mode = Gtk.CellRendererMode.ACTIVATABLE
self.tree_view = tree_view
self._model_column_index = column_index
def create_palette(self):
tree_model = self.tree_view.get_model()
row = tree_model[self.props.palette_invoker.path]
# FIXME workaround for pygobject bug, see
# https://bugzilla.gnome.org/show_bug.cgi?id=689277
# if row[self._model_column_index] is not None:
# nick, xo_color = row[self._model_column_index]
if row.model.do_get_value(row.iter, self._model_column_index) \
is not None:
nick, xo_color = row.model.do_get_value(
row.iter, self._model_column_index)
return BuddyPalette((nick, xo_color.to_string()))
else:
return None
def set_buddy(self, buddy):
if buddy is None:
self.props.icon_name = None
else:
nick_, xo_color = buddy
self.props.icon_name = 'computer-xo'
self.props.xo_color = xo_color
buddy = GObject.property(type=object, setter=set_buddy)
|
waliens/sldc | refs/heads/master | test/util.py | 1 | import numpy as np
from PIL.Image import fromarray
from PIL.ImageDraw import ImageDraw
from shapely.geometry import Point, Polygon, box
from sldc import Image
def mk_img(w, h, level=0):
return np.ones((w, h)).astype("uint8") * level
def circularity(polygon):
return 4 * np.pi * polygon.area / (polygon.length * polygon.length)
def draw_square(image, side, center, color):
"""Draw a square centered in 'center' and of which the side has 'side'"""
top_left = (center[1] - side / 2, center[0] - side / 2)
top_right = (center[1] + side / 2, center[0] - side / 2)
bottom_left = (center[1] - side / 2, center[0] + side / 2)
bottom_right = (center[1] + side / 2, center[0] + side / 2)
p = Polygon([top_left, top_right, bottom_right, bottom_left, top_left])
return draw_poly(image, p, color)
def draw_square_by_corner(image, side, top_left, color):
top_left = (top_left[1], top_left[0])
top_right = (top_left[0] + side, top_left[1])
bottom_left = (top_left[0], top_left[1] + side)
bottom_right = (top_left[0] + side, top_left[1] + side)
p = Polygon([top_left, top_right, bottom_right, bottom_left, top_left])
return draw_poly(image, p, color)
def draw_circle(image, radius, center, color=255, return_circle=False):
"""Draw a circle of radius 'radius' and centered in 'centered'"""
circle_center = Point(*center)
circle_polygon = circle_center.buffer(radius)
image_out = draw_poly(image, circle_polygon, color)
if return_circle:
return image_out, circle_polygon
else:
return image_out
def draw_poly(image, polygon, color=255):
"""Draw a polygon in the given color at the given location"""
pil_image = fromarray(image)
validated_color = color
draw = ImageDraw(pil_image)
if len(image.shape) > 2 and image.shape[2] > 1:
validated_color = tuple(color)
draw.polygon(polygon.boundary.coords, fill=validated_color, outline=validated_color)
return np.asarray(pil_image)
class NumpyImage(Image):
def __init__(self, np_image):
"""An image represented as a numpy ndarray"""
self._np_image = np_image
@property
def np_image(self):
return self._np_image
@property
def channels(self):
shape = self._np_image.shape
return shape[2] if len(shape) == 3 else 1
@property
def width(self):
return self._np_image.shape[1]
@property
def height(self):
return self._np_image.shape[0]
def relative_error(val, ref):
return np.abs(val - ref) / ref
def draw_multisquare(image, position, size, color_out=255, color_in=255):
"""Draw a square with color 'color_out' and given size at a given position (x, y)
Then draw four square of size (size/5) with color 'color_in' at:
1) coord: (y + (size / 5), x + (size / 5))
2) coord: (y + (size / 5), x + (3 * size / 5))
3) coord: (y + (3 * size / 5), x + (size / 5))
4) coord: (y + (3 * size / 5), x + (3 * size / 5))
"""
x, y = position
small_size = size / 5
image = draw_poly(image, box(x, y, x + size, y + size), color=color_out)
square1 = box(x + small_size, y + small_size, x + 2 * small_size, y + 2 * small_size)
square2 = box(x + 3 * small_size, y + small_size, x + 4 * small_size, y + 2 * small_size)
square3 = box(x + small_size, y + 3 * small_size, x + 2 * small_size, y + 4 * small_size)
square4 = box(x + 3 * small_size, y + 3 * small_size, x + 4 * small_size, y + 4 * small_size)
squares = [square1, square2, square3, square4]
for square in squares:
image = draw_poly(image, square, color=color_in)
return image
def draw_multicircle(image, position, diameter, color_out=255, color_in=255):
"""Draw a circle with color 'color_out' and given diameter at the given position (center of the circle will be at
coordinates (c_x, c_y) = (position[0] + diameter / 2, position[1] + diameter / 2).
Then, draw four circles with color 'color_in' of diameter diameter / 5. Those four circles are located at:
1) coord: (c_x - a, c_y - a)
2) coord: (c_x - a, c_y + a)
3) coord: (c_x + a, c_y - a)
4) coord: (c_x + a, c_y + a)
where a = diameter * cos (45 deg) / 5
"""
x, y = position
radius = diameter / 2
c_x, c_y = x + radius, y + radius
center = (c_x, c_y)
image = draw_circle(image, diameter / 2, center, color=color_out)
center_offset = diameter * np.sqrt(2) / 10
image = draw_circle(image, diameter / 10, (c_x - center_offset, c_y - center_offset), color=color_in)
image = draw_circle(image, diameter / 10, (c_x - center_offset, c_y + center_offset), color=color_in)
image = draw_circle(image, diameter / 10, (c_x + center_offset, c_y - center_offset), color=color_in)
return draw_circle(image, diameter / 10, (c_x + center_offset, c_y + center_offset), color=color_in)
|
bettermirror/wget | refs/heads/master | testenv/Test-pinnedpubkey-hash-no-check-fail-https.py | 2 | #!/usr/bin/env python3
from sys import exit
from test.http_test import HTTPTest
from test.base_test import HTTPS, SKIP_TEST
from misc.wget_file import WgetFile
import os
"""
This test ensures that Wget can download files from HTTPS Servers
"""
if os.getenv('SSL_TESTS') is None:
exit (SKIP_TEST)
############# File Definitions ###############################################
File1 = "Would you like some Tea?"
File2 = "With lemon or cream?"
A_File = WgetFile ("File1", File1)
B_File = WgetFile ("File2", File2)
WGET_OPTIONS = "--no-check-certificate --pinnedpubkey=sha256//invalid"
WGET_URLS = [["File1", "File2"]]
Files = [[A_File, B_File]]
Servers = [HTTPS]
ExpectedReturnCode = 5
ExpectedDownloadedFiles = []
################ Pre and Post Test Hooks #####################################
pre_test = {
"ServerFiles" : Files
}
test_options = {
"WgetCommands" : WGET_OPTIONS,
"Urls" : WGET_URLS
}
post_test = {
"ExpectedFiles" : ExpectedDownloadedFiles,
"ExpectedRetcode" : ExpectedReturnCode
}
err = HTTPTest (
pre_hook=pre_test,
test_params=test_options,
post_hook=post_test,
protocols=Servers
).begin ()
exit (err)
|
MarcosCommunity/odoo | refs/heads/marcos-8.0 | addons/account_payment/wizard/account_payment_populate_statement.py | 274 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import time
from lxml import etree
from openerp.osv import fields, osv
class account_payment_populate_statement(osv.osv_memory):
_name = "account.payment.populate.statement"
_description = "Account Payment Populate Statement"
_columns = {
'lines': fields.many2many('payment.line', 'payment_line_rel_', 'payment_id', 'line_id', 'Payment Lines')
}
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
line_obj = self.pool.get('payment.line')
res = super(account_payment_populate_statement, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=False)
line_ids = line_obj.search(cr, uid, [
('move_line_id.reconcile_id', '=', False),
('bank_statement_line_id', '=', False),
('move_line_id.state','=','valid')])
line_ids.extend(line_obj.search(cr, uid, [
('move_line_id.reconcile_id', '=', False),
('order_id.mode', '=', False),
('move_line_id.state','=','valid')]))
domain = '[("id", "in", '+ str(line_ids)+')]'
doc = etree.XML(res['arch'])
nodes = doc.xpath("//field[@name='lines']")
for node in nodes:
node.set('domain', domain)
res['arch'] = etree.tostring(doc)
return res
def populate_statement(self, cr, uid, ids, context=None):
line_obj = self.pool.get('payment.line')
statement_obj = self.pool.get('account.bank.statement')
statement_line_obj = self.pool.get('account.bank.statement.line')
currency_obj = self.pool.get('res.currency')
if context is None:
context = {}
data = self.read(cr, uid, ids, context=context)[0]
line_ids = data['lines']
if not line_ids:
return {'type': 'ir.actions.act_window_close'}
statement = statement_obj.browse(cr, uid, context['active_id'], context=context)
for line in line_obj.browse(cr, uid, line_ids, context=context):
ctx = context.copy()
ctx['date'] = line.ml_maturity_date # was value_date earlier,but this field exists no more now
amount = currency_obj.compute(cr, uid, line.currency.id,
statement.currency.id, line.amount_currency, context=ctx)
st_line_vals = self._prepare_statement_line_vals(cr, uid, line, amount, statement, context=context)
st_line_id = statement_line_obj.create(cr, uid, st_line_vals, context=context)
line_obj.write(cr, uid, [line.id], {'bank_statement_line_id': st_line_id})
return {'type': 'ir.actions.act_window_close'}
def _prepare_statement_line_vals(self, cr, uid, payment_line, amount,
statement, context=None):
return {
'name': payment_line.order_id.reference or '?',
'amount':-amount,
'partner_id': payment_line.partner_id.id,
'statement_id': statement.id,
'ref': payment_line.communication,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
devopservices/ansible | refs/heads/devel | test/units/TestUtilsStringFunctions.py | 146 | # -*- coding: utf-8 -*-
import unittest
import os
import os.path
import tempfile
import yaml
import passlib.hash
import string
import StringIO
import copy
from nose.plugins.skip import SkipTest
from ansible.utils import string_functions
import ansible.errors
import ansible.constants as C
import ansible.utils.template as template2
from ansible import __version__
import sys
reload(sys)
sys.setdefaultencoding("utf8")
class TestUtilsStringFunctions(unittest.TestCase):
def test_isprintable(self):
self.assertFalse(string_functions.isprintable(chr(7)))
self.assertTrue(string_functions.isprintable('hello'))
def test_count_newlines_from_end(self):
self.assertEqual(string_functions.count_newlines_from_end('foo\n\n\n\n'), 4)
self.assertEqual(string_functions.count_newlines_from_end('\nfoo'), 0)
|
EricForgy/JuliaBox | refs/heads/master | engine/src/juliabox/plugins/db_sqlite3/__init__.py | 8 | __author__ = 'tan'
from impl_sqlite3 import JBoxSQLite3 |
ndardenne/pymatgen | refs/heads/master | pymatgen/analysis/chemenv/utils/chemenv_config.py | 3 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import division, unicode_literals
"""
This module contains the classes for configuration of the chemenv package.
"""
__author__ = "David Waroquiers"
__copyright__ = "Copyright 2012, The Materials Project"
__credits__ = "Geoffroy Hautier"
__version__ = "2.0"
__maintainer__ = "David Waroquiers"
__email__ = "david.waroquiers@gmail.com"
__date__ = "Feb 20, 2016"
from pymatgen.analysis.chemenv.utils.chemenv_errors import ChemenvError
from pymatgen.analysis.chemenv.utils.scripts_utils import strategies_class_lookup
from os.path import expanduser, exists
from os import makedirs
import json
class ChemEnvConfig():
"""
Class used to store the configuration of the chemenv package :
- Materials project access
- ICSD database access
- Default options (strategies, ...)
"""
DEFAULT_PACKAGE_OPTIONS = {'default_strategy': {'strategy': 'SimplestChemenvStrategy',
'strategy_options': {'distance_cutoff': strategies_class_lookup['SimplestChemenvStrategy'].DEFAULT_DISTANCE_CUTOFF,
'angle_cutoff': strategies_class_lookup['SimplestChemenvStrategy'].DEFAULT_ANGLE_CUTOFF,
'additional_condition': strategies_class_lookup['SimplestChemenvStrategy'].DEFAULT_ADDITIONAL_CONDITION,
'continuous_symmetry_measure_cutoff': strategies_class_lookup['SimplestChemenvStrategy'].DEFAULT_CONTINUOUS_SYMMETRY_MEASURE_CUTOFF}},
'default_max_distance_factor': 1.5
}
def __init__(self, materials_project_configuration=None, package_options=None):
self.materials_project_configuration = materials_project_configuration
if package_options is None:
self.package_options = self.DEFAULT_PACKAGE_OPTIONS
else:
self.package_options = package_options
def setup(self):
while True:
print('\n=> Configuration of the ChemEnv package <=')
print('Current configuration :')
if self.has_materials_project_access:
print(' - Access to materials project is configured (add test ?)')
else:
print(' - No access to materials project')
print(' - Package options :')
for key, val in self.package_options.items():
print(' {} : {}'.format(str(key), str(val)))
print('\nChoose in the following :')
print(' <1> + <ENTER> : setup of the access to the materials project database')
print(' <2> + <ENTER> : configuration of the package options (strategy, ...)')
print(' <q> + <ENTER> : quit without saving configuration')
test = raw_input(' <S> + <ENTER> : save configuration and quit\n ... ')
if test == '1':
self.setup_materials_project_configuration()
elif test == '2':
self.setup_package_options()
elif test == 'q':
break
elif test == 'S':
config_file = self.save()
break
else:
print(' ... wrong key, try again ...')
print('')
if test == 'S':
print('Configuration has been saved to file "{}"'.format(config_file))
def setup_materials_project_configuration(self):
api_key = raw_input('\nEnter your Materials Project API key : ')
self.materials_project_configuration = {'api_key': api_key}
@property
def has_materials_project_access(self):
return self.materials_project_configuration is not None
def setup_package_options(self):
self.package_options = self.DEFAULT_PACKAGE_OPTIONS
print('Choose between the following strategies : ')
strategies = list(strategies_class_lookup.keys())
for istrategy, strategy in enumerate(strategies):
print(' <{}> : {}'.format(str(istrategy + 1), strategy))
test = raw_input(' ... ')
self.package_options['default_strategy'] = {'strategy': strategies[int(test) - 1], 'strategy_options': {}}
strategy_class = strategies_class_lookup[strategies[int(test) - 1]]
if len(strategy_class.STRATEGY_OPTIONS) > 0:
for option, option_dict in strategy_class.STRATEGY_OPTIONS.items():
while True:
print(' => Enter value for option "{}" '
'(<ENTER> for default = {})\n'.format(option,
str(option_dict['default'])))
print(' Valid options are :\n')
print(' {}'.format(option_dict['type'].allowed_values))
test = raw_input(' Your choice : ')
if test == '':
self.package_options['default_strategy']['strategy_options'][option] = option_dict['type'](strategy_class.STRATEGY_OPTIONS[option]['default'])
break
try:
self.package_options['default_strategy']['strategy_options'][option] = option_dict['type'](test)
break
except ValueError:
print('Wrong input for option {}'.format(option))
def package_options_description(self):
out = 'Package options :\n'
out += ' - Maximum distance factor : {:.4f}\n'.format(self.package_options['default_max_distance_factor'])
out += ' - Default strategy is "{}" :\n'.format(self.package_options['default_strategy']['strategy'])
strategy_class = strategies_class_lookup[self.package_options['default_strategy']['strategy']]
out += '{}\n'.format(strategy_class.STRATEGY_DESCRIPTION)
out += ' with options :\n'
for option, option_dict in strategy_class.STRATEGY_OPTIONS.items():
out += ' - {} : {}\n'.format(option,
self.package_options['default_strategy']['strategy_options'][option])
return out
def save(self, root_dir=None):
if root_dir is None:
home = expanduser("~")
root_dir = '{}/.chemenv'.format(home)
if not exists(root_dir):
makedirs(root_dir)
config_dict = {'materials_project_configuration': self.materials_project_configuration,
'package_options': self.package_options}
config_file = '{}/config.json'.format(root_dir)
if exists(config_file):
test = raw_input('Overwrite existing configuration ? (<Y> + <ENTER> to confirm)')
if test != 'Y':
print('Configuration not saved')
return config_file
f = open(config_file, 'w')
json.dump(config_dict, f)
f.close()
print('Configuration saved')
return config_file
@classmethod
def auto_load(cls, root_dir=None):
if root_dir is None:
home = expanduser("~")
root_dir = '{}/.chemenv'.format(home)
config_file = '{}/config.json'.format(root_dir)
try:
f = open(config_file, 'r')
config_dict = json.load(f)
f.close()
return ChemEnvConfig(materials_project_configuration=config_dict['materials_project_configuration'],
package_options=config_dict['package_options'])
except IOError:
print('Unable to load configuration from file "{}" ...'.format(config_file))
print(' ... loading default configuration')
return ChemEnvConfig()
@property
def materials_project_api_key(self):
if self.materials_project_configuration is None:
raise ChemenvError('ChemEnvConfig', 'materials_project_api_key', 'No api_key saved')
return self.materials_project_configuration['api_key'] |
reminisce/mxnet | refs/heads/master | python/mxnet/image/__init__.py | 61 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding: utf-8
# pylint: disable=wildcard-import
"""Image Iterators and image augmentation functions"""
from . import image
from .image import *
from . import detection
from . import detection as det
from .detection import *
|
sgraham/nope | refs/heads/master | tools/memory_inspector/memory_inspector/core/backends.py | 89 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
_backends = {} # Maps a string (backend name) to a |Backend| instance.
def Register(backend):
"""Called by each backend module to register upon initialization."""
assert(isinstance(backend, Backend))
_backends[backend.name] = backend
def ListBackends():
"""Enumerates all the backends."""
return _backends.itervalues()
def ListDevices():
"""Enumerates all the devices from all the registered backends."""
for backend in _backends.itervalues():
for device in backend.EnumerateDevices():
assert(isinstance(device, Device))
yield device
def GetBackend(backend_name):
"""Retrieves a specific backend given its name."""
return _backends.get(backend_name, None)
def GetDevice(backend_name, device_id):
"""Retrieves a specific device given its backend name and device id."""
backend = GetBackend(backend_name)
if not backend:
return None
for device in backend.EnumerateDevices():
if device.id == device_id:
return device
return None
# The classes below model the contract interfaces exposed to the frontends and
# implemented by each concrete backend.
class Backend(object):
"""Base class for backends.
This is the extension point for the OS-specific profiler implementations.
"""
def __init__(self, settings=None):
# Initialize with empty settings if not required by the overriding backend.
self.settings = settings or Settings()
def EnumerateDevices(self):
"""Enumeates the devices discovered and supported by the backend.
Returns:
A sequence of |Device| instances.
"""
raise NotImplementedError()
def ExtractSymbols(self, native_heaps, sym_paths):
"""Performs symbolization. Returns a |symbol.Symbols| from |NativeHeap|s."""
raise NotImplementedError()
@property
def name(self):
"""A unique name which identifies the backend.
Typically this will just return the target OS name, e.g., 'Android'."""
raise NotImplementedError()
class Device(object):
"""Interface contract for devices enumerated by a backend."""
def __init__(self, backend, settings=None):
self.backend = backend
# Initialize with empty settings if not required by the overriding device.
self.settings = settings or Settings()
def Initialize(self):
"""Called before anything else, for initial provisioning."""
raise NotImplementedError()
def IsNativeTracingEnabled(self):
"""Check if the device is ready to capture native allocation traces."""
raise NotImplementedError()
def EnableNativeTracing(self, enabled):
"""Provision the device and make it ready to trace native allocations."""
raise NotImplementedError()
def ListProcesses(self):
"""Returns a sequence of |Process|."""
raise NotImplementedError()
def GetProcess(self, pid):
"""Returns an instance of |Process| or None (if not found)."""
raise NotImplementedError()
def GetStats(self):
"""Returns an instance of |DeviceStats|."""
raise NotImplementedError()
@property
def name(self):
"""Friendly name of the target device (e.g., phone model)."""
raise NotImplementedError()
@property
def id(self):
"""Unique identifier (within the backend) of the device (e.g., S/N)."""
raise NotImplementedError()
class Process(object):
"""Interface contract for each running process."""
def __init__(self, device, pid, name):
assert(isinstance(device, Device))
assert(isinstance(pid, int))
self.device = device
self.pid = pid
self.name = name
def DumpMemoryMaps(self):
"""Returns an instance of |memory_map.Map|."""
raise NotImplementedError()
def DumpNativeHeap(self):
"""Returns an instance of |native_heap.NativeHeap|."""
raise NotImplementedError()
def Freeze(self):
"""Stops the process and all its threads."""
raise NotImplementedError()
def Unfreeze(self):
"""Resumes the process."""
raise NotImplementedError()
def GetStats(self):
"""Returns an instance of |ProcessStats|."""
raise NotImplementedError()
def __str__(self):
return '[%d] %s' % (self.pid, self.name)
class DeviceStats(object):
"""CPU/Memory stats for a |Device|."""
def __init__(self, uptime, cpu_times, memory_stats):
"""Args:
uptime: uptime in seconds.
cpu_times: array (CPUs) of dicts (cpu times since last call).
e.g., [{'User': 10, 'System': 80, 'Idle': 10}, ... ]
memory_stats: Dictionary of memory stats. e.g., {'Free': 1, 'Cached': 10}
"""
assert(isinstance(cpu_times, list) and isinstance(cpu_times[0], dict))
assert(isinstance(memory_stats, dict))
self.uptime = uptime
self.cpu_times = cpu_times
self.memory_stats = memory_stats
class ProcessStats(object):
"""CPU/Memory stats for a |Process|."""
def __init__(self, threads, run_time, cpu_usage, vm_rss, page_faults):
"""Args:
threads: Number of threads.
run_time: Total process uptime in seconds.
cpu_usage: CPU usage [0-100] since the last GetStats call.
vm_rss_kb: Resident Memory Set in Kb.
page_faults: Number of VM page faults (hard + soft).
"""
self.threads = threads
self.run_time = run_time
self.cpu_usage = cpu_usage
self.vm_rss = vm_rss
self.page_faults = page_faults
class Settings(object):
"""Models user-definable settings for backends and devices."""
def __init__(self, expected_keys=None):
"""Args:
expected_keys: A dict. (key-name -> description) of expected settings
"""
self.expected_keys = expected_keys or {}
self.values = dict((k, '') for k in self.expected_keys.iterkeys())
def __getitem__(self, key):
assert(key in self.expected_keys), 'Unexpected setting: ' + key
return self.values.get(key)
def __setitem__(self, key, value):
assert(key in self.expected_keys), 'Unexpected setting: ' + key
self.values[key] = value
|
lcgong/alchemy | refs/heads/master | appserv/t.py | 2 | # function hash (str) {
# return crypto
# .createHash('sha1')
# .update(str, 'ascii')
# .digest('base64')
# .replace(PLUS_GLOBAL_REGEXP, '-')
# .replace(SLASH_GLOBAL_REGEXP, '_')
# .replace(EQUAL_GLOBAL_REGEXP, '')
# # }
# salt + '-' + hash(salt + '-' + secret)
secure = 'DjwennlKciQiTlxKmYtWqH8NG7Lnf7Y8vDcyjxlg'
token = 'X1KfgR1J-OgSnojv73LpcSlOZ_AcX0Pv3H2A'
verifyCRSFToken(token, secure)
# salt + '-' +
# token[0, token.indexOf('-')]
|
supriyantomaftuh/roboto | refs/heads/master | scripts/lib/fontbuild/curveFitPen.py | 4 | #! /opt/local/bin/pythonw2.7
#
# 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.
__all__ = ["SubsegmentPen","SubsegmentsToCurvesPen", "segmentGlyph", "fitGlyph"]
from fontTools.pens.basePen import BasePen
from fontTools.misc import bezierTools
from robofab.pens.pointPen import AbstractPointPen
from robofab.pens.adapterPens import PointToSegmentPen, GuessSmoothPointPen
import numpy as np
from numpy.linalg import norm
from numpy import array as v
from random import random
from robofab.pens.pointPen import BasePointToSegmentPen
class SubsegmentsToCurvesPointPen(BasePointToSegmentPen):
def __init__(self, glyph, subsegmentGlyph, subsegments):
BasePointToSegmentPen.__init__(self)
self.glyph = glyph
self.subPen = SubsegmentsToCurvesPen(None, glyph.getPen(), subsegmentGlyph, subsegments)
def setMatchTangents(self, b):
self.subPen.matchTangents = b
def _flushContour(self, segments):
#
# adapted from robofab.pens.adapterPens.rfUFOPointPen
#
assert len(segments) >= 1
# if we only have one point and it has a name, we must have an anchor
first = segments[0]
segmentType, points = first
pt, smooth, name, kwargs = points[0]
if len(segments) == 1 and name != None:
self.glyph.appendAnchor(name, pt)
return
else:
segmentType, points = segments[-1]
movePt, smooth, name, kwargs = points[-1]
if smooth:
# last point is smooth, set pen to start smooth
self.subPen.setLastSmooth(True)
if segmentType == 'line':
del segments[-1]
self.subPen.moveTo(movePt)
# do the rest of the segments
for segmentType, points in segments:
isSmooth = True in [smooth for pt, smooth, name, kwargs in points]
pp = [pt for pt, smooth, name, kwargs in points]
if segmentType == "line":
assert len(pp) == 1
if isSmooth:
self.subPen.smoothLineTo(pp[0])
else:
self.subPen.lineTo(pp[0])
elif segmentType == "curve":
assert len(pp) == 3
if isSmooth:
self.subPen.smoothCurveTo(*pp)
else:
self.subPen.curveTo(*pp)
elif segmentType == "qcurve":
assert 0, "qcurve not supported"
else:
assert 0, "illegal segmentType: %s" % segmentType
self.subPen.closePath()
def addComponent(self, glyphName, transform):
self.subPen.addComponent(glyphName, transform)
class SubsegmentsToCurvesPen(BasePen):
def __init__(self, glyphSet, otherPen, subsegmentGlyph, subsegments):
BasePen.__init__(self, None)
self.otherPen = otherPen
self.ssglyph = subsegmentGlyph
self.subsegments = subsegments
self.contourIndex = -1
self.segmentIndex = -1
self.lastPoint = (0,0)
self.lastSmooth = False
self.nextSmooth = False
def setLastSmooth(self, b):
self.lastSmooth = b
def _moveTo(self, (x, y)):
self.contourIndex += 1
self.segmentIndex = 0
self.startPoint = (x,y)
p = self.ssglyph.contours[self.contourIndex][0].points[0]
self.otherPen.moveTo((p.x, p.y))
self.lastPoint = (x,y)
def _lineTo(self, (x, y)):
self.segmentIndex += 1
index = self.subsegments[self.contourIndex][self.segmentIndex][0]
p = self.ssglyph.contours[self.contourIndex][index].points[0]
self.otherPen.lineTo((p.x, p.y))
self.lastPoint = (x,y)
self.lastSmooth = False
def smoothLineTo(self, (x, y)):
self.lineTo((x,y))
self.lastSmooth = True
def smoothCurveTo(self, (x1, y1), (x2, y2), (x3, y3)):
self.nextSmooth = True
self.curveTo((x1, y1), (x2, y2), (x3, y3))
self.nextSmooth = False
self.lastSmooth = True
def _curveToOne(self, (x1, y1), (x2, y2), (x3, y3)):
self.segmentIndex += 1
c = self.ssglyph.contours[self.contourIndex]
n = len(c)
startIndex = (self.subsegments[self.contourIndex][self.segmentIndex-1][0])
segmentCount = (self.subsegments[self.contourIndex][self.segmentIndex][1])
endIndex = (startIndex + segmentCount + 1) % (n)
indices = [(startIndex + i) % (n) for i in range(segmentCount + 1)]
points = np.array([(c[i].points[0].x, c[i].points[0].y) for i in indices])
prevPoint = (c[(startIndex - 1)].points[0].x, c[(startIndex - 1)].points[0].y)
nextPoint = (c[(endIndex) % n].points[0].x, c[(endIndex) % n].points[0].y)
prevTangent = prevPoint - points[0]
nextTangent = nextPoint - points[-1]
tangent1 = points[1] - points[0]
tangent3 = points[-2] - points[-1]
prevTangent /= np.linalg.norm(prevTangent)
nextTangent /= np.linalg.norm(nextTangent)
tangent1 /= np.linalg.norm(tangent1)
tangent3 /= np.linalg.norm(tangent3)
tangent1, junk = self.smoothTangents(tangent1, prevTangent, self.lastSmooth)
tangent3, junk = self.smoothTangents(tangent3, nextTangent, self.nextSmooth)
if self.matchTangents == True:
cp = fitBezier(points, tangent1, tangent3)
cp[1] = norm(cp[1] - cp[0]) * tangent1 / norm(tangent1) + cp[0]
cp[2] = norm(cp[2] - cp[3]) * tangent3 / norm(tangent3) + cp[3]
else:
cp = fitBezier(points)
# if self.ssglyph.name == 'r':
# print "-----------"
# print self.lastSmooth, self.nextSmooth
# print "%i %i : %i %i \n %i %i : %i %i \n %i %i : %i %i"%(x1,y1, cp[1,0], cp[1,1], x2,y2, cp[2,0], cp[2,1], x3,y3, cp[3,0], cp[3,1])
self.otherPen.curveTo((cp[1,0], cp[1,1]), (cp[2,0], cp[2,1]), (cp[3,0], cp[3,1]))
self.lastPoint = (x3, y3)
self.lastSmooth = False
def smoothTangents(self,t1,t2,forceSmooth = False):
if forceSmooth or (abs(t1.dot(t2)) > .95 and norm(t1-t2) > 1):
# print t1,t2,
t1 = (t1 - t2) / 2
t2 = -t1
# print t1,t2
return t1 / norm(t1), t2 / norm(t2)
def _closePath(self):
self.otherPen.closePath()
def _endPath(self):
self.otherPen.endPath()
def addComponent(self, glyphName, transformation):
self.otherPen.addComponent(glyphName, transformation)
class SubsegmentPointPen(BasePointToSegmentPen):
def __init__(self, glyph, resolution):
BasePointToSegmentPen.__init__(self)
self.glyph = glyph
self.resolution = resolution
self.subPen = SubsegmentPen(None, glyph.getPen())
def getSubsegments(self):
return self.subPen.subsegments[:]
def _flushContour(self, segments):
#
# adapted from robofab.pens.adapterPens.rfUFOPointPen
#
assert len(segments) >= 1
# if we only have one point and it has a name, we must have an anchor
first = segments[0]
segmentType, points = first
pt, smooth, name, kwargs = points[0]
if len(segments) == 1 and name != None:
self.glyph.appendAnchor(name, pt)
return
else:
segmentType, points = segments[-1]
movePt, smooth, name, kwargs = points[-1]
if segmentType == 'line':
del segments[-1]
self.subPen.moveTo(movePt)
# do the rest of the segments
for segmentType, points in segments:
points = [pt for pt, smooth, name, kwargs in points]
if segmentType == "line":
assert len(points) == 1
self.subPen.lineTo(points[0])
elif segmentType == "curve":
assert len(points) == 3
self.subPen.curveTo(*points)
elif segmentType == "qcurve":
assert 0, "qcurve not supported"
else:
assert 0, "illegal segmentType: %s" % segmentType
self.subPen.closePath()
def addComponent(self, glyphName, transform):
self.subPen.addComponent(glyphName, transform)
class SubsegmentPen(BasePen):
def __init__(self, glyphSet, otherPen, resolution=25):
BasePen.__init__(self,glyphSet)
self.resolution = resolution
self.otherPen = otherPen
self.subsegments = []
self.startContour = (0,0)
self.contourIndex = -1
def _moveTo(self, (x, y)):
self.contourIndex += 1
self.segmentIndex = 0
self.subsegments.append([])
self.subsegmentCount = 0
self.subsegments[self.contourIndex].append([self.subsegmentCount, 0])
self.startContour = (x,y)
self.lastPoint = (x,y)
self.otherPen.moveTo((x,y))
def _lineTo(self, (x, y)):
count = self.stepsForSegment((x,y),self.lastPoint)
if count < 1:
count = 1
self.subsegmentCount += count
self.subsegments[self.contourIndex].append([self.subsegmentCount, count])
for i in range(1,count+1):
x1 = self.lastPoint[0] + (x - self.lastPoint[0]) * i/float(count)
y1 = self.lastPoint[1] + (y - self.lastPoint[1]) * i/float(count)
self.otherPen.lineTo((x1,y1))
self.lastPoint = (x,y)
def _curveToOne(self, (x1, y1), (x2, y2), (x3, y3)):
count = self.stepsForSegment((x3,y3),self.lastPoint)
if count < 2:
count = 2
self.subsegmentCount += count
self.subsegments[self.contourIndex].append([self.subsegmentCount,count])
x = self.renderCurve((self.lastPoint[0],x1,x2,x3),count)
y = self.renderCurve((self.lastPoint[1],y1,y2,y3),count)
assert len(x) == count
if (x3 == self.startContour[0] and y3 == self.startContour[1]):
count -= 1
for i in range(count):
self.otherPen.lineTo((x[i],y[i]))
self.lastPoint = (x3,y3)
def _closePath(self):
if not (self.lastPoint[0] == self.startContour[0] and self.lastPoint[1] == self.startContour[1]):
self._lineTo(self.startContour)
self.otherPen.closePath()
def _endPath(self):
self.otherPen.endPath()
def addComponent(self, glyphName, transformation):
self.otherPen.addComponent(glyphName, transformation)
def stepsForSegment(self, p1, p2):
dist = np.linalg.norm(v(p1) - v(p2))
out = int(dist / self.resolution)
return out
def renderCurve(self,p,count):
curvePoints = []
t = 1.0 / float(count)
temp = t * t
f = p[0]
fd = 3 * (p[1] - p[0]) * t
fdd_per_2 = 3 * (p[0] - 2 * p[1] + p[2]) * temp
fddd_per_2 = 3 * (3 * (p[1] - p[2]) + p[3] - p[0]) * temp * t
fddd = fddd_per_2 + fddd_per_2
fdd = fdd_per_2 + fdd_per_2
fddd_per_6 = fddd_per_2 * (1.0 / 3)
for i in range(count):
f = f + fd + fdd_per_2 + fddd_per_6
fd = fd + fdd + fddd_per_2
fdd = fdd + fddd
fdd_per_2 = fdd_per_2 + fddd_per_2
curvePoints.append(f)
return curvePoints
def fitBezierSimple(pts):
T = [np.linalg.norm(pts[i]-pts[i-1]) for i in range(1,len(pts))]
tsum = np.sum(T)
T = [0] + T
T = [np.sum(T[0:i+1])/tsum for i in range(len(pts))]
T = [[t**3, t**2, t, 1] for t in T]
T = np.array(T)
M = np.array([[-1, 3, -3, 1],
[ 3, -6, 3, 0],
[-3, 3, 0, 0],
[ 1, 0, 0, 0]])
T = T.dot(M)
T = np.concatenate((T, np.array([[100,0,0,0], [0,0,0,100]])))
# pts = np.vstack((pts, pts[0] * 100, pts[-1] * 100))
C = np.linalg.lstsq(T, pts)
return C[0]
def subdivideLineSegment(pts):
out = [pts[0]]
for i in range(1, len(pts)):
out.append(pts[i-1] + (pts[i] - pts[i-1]) * .5)
out.append(pts[i])
return np.array(out)
def fitBezier(pts,tangent0=None,tangent3=None):
if len(pts < 4):
pts = subdivideLineSegment(pts)
T = [np.linalg.norm(pts[i]-pts[i-1]) for i in range(1,len(pts))]
tsum = np.sum(T)
T = [0] + T
T = [np.sum(T[0:i+1])/tsum for i in range(len(pts))]
T = [[t**3, t**2, t, 1] for t in T]
T = np.array(T)
M = np.array([[-1, 3, -3, 1],
[ 3, -6, 3, 0],
[-3, 3, 0, 0],
[ 1, 0, 0, 0]])
T = T.dot(M)
n = len(pts)
pout = pts.copy()
pout[:,0] -= (T[:,0] * pts[0,0]) + (T[:,3] * pts[-1,0])
pout[:,1] -= (T[:,0] * pts[0,1]) + (T[:,3] * pts[-1,1])
TT = np.zeros((n*2,4))
for i in range(n):
for j in range(2):
TT[i*2,j*2] = T[i,j+1]
TT[i*2+1,j*2+1] = T[i,j+1]
pout = pout.reshape((n*2,1),order="C")
if tangent0 != None and tangent3 != None:
tangentConstraintsT = np.array([
[tangent0[1], -tangent0[0], 0, 0],
[0, 0, tangent3[1], -tangent3[0]]
])
tangentConstraintsP = np.array([
[pts[0][1] * -tangent0[0] + pts[0][0] * tangent0[1]],
[pts[-1][1] * -tangent3[0] + pts[-1][0] * tangent3[1]]
])
TT = np.concatenate((TT, tangentConstraintsT * 1000))
pout = np.concatenate((pout, tangentConstraintsP * 1000))
C = np.linalg.lstsq(TT,pout)[0].reshape((2,2))
return np.array([pts[0], C[0], C[1], pts[-1]])
def segmentGlyph(glyph,resolution=50):
g1 = glyph.copy()
g1.clear()
dp = SubsegmentPointPen(g1, resolution)
glyph.drawPoints(dp)
return g1, dp.getSubsegments()
def fitGlyph(glyph, subsegmentGlyph, subsegmentIndices, matchTangents=True):
outGlyph = glyph.copy()
outGlyph.clear()
fitPen = SubsegmentsToCurvesPointPen(outGlyph, subsegmentGlyph, subsegmentIndices)
fitPen.setMatchTangents(matchTangents)
# smoothPen = GuessSmoothPointPen(fitPen)
glyph.drawPoints(fitPen)
outGlyph.width = subsegmentGlyph.width
return outGlyph
if __name__ == '__main__':
p = SubsegmentPen(None, None)
pts = np.array([
[0,0],
[.5,.5],
[.5,.5],
[1,1]
])
print np.array(p.renderCurve(pts,10)) * 10
|
pepeportela/edx-platform | refs/heads/master | common/lib/capa/capa/inputtypes.py | 8 | #
# File: courseware/capa/inputtypes.py
#
"""
Module containing the problem elements which render into input objects
- textline
- textbox (aka codeinput)
- schematic
- choicegroup (aka radiogroup, checkboxgroup)
- imageinput (for clickable image)
- optioninput (for option list)
- filesubmission (upload a file)
- crystallography
- vsepr_input
- drag_and_drop
- formulaequationinput
- chemicalequationinput
These are matched by *.html files templates/*.html which are mako templates with the
actual html.
Each input type takes the xml tree as 'element', the previous answer as 'value', and the
graded status as'status'
"""
# TODO: make hints do something
# TODO: make all inputtypes actually render msg
# TODO: remove unused fields (e.g. 'hidden' in a few places)
# TODO: add validators so that content folks get better error messages.
# Possible todo: make inline the default for textlines and other "one-line" inputs. It probably
# makes sense, but a bunch of problems have markup that assumes block. Bigger TODO: figure out a
# general css and layout strategy for capa, document it, then implement it.
import json
import logging
import re
import shlex # for splitting quoted strings
import sys
import time
from datetime import datetime
import bleach
import html5lib
import pyparsing
from lxml import etree
import xqueue_interface
from calc.preview import latex_preview
from capa.xqueue_interface import XQUEUE_TIMEOUT
from chem import chemcalc
from openedx.core.djangolib.markup import HTML, Text
from xmodule.stringify import stringify_children
from .registry import TagRegistry
from .util import sanitize_html
log = logging.getLogger(__name__)
#########################################################################
registry = TagRegistry() # pylint: disable=invalid-name
class Status(object):
"""
Problem status
attributes: classname, display_name, display_tooltip
"""
css_classes = {
# status: css class
'unsubmitted': 'unanswered',
'incomplete': 'incorrect',
'queued': 'processing',
}
__slots__ = ('classname', '_status', 'display_name', 'display_tooltip')
def __init__(self, status, gettext_func=unicode):
self.classname = self.css_classes.get(status, status)
_ = gettext_func
names = {
'correct': _('correct'),
'incorrect': _('incorrect'),
'partially-correct': _('partially correct'),
'incomplete': _('incomplete'),
'unanswered': _('unanswered'),
'unsubmitted': _('unanswered'),
'submitted': _('submitted'),
'queued': _('processing'),
}
tooltips = {
# Translators: these are tooltips that indicate the state of an assessment question
'correct': _('This answer is correct.'),
'incorrect': _('This answer is incorrect.'),
'partially-correct': _('This answer is partially correct.'),
'queued': _('This answer is being processed.'),
}
tooltips.update(
dict.fromkeys(
['incomplete', 'unanswered', 'unsubmitted'], _('Not yet answered.')
)
)
self.display_name = names.get(status, unicode(status))
self.display_tooltip = tooltips.get(status, u'')
self._status = status or ''
def __str__(self):
return self._status
def __unicode__(self):
return self._status.decode('utf8')
def __repr__(self):
return 'Status(%r)' % self._status
def __eq__(self, other):
return self._status == str(other)
class Attribute(object):
"""
Allows specifying required and optional attributes for input types.
"""
# want to allow default to be None, but also allow required objects
_sentinel = object()
def __init__(self, name, default=_sentinel, transform=None, validate=None, render=True):
"""
Define an attribute
name (str): then name of the attribute--should be alphanumeric (valid for an XML attribute)
default (any type): If not specified, this attribute is required. If specified, use this as the default value
if the attribute is not specified. Note that this value will not be transformed or validated.
transform (function str -> any type): If not None, will be called to transform the parsed value into an internal
representation.
validate (function str-or-return-type-of-tranform -> unit or exception): If not None, called to validate the
(possibly transformed) value of the attribute. Should raise ValueError with a helpful message if
the value is invalid.
render (bool): if False, don't include this attribute in the template context.
"""
self.name = name
self.default = default
self.validate = validate
self.transform = transform
self.render = render
def parse_from_xml(self, element):
"""
Given an etree xml element that should have this attribute, do the obvious thing:
- look for it. raise ValueError if not found and required.
- transform and validate. pass through any exceptions from transform or validate.
"""
val = element.get(self.name)
if self.default == self._sentinel and val is None:
raise ValueError(
'Missing required attribute {0}.'.format(self.name)
)
if val is None:
# not required, so return default
return self.default
if self.transform is not None:
val = self.transform(val)
if self.validate is not None:
self.validate(val)
return val
class InputTypeBase(object):
"""
Abstract base class for input types.
"""
template = None
def __init__(self, system, xml, state):
"""
Instantiate an InputType class. Arguments:
- system : LoncapaModule instance which provides OS, rendering, and user context.
Specifically, must have a render_template function.
- xml : Element tree of this Input element
- state : a dictionary with optional keys:
* 'value' -- the current value of this input
(what the student entered last time)
* 'id' -- the id of this input, typically
"{problem-location}_{response-num}_{input-num}"
* 'status' (submitted, unanswered, unsubmitted)
* 'input_state' -- dictionary containing any inputtype-specific state
that has been preserved
* 'feedback' (dictionary containing keys for hints, errors, or other
feedback from previous attempt. Specifically 'message', 'hint',
'hintmode'. If 'hintmode' is 'always', the hint is always displayed.)
"""
self.xml = xml
self.tag = xml.tag
self.capa_system = system
# NOTE: ID should only come from one place. If it comes from multiple,
# we use state first, XML second (in case the xml changed, but we have
# existing state with an old id). Since we don't make this guarantee,
# we can swap this around in the future if there's a more logical
# order.
self.input_id = state.get('id', xml.get('id'))
if self.input_id is None:
raise ValueError(
"input id state is None. xml is {0}".format(etree.tostring(xml))
)
self.value = state.get('value', '')
feedback = state.get('feedback', {})
self.msg = feedback.get('message', '')
self.hint = feedback.get('hint', '')
self.hintmode = feedback.get('hintmode', None)
self.input_state = state.get('input_state', {})
self.answervariable = state.get('answervariable', None)
self.response_data = state.get('response_data')
# put hint above msg if it should be displayed
if self.hintmode == 'always':
self.msg = HTML('{hint}<br/>{msg}' if self.msg else '{hint}').format(hint=HTML(self.hint),
msg=HTML(self.msg))
self.status = state.get('status', 'unanswered')
try:
# Pre-parse and process all the declared requirements.
self.process_requirements()
# Call subclass "constructor" -- means they don't have to worry about calling
# super().__init__, and are isolated from changes to the input
# constructor interface.
self.setup()
except Exception as err:
# Something went wrong: add xml to message, but keep the traceback
msg = u"Error in xml '{x}': {err} ".format(
x=etree.tostring(xml), err=err.message)
raise Exception, msg, sys.exc_info()[2]
@classmethod
def get_attributes(cls):
"""
Should return a list of Attribute objects (see docstring there for details). Subclasses should override. e.g.
return [Attribute('unicorn', True), Attribute('num_dragons', 12, transform=int), ...]
"""
return []
def process_requirements(self):
"""
Subclasses can declare lists of required and optional attributes. This
function parses the input xml and pulls out those attributes. This
isolates most simple input types from needing to deal with xml parsing at all.
Processes attributes, putting the results in the self.loaded_attributes dictionary. Also creates a set
self.to_render, containing the names of attributes that should be included in the context by default.
"""
# Use local dicts and sets so that if there are exceptions, we don't
# end up in a partially-initialized state.
loaded = {}
to_render = set()
for attribute in self.get_attributes():
loaded[attribute.name] = attribute.parse_from_xml(self.xml)
if attribute.render:
to_render.add(attribute.name)
self.loaded_attributes = loaded
self.to_render = to_render
def setup(self):
"""
InputTypes should override this to do any needed initialization. It is called after the
constructor, so all base attributes will be set.
If this method raises an exception, it will be wrapped with a message that includes the
problem xml.
"""
pass
def handle_ajax(self, dispatch, data):
"""
InputTypes that need to handle specialized AJAX should override this.
Input:
dispatch: a string that can be used to determine how to handle the data passed in
data: a dictionary containing the data that was sent with the ajax call
Output:
a dictionary object that can be serialized into JSON. This will be sent back to the Javascript.
"""
pass
def _get_render_context(self):
"""
Should return a dictionary of keys needed to render the template for the input type.
(Separate from get_html to faciliate testing of logic separately from the rendering)
The default implementation gets the following rendering context: basic things like value, id, status, and msg,
as well as everything in self.loaded_attributes, and everything returned by self._extra_context().
This means that input types that only parse attributes and pass them to the template get everything they need,
and don't need to override this method.
"""
context = {
'id': self.input_id,
'value': self.value,
'status': Status(self.status, self.capa_system.i18n.ugettext),
'msg': self.msg,
'response_data': self.response_data,
'STATIC_URL': self.capa_system.STATIC_URL,
'describedby_html': HTML(''),
}
# Generate the list of ids to be used with the aria-describedby field.
descriptions = list()
# If there is trailing text, add the id as the first element to the list before adding the status id
if 'trailing_text' in self.loaded_attributes and self.loaded_attributes['trailing_text']:
trailing_text_id = 'trailing_text_' + self.input_id
descriptions.append(trailing_text_id)
# Every list should contain the status id
status_id = 'status_' + self.input_id
descriptions.append(status_id)
descriptions.extend(self.response_data.get('descriptions', {}).keys())
description_ids = ' '.join(descriptions)
context.update(
{'describedby_html': HTML('aria-describedby="{}"').format(description_ids)}
)
context.update(
(a, v) for (a, v) in self.loaded_attributes.iteritems() if a in self.to_render
)
context.update(self._extra_context())
if self.answervariable:
context.update({'answervariable': self.answervariable})
return context
def _extra_context(self):
"""
Subclasses can override this to return extra context that should be passed to their templates for rendering.
This is useful when the input type requires computing new template variables from the parsed attributes.
"""
return {}
def get_html(self):
"""
Return the html for this input, as an etree element.
"""
if self.template is None:
raise NotImplementedError("no rendering template specified for class {0}"
.format(self.__class__))
context = self._get_render_context()
html = self.capa_system.render_template(self.template, context).strip()
try:
output = etree.XML(html)
except etree.XMLSyntaxError as ex:
# If `html` contains attrs with no values, like `controls` in <audio controls src='smth'/>,
# XML parser will raise exception, so wee fallback to html5parser, which will set empty "" values for such attrs.
try:
output = html5lib.parseFragment(html, treebuilder='lxml', namespaceHTMLElements=False)[0]
except IndexError:
raise ex
return output
def get_user_visible_answer(self, internal_answer):
"""
Given the internal representation of the answer provided by the user, return the representation of the answer
as the user saw it. Subclasses should override this method if and only if the internal represenation of the
answer is different from the answer that is displayed to the user.
"""
return internal_answer
#-----------------------------------------------------------------------------
@registry.register
class OptionInput(InputTypeBase):
"""
Input type for selecting and Select option input type.
Example:
<optioninput options="('Up','Down')" correct="Up"/><text>The location of the sky</text>
# TODO: allow ordering to be randomized
"""
template = "optioninput.html"
tags = ['optioninput']
@staticmethod
def parse_options(options):
"""
Given options string, convert it into an ordered list of (option_id, option_description) tuples, where
id==description for now. TODO: make it possible to specify different id and descriptions.
"""
# convert single quotes inside option values to html encoded string
options = re.sub(r"([a-zA-Z])('|\\')([a-zA-Z])", r"\1'\3", options)
options = re.sub(r"\\'", r"'", options) # replace already escaped single quotes
# parse the set of possible options
lexer = shlex.shlex(options[1:-1].encode('utf8'))
lexer.quotes = "'"
# Allow options to be separated by whitespace as well as commas
lexer.whitespace = ", "
# remove quotes
# convert escaped single quotes (html encoded string) back to single quotes
tokens = [x[1:-1].decode('utf8').replace("'", "'") for x in lexer]
# make list of (option_id, option_description), with description=id
return [(t, t) for t in tokens]
@classmethod
def get_attributes(cls):
"""
Convert options to a convenient format.
"""
return [Attribute('options', transform=cls.parse_options),
Attribute('inline', False)]
def _extra_context(self):
"""
Return extra context.
"""
_ = self.capa_system.i18n.ugettext
return {'default_option_text': _('Select an option')}
#-----------------------------------------------------------------------------
# TODO: consolidate choicegroup, radiogroup, checkboxgroup after discussion of
# desired semantics.
@registry.register
class ChoiceGroup(InputTypeBase):
"""
Radio button or checkbox inputs: multiple choice or true/false
TODO: allow order of choices to be randomized, following lon-capa spec. Use
"location" attribute, ie random, top, bottom.
Example:
<choicegroup>
<choice correct="false" name="foil1">
<text>This is foil One.</text>
</choice>
<choice correct="false" name="foil2">
<text>This is foil Two.</text>
</choice>
<choice correct="true" name="foil3">
<text>This is foil Three.</text>
</choice>
</choicegroup>
"""
template = "choicegroup.html"
tags = ['choicegroup', 'radiogroup', 'checkboxgroup']
def setup(self):
i18n = self.capa_system.i18n
# suffix is '' or [] to change the way the input is handled in --as a scalar or vector
# value. (VS: would be nice to make this less hackish).
if self.tag == 'choicegroup':
self.suffix = ''
self.html_input_type = "radio"
elif self.tag == 'radiogroup':
self.html_input_type = "radio"
self.suffix = '[]'
elif self.tag == 'checkboxgroup':
self.html_input_type = "checkbox"
self.suffix = '[]'
else:
_ = i18n.ugettext
# Translators: 'ChoiceGroup' is an input type and should not be translated.
msg = _("ChoiceGroup: unexpected tag {tag_name}").format(tag_name=self.tag)
raise Exception(msg)
self.choices = self.extract_choices(self.xml, i18n)
self._choices_map = dict(self.choices,)
@classmethod
def get_attributes(cls):
# Make '_' a no-op so we can scrape strings. Using lambda instead of
# `django.utils.translation.ugettext_noop` because Django cannot be imported in this file
_ = lambda text: text
return [Attribute("show_correctness", "always"),
Attribute("submitted_message", _("Answer received."))]
def _extra_context(self):
return {'input_type': self.html_input_type,
'choices': self.choices,
'name_array_suffix': self.suffix}
@staticmethod
def extract_choices(element, i18n):
"""
Extracts choices for a few input types, such as ChoiceGroup, RadioGroup and
CheckboxGroup.
returns list of (choice_name, choice_text) tuples
TODO: allow order of choices to be randomized, following lon-capa spec. Use
"location" attribute, ie random, top, bottom.
"""
choices = []
_ = i18n.ugettext
for choice in element:
if choice.tag == 'choice':
choices.append((choice.get("name"), stringify_children(choice)))
else:
if choice.tag != 'compoundhint':
msg = Text('[capa.inputtypes.extract_choices] {error_message}').format(
error_message=Text(
# Translators: '<choice>' and '<compoundhint>' are tag names and should not be translated.
_('Expected a <choice> or <compoundhint> tag; got {given_tag} instead')).format(
given_tag=choice.tag
)
)
raise Exception(msg)
return choices
def get_user_visible_answer(self, internal_answer):
if isinstance(internal_answer, basestring):
return self._choices_map[internal_answer]
return [self._choices_map[i] for i in internal_answer]
#-----------------------------------------------------------------------------
@registry.register
class JSInput(InputTypeBase):
"""
Inputtype for general javascript inputs. Intended to be used with
customresponse.
Loads in a sandboxed iframe to help prevent css and js conflicts between
frame and top-level window.
iframe sandbox whitelist:
- allow-scripts
- allow-popups
- allow-forms
- allow-pointer-lock
This in turn means that the iframe cannot directly access the top-level
window elements.
Example:
<jsinput html_file="/static/test.html"
gradefn="grade"
height="500"
width="400"/>
See the documentation in docs/data/source/course_data_formats/jsinput.rst
for more information.
"""
template = "jsinput.html"
tags = ['jsinput']
@classmethod
def get_attributes(cls):
"""
Register the attributes.
"""
return [
Attribute('params', None), # extra iframe params
Attribute('html_file', None),
Attribute('gradefn', "gradefn"),
Attribute('get_statefn', None), # Function to call in iframe
# to get current state.
Attribute('initial_state', None), # JSON string to be used as initial state
Attribute('set_statefn', None), # Function to call iframe to
# set state
Attribute('width', "400"), # iframe width
Attribute('height', "300"), # iframe height
# Title for the iframe, which should be supplied by the author of the problem. Not translated
# because we are in a class method and therefore do not have access to capa_system.i18n.
# Note that the default "display name" for the problem is also not translated.
Attribute('title', "Problem Remote Content"),
# SOP will be relaxed only if this attribute is set to false.
Attribute('sop', None)
]
def _extra_context(self):
context = {
'jschannel_loader': '{static_url}js/capa/src/jschannel.js'.format(
static_url=self.capa_system.STATIC_URL),
'jsinput_loader': '{static_url}js/capa/src/jsinput.js'.format(
static_url=self.capa_system.STATIC_URL),
'saved_state': self.value
}
return context
#-----------------------------------------------------------------------------
@registry.register
class TextLine(InputTypeBase):
"""
A text line input. Can do math preview if "math"="1" is specified.
If "trailing_text" is set to a value, then the textline will be shown with
the value after the text input, and before the checkmark or any input-specific
feedback. HTML will not work, but properly escaped HTML characters will. This
feature is useful if you would like to specify a specific type of units for the
text input.
If the hidden attribute is specified, the textline is hidden and the input id
is stored in a div with name equal to the value of the hidden attribute. This
is used e.g. for embedding simulations turned into questions.
Example:
<textline math="1" trailing_text="m/s"/>
This example will render out a text line with a math preview and the text 'm/s'
after the end of the text line.
"""
template = "textline.html"
tags = ['textline']
@classmethod
def get_attributes(cls):
"""
Register the attributes.
"""
return [
Attribute('size', None),
Attribute('hidden', False),
Attribute('inline', False),
# Attributes below used in setup(), not rendered directly.
Attribute('math', None, render=False),
# TODO: 'dojs' flag is temporary, for backwards compatibility with
# 8.02x
Attribute('dojs', None, render=False),
Attribute('preprocessorClassName', None, render=False),
Attribute('preprocessorSrc', None, render=False),
Attribute('trailing_text', ''),
]
def setup(self):
self.do_math = bool(self.loaded_attributes['math'] or
self.loaded_attributes['dojs'])
# TODO: do math checking using ajax instead of using js, so
# that we only have one math parser.
self.preprocessor = None
if self.do_math:
# Preprocessor to insert between raw input and Mathjax
self.preprocessor = {
'class_name': self.loaded_attributes['preprocessorClassName'],
'script_src': self.loaded_attributes['preprocessorSrc'],
}
if None in self.preprocessor.values():
self.preprocessor = None
def _extra_context(self):
return {'do_math': self.do_math,
'preprocessor': self.preprocessor, }
#-----------------------------------------------------------------------------
@registry.register
class FileSubmission(InputTypeBase):
"""
Upload some files (e.g. for programming assignments)
"""
template = "filesubmission.html"
tags = ['filesubmission']
@staticmethod
def parse_files(files):
"""
Given a string like 'a.py b.py c.out', split on whitespace and return as a json list.
"""
return json.dumps(files.split())
@classmethod
def get_attributes(cls):
"""
Convert the list of allowed files to a convenient format.
"""
return [Attribute('allowed_files', '[]', transform=cls.parse_files),
Attribute('required_files', '[]', transform=cls.parse_files), ]
def setup(self):
"""
Do some magic to handle queueing status (render as "queued" instead of "incomplete"),
pull queue_len from the msg field. (TODO: get rid of the queue_len hack).
"""
_ = self.capa_system.i18n.ugettext
submitted_msg = _("Your files have been submitted. As soon as your submission is"
" graded, this message will be replaced with the grader's feedback.")
self.submitted_msg = submitted_msg
# Check if problem has been queued
self.queue_len = 0
# Flag indicating that the problem has been queued, 'msg' is length of
# queue
if self.status == 'incomplete':
self.status = 'queued'
self.queue_len = self.msg
self.msg = self.submitted_msg
def _extra_context(self):
return {'queue_len': self.queue_len, }
#-----------------------------------------------------------------------------
@registry.register
class CodeInput(InputTypeBase):
"""
A text area input for code--uses codemirror, does syntax highlighting, special tab handling,
etc.
"""
template = "codeinput.html"
tags = [
'codeinput',
'textbox',
# Another (older) name--at some point we may want to make it use a
# non-codemirror editor.
]
@classmethod
def get_attributes(cls):
"""
Convert options to a convenient format.
"""
return [
Attribute('rows', '30'),
Attribute('cols', '80'),
Attribute('hidden', ''),
# For CodeMirror
Attribute('mode', 'python'),
Attribute('linenumbers', 'true'),
# Template expects tabsize to be an int it can do math with
Attribute('tabsize', 4, transform=int),
]
def setup_code_response_rendering(self):
"""
Implement special logic: handle queueing state, and default input.
"""
# if no student input yet, then use the default input given by the
# problem
if not self.value and self.xml.text:
self.value = self.xml.text.strip()
# Check if problem has been queued
self.queue_len = 0
# Flag indicating that the problem has been queued, 'msg' is length of
# queue
if self.status == 'incomplete':
self.status = 'queued'
self.queue_len = self.msg
self.msg = bleach.clean(self.submitted_msg)
def setup(self):
""" setup this input type """
_ = self.capa_system.i18n.ugettext
submitted_msg = _("Your answer has been submitted. As soon as your submission is"
" graded, this message will be replaced with the grader's feedback.")
self.submitted_msg = submitted_msg
self.setup_code_response_rendering()
def _extra_context(self):
"""
Define queue_len, arial_label and code mirror exit message context variables
"""
_ = self.capa_system.i18n.ugettext
return {
'queue_len': self.queue_len,
'aria_label': _('{programming_language} editor').format(
programming_language=self.loaded_attributes.get('mode')
),
'code_mirror_exit_message': _('Press ESC then TAB or click outside of the code editor to exit')
}
#-----------------------------------------------------------------------------
@registry.register
class MatlabInput(CodeInput):
"""
InputType for handling Matlab code input
Example:
<matlabinput rows="10" cols="80" tabsize="4">
Initial Text
</matlabinput>
"""
template = "matlabinput.html"
tags = ['matlabinput']
def setup(self):
"""
Handle matlab-specific parsing
"""
_ = self.capa_system.i18n.ugettext
submitted_msg = _("Submitted. As soon as a response is returned, "
"this message will be replaced by that feedback.")
self.submitted_msg = submitted_msg
self.setup_code_response_rendering()
xml = self.xml
self.plot_payload = xml.findtext('./plot_payload')
# Check if problem has been queued
self.queuename = 'matlab'
self.queue_msg = ''
# this is only set if we don't have a graded response
# the graded response takes precedence
if 'queue_msg' in self.input_state and self.status in ['queued', 'incomplete', 'unsubmitted']:
self.queue_msg = sanitize_html(self.input_state['queue_msg'])
if 'queuestate' in self.input_state and self.input_state['queuestate'] == 'queued':
self.status = 'queued'
self.queue_len = 1
self.msg = self.submitted_msg
# Handle situation if no response from xqueue arrived during specified time.
if ('queuetime' not in self.input_state or
time.time() - self.input_state['queuetime'] > XQUEUE_TIMEOUT):
self.queue_len = 0
self.status = 'unsubmitted'
self.msg = _(
'No response from Xqueue within {xqueue_timeout} seconds. Aborted.'
).format(xqueue_timeout=XQUEUE_TIMEOUT)
def handle_ajax(self, dispatch, data):
"""
Handle AJAX calls directed to this input
Args:
- dispatch (str) - indicates how we want this ajax call to be handled
- data (dict) - dictionary of key-value pairs that contain useful data
Returns:
dict - 'success' - whether or not we successfully queued this submission
- 'message' - message to be rendered in case of error
"""
if dispatch == 'plot':
return self._plot_data(data)
return {}
def ungraded_response(self, queue_msg, queuekey):
"""
Handle the response from the XQueue
Stores the response in the input_state so it can be rendered later
Args:
- queue_msg (str) - message returned from the queue. The message to be rendered
- queuekey (str) - a key passed to the queue. Will be matched up to verify that this is the response we're waiting for
Returns:
nothing
"""
# check the queuekey against the saved queuekey
if('queuestate' in self.input_state and self.input_state['queuestate'] == 'queued'
and self.input_state['queuekey'] == queuekey):
msg = self._parse_data(queue_msg)
# save the queue message so that it can be rendered later
self.input_state['queue_msg'] = msg
self.input_state['queuestate'] = None
self.input_state['queuekey'] = None
def button_enabled(self):
""" Return whether or not we want the 'Test Code' button visible
Right now, we only want this button to show up when a problem has not been
checked.
"""
if self.status in ['correct', 'incorrect', 'partially-correct']:
return False
else:
return True
def _extra_context(self):
""" Set up additional context variables"""
_ = self.capa_system.i18n.ugettext
queue_msg = self.queue_msg
if len(self.queue_msg) > 0: # An empty string cannot be parsed as XML but is okay to include in the template.
try:
etree.XML(HTML(u'<div>{0}</div>').format(HTML(self.queue_msg)))
except etree.XMLSyntaxError:
try:
html5lib.parseFragment(self.queue_msg, treebuilder='lxml', namespaceHTMLElements=False)[0]
except (IndexError, ValueError):
# If neither can parse queue_msg, it contains invalid xml.
queue_msg = HTML("<span>{0}</span>").format(_("Error running code."))
extra_context = {
'queue_len': str(self.queue_len),
'queue_msg': queue_msg,
'button_enabled': self.button_enabled(),
'matlab_editor_js': '{static_url}js/vendor/CodeMirror/octave.js'.format(
static_url=self.capa_system.STATIC_URL),
'msg': sanitize_html(self.msg) # sanitize msg before rendering into template
}
return extra_context
def _parse_data(self, queue_msg):
"""
Parses the message out of the queue message
Args:
queue_msg (str) - a JSON encoded string
Returns:
returns the value for the the key 'msg' in queue_msg
"""
try:
result = json.loads(queue_msg)
except (TypeError, ValueError):
log.error("External message should be a JSON serialized dict."
" Received queue_msg = %s", queue_msg)
raise
msg = result['msg']
return msg
def _plot_data(self, data):
"""
AJAX handler for the plot button
Args:
get (dict) - should have key 'submission' which contains the student submission
Returns:
dict - 'success' - whether or not we successfully queued this submission
- 'message' - message to be rendered in case of error
"""
_ = self.capa_system.i18n.ugettext
# only send data if xqueue exists
if self.capa_system.xqueue is None:
return {'success': False, 'message': _('Cannot connect to the queue')}
# pull relevant info out of get
response = data['submission']
# construct xqueue headers
qinterface = self.capa_system.xqueue['interface']
qtime = datetime.utcnow().strftime(xqueue_interface.dateformat)
callback_url = self.capa_system.xqueue['construct_callback']('ungraded_response')
anonymous_student_id = self.capa_system.anonymous_student_id
# TODO: Why is this using self.capa_system.seed when we have self.seed???
queuekey = xqueue_interface.make_hashkey(str(self.capa_system.seed) + qtime +
anonymous_student_id +
self.input_id)
xheader = xqueue_interface.make_xheader(
lms_callback_url=callback_url,
lms_key=queuekey,
queue_name=self.queuename)
# construct xqueue body
student_info = {
'anonymous_student_id': anonymous_student_id,
'submission_time': qtime
}
contents = {
'grader_payload': self.plot_payload,
'student_info': json.dumps(student_info),
'student_response': response,
'token': getattr(self.capa_system, 'matlab_api_key', None),
'endpoint_version': "2",
'requestor_id': anonymous_student_id,
}
(error, msg) = qinterface.send_to_queue(header=xheader,
body=json.dumps(contents))
# save the input state if successful
if error == 0:
self.input_state['queuekey'] = queuekey
self.input_state['queuestate'] = 'queued'
self.input_state['queuetime'] = time.time()
return {'success': error == 0, 'message': msg}
#-----------------------------------------------------------------------------
@registry.register
class Schematic(InputTypeBase):
"""
InputType for the schematic editor
"""
template = "schematicinput.html"
tags = ['schematic']
@classmethod
def get_attributes(cls):
"""
Convert options to a convenient format.
"""
return [
Attribute('height', None),
Attribute('width', None),
Attribute('parts', None),
Attribute('analyses', None),
Attribute('initial_value', None),
Attribute('submit_analyses', None),
]
def _extra_context(self):
context = {
'setup_script': '{static_url}js/capa/schematicinput.js'.format(
static_url=self.capa_system.STATIC_URL),
}
return context
#-----------------------------------------------------------------------------
@registry.register
class ImageInput(InputTypeBase):
"""
Clickable image as an input field. Element should specify the image source, height,
and width, e.g.
<imageinput src="/static/Figures/Skier-conservation-of-energy.jpg" width="388" height="560" />
TODO: showanswer for imageimput does not work yet - need javascript to put rectangle
over acceptable area of image.
"""
template = "imageinput.html"
tags = ['imageinput']
@classmethod
def get_attributes(cls):
"""
Note: src, height, and width are all required.
"""
return [Attribute('src'),
Attribute('height'),
Attribute('width'), ]
def setup(self):
"""
if value is of the form [x,y] then parse it and send along coordinates of previous answer
"""
m = re.match(r'\[([0-9]+),([0-9]+)]',
self.value.strip().replace(' ', ''))
if m:
# Note: we subtract 15 to compensate for the size of the dot on the screen.
# (is a 30x30 image--lms/static/images/green-pointer.png).
(self.gx, self.gy) = [int(x) - 15 for x in m.groups()]
else:
(self.gx, self.gy) = (0, 0)
def _extra_context(self):
return {'gx': self.gx,
'gy': self.gy}
#-----------------------------------------------------------------------------
@registry.register
class Crystallography(InputTypeBase):
"""
An input for crystallography -- user selects 3 points on the axes, and we get a plane.
TODO: what's the actual value format?
"""
template = "crystallography.html"
tags = ['crystallography']
@classmethod
def get_attributes(cls):
"""
Note: height, width are required.
"""
return [Attribute('height'),
Attribute('width'),
]
# -------------------------------------------------------------------------
@registry.register
class VseprInput(InputTypeBase):
"""
Input for molecular geometry--show possible structures, let student
pick structure and label positions with atoms or electron pairs.
"""
template = 'vsepr_input.html'
tags = ['vsepr_input']
@classmethod
def get_attributes(cls):
"""
Note: height, width, molecules and geometries are required.
"""
return [Attribute('height'),
Attribute('width'),
Attribute('molecules'),
Attribute('geometries'),
]
#-------------------------------------------------------------------------
@registry.register
class ChemicalEquationInput(InputTypeBase):
"""
An input type for entering chemical equations. Supports live preview.
Example:
<chemicalequationinput size="50"/>
options: size -- width of the textbox.
"""
template = "chemicalequationinput.html"
tags = ['chemicalequationinput']
@classmethod
def get_attributes(cls):
"""
Can set size of text field.
"""
return [Attribute('size', '20'), ]
def _extra_context(self):
"""
TODO (vshnayder): Get rid of this once we have a standard way of requiring js to be loaded.
"""
return {
'previewer': '{static_url}js/capa/chemical_equation_preview.js'.format(
static_url=self.capa_system.STATIC_URL),
}
def handle_ajax(self, dispatch, data):
"""
Since we only have chemcalc preview this input, check to see if it
matches the corresponding dispatch and send it through if it does
"""
if dispatch == 'preview_chemcalc':
return self.preview_chemcalc(data)
return {}
def preview_chemcalc(self, data):
"""
Render an html preview of a chemical formula or equation. get should
contain a key 'formula' and value 'some formula string'.
Returns a json dictionary:
{
'preview' : 'the-preview-html' or ''
'error' : 'the-error' or ''
}
"""
_ = self.capa_system.i18n.ugettext
result = {'preview': '',
'error': ''}
try:
formula = data['formula']
except KeyError:
result['error'] = _("No formula specified.")
return result
try:
result['preview'] = chemcalc.render_to_html(formula)
except pyparsing.ParseException as err:
result['error'] = _("Couldn't parse formula: {error_msg}").format(error_msg=err.msg)
except Exception:
# this is unexpected, so log
log.warning(
"Error while previewing chemical formula", exc_info=True)
result['error'] = _("Error while rendering preview")
return result
#-------------------------------------------------------------------------
@registry.register
class FormulaEquationInput(InputTypeBase):
"""
An input type for entering formula equations. Supports live preview.
Example:
<formulaequationinput size="50"/>
options: size -- width of the textbox.
trailing_text -- text to show after the input textbox when
rendered, same as textline (useful for units)
"""
template = "formulaequationinput.html"
tags = ['formulaequationinput']
@classmethod
def get_attributes(cls):
"""
Can set size of text field.
"""
return [
Attribute('size', '20'),
Attribute('inline', False),
Attribute('trailing_text', ''),
]
def _extra_context(self):
"""
TODO (vshnayder): Get rid of 'previewer' once we have a standard way of requiring js to be loaded.
"""
# `reported_status` is basically `status`, except we say 'unanswered'
return {
'previewer': '{static_url}js/capa/src/formula_equation_preview.js'.format(
static_url=self.capa_system.STATIC_URL),
}
def handle_ajax(self, dispatch, get):
"""
Since we only have formcalc preview this input, check to see if it
matches the corresponding dispatch and send it through if it does
"""
if dispatch == 'preview_formcalc':
return self.preview_formcalc(get)
return {}
def preview_formcalc(self, get):
"""
Render an preview of a formula or equation. `get` should
contain a key 'formula' with a math expression.
Returns a json dictionary:
{
'preview' : '<some latex>' or ''
'error' : 'the-error' or ''
'request_start' : <time sent with request>
}
"""
_ = self.capa_system.i18n.ugettext
result = {'preview': '',
'error': ''}
try:
formula = get['formula']
except KeyError:
result['error'] = _("No formula specified.")
return result
result['request_start'] = int(get.get('request_start', 0))
try:
# TODO add references to valid variables and functions
# At some point, we might want to mark invalid variables as red
# or something, and this is where we would need to pass those in.
result['preview'] = latex_preview(formula)
except pyparsing.ParseException:
result['error'] = _("Sorry, couldn't parse formula")
result['formula'] = formula
except Exception:
# this is unexpected, so log
log.warning(
"Error while previewing formula", exc_info=True
)
result['error'] = _("Error while rendering preview")
return result
#-----------------------------------------------------------------------------
@registry.register
class DragAndDropInput(InputTypeBase):
"""
Input for drag and drop problems. Allows student to drag and drop images and
labels to base image.
"""
template = 'drag_and_drop_input.html'
tags = ['drag_and_drop_input']
def setup(self):
def parse(tag, tag_type):
"""Parses <tag ... /> xml element to dictionary. Stores
'draggable' and 'target' tags with attributes to dictionary and
returns last.
Args:
tag: xml etree element <tag...> with attributes
tag_type: 'draggable' or 'target'.
If tag_type is 'draggable' : all attributes except id
(name or label or icon or can_reuse) are optional
If tag_type is 'target' all attributes (name, x, y, w, h)
are required. (x, y) - coordinates of center of target,
w, h - weight and height of target.
Returns:
Dictionary of vaues of attributes:
dict{'name': smth, 'label': smth, 'icon': smth,
'can_reuse': smth}.
"""
tag_attrs = dict()
tag_attrs['draggable'] = {
'id': Attribute._sentinel,
'label': "", 'icon': "",
'can_reuse': ""
}
tag_attrs['target'] = {
'id': Attribute._sentinel,
'x': Attribute._sentinel,
'y': Attribute._sentinel,
'w': Attribute._sentinel,
'h': Attribute._sentinel
}
dic = dict()
for attr_name in tag_attrs[tag_type].keys():
dic[attr_name] = Attribute(attr_name,
default=tag_attrs[tag_type][attr_name]).parse_from_xml(tag)
if tag_type == 'draggable' and not self.no_labels:
dic['label'] = dic['label'] or dic['id']
if tag_type == 'draggable':
dic['target_fields'] = [parse(target, 'target') for target in
tag.iterchildren('target')]
return dic
# add labels to images?:
self.no_labels = Attribute('no_labels',
default="False").parse_from_xml(self.xml)
to_js = dict()
# image drag and drop onto
to_js['base_image'] = Attribute('img').parse_from_xml(self.xml)
# outline places on image where to drag adn drop
to_js['target_outline'] = Attribute('target_outline',
default="False").parse_from_xml(self.xml)
# one draggable per target?
to_js['one_per_target'] = Attribute('one_per_target',
default="True").parse_from_xml(self.xml)
# list of draggables
to_js['draggables'] = [parse(draggable, 'draggable') for draggable in
self.xml.iterchildren('draggable')]
# list of targets
to_js['targets'] = [parse(target, 'target') for target in
self.xml.iterchildren('target')]
# custom background color for labels:
label_bg_color = Attribute('label_bg_color',
default=None).parse_from_xml(self.xml)
if label_bg_color:
to_js['label_bg_color'] = label_bg_color
self.loaded_attributes['drag_and_drop_json'] = json.dumps(to_js)
self.to_render.add('drag_and_drop_json')
#-------------------------------------------------------------------------
@registry.register
class EditAMoleculeInput(InputTypeBase):
"""
An input type for edit-a-molecule. Integrates with the molecule editor java applet.
Example:
<editamolecule size="50"/>
options: size -- width of the textbox.
"""
template = "editamolecule.html"
tags = ['editamoleculeinput']
@classmethod
def get_attributes(cls):
"""
Can set size of text field.
"""
return [Attribute('file'),
Attribute('missing', None)]
def _extra_context(self):
context = {
'applet_loader': '{static_url}js/capa/editamolecule.js'.format(
static_url=self.capa_system.STATIC_URL),
}
return context
#-----------------------------------------------------------------------------
@registry.register
class DesignProtein2dInput(InputTypeBase):
"""
An input type for design of a protein in 2D. Integrates with the Protex java applet.
Example:
<designprotein2d width="800" hight="500" target_shape="E;NE;NW;W;SW;E;none" />
"""
template = "designprotein2dinput.html"
tags = ['designprotein2dinput']
@classmethod
def get_attributes(cls):
"""
Note: width, hight, and target_shape are required.
"""
return [Attribute('width'),
Attribute('height'),
Attribute('target_shape')
]
def _extra_context(self):
context = {
'applet_loader': '{static_url}js/capa/design-protein-2d.js'.format(
static_url=self.capa_system.STATIC_URL),
}
return context
#-----------------------------------------------------------------------------
@registry.register
class EditAGeneInput(InputTypeBase):
"""
An input type for editing a gene.
Integrates with the genex GWT application.
Example:
<editagene genex_dna_sequence="CGAT" genex_problem_number="1"/>
"""
template = "editageneinput.html"
tags = ['editageneinput']
@classmethod
def get_attributes(cls):
"""
Note: width, height, and dna_sequencee are required.
"""
return [Attribute('genex_dna_sequence'),
Attribute('genex_problem_number')
]
def _extra_context(self):
context = {
'applet_loader': '{static_url}js/capa/edit-a-gene.js'.format(
static_url=self.capa_system.STATIC_URL),
}
return context
#---------------------------------------------------------------------
@registry.register
class AnnotationInput(InputTypeBase):
"""
Input type for annotations: students can enter some notes or other text
(currently ungraded), and then choose from a set of tags/optoins, which are graded.
Example:
<annotationinput>
<title>Annotation Exercise</title>
<text>
They are the ones who, at the public assembly, had put savage derangement [ate] into my thinking
[phrenes] |89 on that day when I myself deprived Achilles of his honorific portion [geras]
</text>
<comment>Agamemnon says that ate or 'derangement' was the cause of his actions: why could Zeus say the same thing?</comment>
<comment_prompt>Type a commentary below:</comment_prompt>
<tag_prompt>Select one tag:</tag_prompt>
<options>
<option choice="correct">ate - both a cause and an effect</option>
<option choice="incorrect">ate - a cause</option>
<option choice="partially-correct">ate - an effect</option>
</options>
</annotationinput>
# TODO: allow ordering to be randomized
"""
template = "annotationinput.html"
tags = ['annotationinput']
def setup(self):
xml = self.xml
self.debug = False # set to True to display extra debug info with input
self.return_to_annotation = True # return only works in conjunction with annotatable xmodule
self.title = xml.findtext('./title', 'Annotation Exercise')
self.text = xml.findtext('./text')
self.comment = xml.findtext('./comment')
self.comment_prompt = xml.findtext(
'./comment_prompt', 'Type a commentary below:')
self.tag_prompt = xml.findtext('./tag_prompt', 'Select one tag:')
self.options = self._find_options()
# Need to provide a value that JSON can parse if there is no
# student-supplied value yet.
if self.value == '':
self.value = 'null'
self._validate_options()
def _find_options(self):
""" Returns an array of dicts where each dict represents an option. """
elements = self.xml.findall('./options/option')
return [{
'id': index,
'description': option.text,
'choice': option.get('choice')
} for (index, option) in enumerate(elements)]
def _validate_options(self):
""" Raises a ValueError if the choice attribute is missing or invalid. """
valid_choices = ('correct', 'partially-correct', 'incorrect')
for option in self.options:
choice = option['choice']
if choice is None:
raise ValueError('Missing required choice attribute.')
elif choice not in valid_choices:
raise ValueError('Invalid choice attribute: {0}. Must be one of: {1}'.format(
choice, ', '.join(valid_choices)))
def _unpack(self, json_value):
""" Unpacks the json input state into a dict. """
d = json.loads(json_value)
if not isinstance(d, dict):
d = {}
comment_value = d.get('comment', '')
if not isinstance(comment_value, basestring):
comment_value = ''
options_value = d.get('options', [])
if not isinstance(options_value, list):
options_value = []
return {
'options_value': options_value,
'has_options_value': len(options_value) > 0, # for convenience
'comment_value': comment_value,
}
def _extra_context(self):
extra_context = {
'title': self.title,
'text': self.text,
'comment': self.comment,
'comment_prompt': self.comment_prompt,
'tag_prompt': self.tag_prompt,
'options': self.options,
'return_to_annotation': self.return_to_annotation,
'debug': self.debug
}
extra_context.update(self._unpack(self.value))
return extra_context
@registry.register
class ChoiceTextGroup(InputTypeBase):
r"""
Groups of radiobutton/checkboxes with text inputs.
Examples:
RadioButton problem
<problem>
<startouttext/>
A person rolls a standard die 100 times and records the results.
On the first roll they received a "1". Given this information
select the correct choice and fill in numbers to make it accurate.
<endouttext/>
<choicetextresponse>
<radiotextgroup>
<choice correct="false">The lowest number rolled was:
<decoy_input/> and the highest number rolled was:
<decoy_input/> .</choice>
<choice correct="true">The lowest number rolled was <numtolerance_input answer="1"/>
and there is not enough information to determine the highest number rolled.
</choice>
<choice correct="false">There is not enough information to determine the lowest
number rolled, and the highest number rolled was:
<decoy_input/> .
</choice>
</radiotextgroup>
</choicetextresponse>
</problem>
CheckboxProblem:
<problem>
<startouttext/>
A person randomly selects 100 times, with replacement, from the list of numbers \(\sqrt{2}\) , 2, 3, 4 ,5 ,6
and records the results. The first number they pick is \(\sqrt{2}\) Given this information
select the correct choices and fill in numbers to make them accurate.
<endouttext/>
<choicetextresponse>
<checkboxtextgroup>
<choice correct="true">
The lowest number selected was <numtolerance_input answer="1.4142" tolerance="0.01"/>
</choice>
<choice correct="false">
The highest number selected was <decoy_input/> .
</choice>
<choice correct="true">There is not enough information given to determine the highest number
which was selected.
</choice>
<choice correct="false">There is not enough information given to determine the lowest number
selected.
</choice>
</checkboxtextgroup>
</choicetextresponse>
</problem>
In the preceding examples the <decoy_input/> is used to generate a textinput html element
in the problem's display. Since it is inside of an incorrect choice, no answer given
for it will be correct, and thus specifying an answer for it is not needed.
"""
template = "choicetext.html"
tags = ['radiotextgroup', 'checkboxtextgroup']
def setup(self):
"""
Performs setup for the initial rendering of the problem.
`self.html_input_type` determines whether this problem is displayed
with radiobuttons or checkboxes
If the initial value of `self.value` is '' change it to {} so that
the template has an empty dictionary to work with.
sets the value of self.choices to be equal to the return value of
`self.extract_choices`
"""
self.text_input_values = {}
if self.tag == 'radiotextgroup':
self.html_input_type = "radio"
elif self.tag == 'checkboxtextgroup':
self.html_input_type = "checkbox"
else:
_ = self.capa_system.i18n.ugettext
msg = _("{input_type}: unexpected tag {tag_name}").format(
input_type="ChoiceTextGroup", tag_name=self.tag
)
raise Exception(msg)
if self.value == '':
# Make `value` an empty dictionary, if it currently has an empty
# value. This is necessary because the template expects a
# dictionary.
self.value = {}
self.choices = self.extract_choices(self.xml, self.capa_system.i18n)
@classmethod
def get_attributes(cls):
"""
Returns a list of `Attribute` for this problem type
"""
# Make '_' a no-op so we can scrape strings. Using lambda instead of
# `django.utils.translation.ugettext_noop` because Django cannot be imported in this file
_ = lambda text: text
return [
Attribute("show_correctness", "always"),
Attribute("submitted_message", _("Answer received.")),
]
def _extra_context(self):
"""
Returns a dictionary of extra content necessary for rendering this InputType.
`input_type` is either 'radio' or 'checkbox' indicating whether the choices for
this problem will have radiobuttons or checkboxes.
"""
return {
'input_type': self.html_input_type,
'choices': self.choices
}
@staticmethod
def extract_choices(element, i18n):
"""
Extracts choices from the xml for this problem type.
If we have xml that is as follows(choice names will have been assigned
by now)
<radiotextgroup>
<choice correct = "true" name ="1_2_1_choiceinput_0bc">
The number
<numtolerance_input name = "1_2_1_choiceinput0_numtolerance_input_0" answer="5"/>
Is the mean of the list.
</choice>
<choice correct = "false" name = "1_2_1_choiceinput_1bc>
False demonstration choice
</choice>
</radiotextgroup>
Choices are used for rendering the problem properly
The function will setup choices as follows:
choices =[
("1_2_1_choiceinput_0bc",
[{'type': 'text', 'contents': "The number", 'tail_text': '',
'value': ''
},
{'type': 'textinput',
'contents': "1_2_1_choiceinput0_numtolerance_input_0",
'tail_text': 'Is the mean of the list',
'value': ''
}
]
),
("1_2_1_choiceinput_1bc",
[{'type': 'text', 'contents': "False demonstration choice",
'tail_text': '',
'value': ''
}
]
)
]
"""
_ = i18n.ugettext
choices = []
for choice in element:
if choice.tag != 'choice':
msg = Text("[capa.inputtypes.extract_choices] {0}").format(
# Translators: a "tag" is an XML element, such as "<b>" in HTML
Text(_("Expected a {expected_tag} tag; got {given_tag} instead")).format(
expected_tag="<choice>",
given_tag=choice.tag,
)
)
raise Exception(msg)
components = []
choice_text = ''
if choice.text is not None:
choice_text += choice.text
# Initialize our dict for the next content
adder = {
'type': 'text',
'contents': choice_text,
'tail_text': '',
'value': ''
}
components.append(adder)
for elt in choice:
# for elements in the choice e.g. <text> <numtolerance_input>
adder = {
'type': 'text',
'contents': '',
'tail_text': '',
'value': ''
}
tag_type = elt.tag
# If the current `elt` is a <numtolerance_input> set the
# `adder`type to 'numtolerance_input', and 'contents' to
# the `elt`'s name.
# Treat decoy_inputs and numtolerance_inputs the same in order
# to prevent students from reading the Html and figuring out
# which inputs are valid
if tag_type in ('numtolerance_input', 'decoy_input'):
# We set this to textinput, so that we get a textinput html
# element.
adder['type'] = 'textinput'
adder['contents'] = elt.get('name')
else:
adder['contents'] = elt.text
# Add any tail text("is the mean" in the example)
adder['tail_text'] = elt.tail if elt.tail else ''
components.append(adder)
# Add the tuple for the current choice to the list of choices
choices.append((choice.get("name"), components))
return choices
|
varunkamra/kuma | refs/heads/master | vendor/packages/pygments/lexers/scripting.py | 72 | # -*- coding: utf-8 -*-
"""
pygments.lexers.scripting
~~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for scripting and embedded languages.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, include, bygroups, default, combined, \
words
from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
Number, Punctuation, Error, Whitespace
from pygments.util import get_bool_opt, get_list_opt, iteritems
__all__ = ['LuaLexer', 'MoonScriptLexer', 'ChaiscriptLexer', 'LSLLexer',
'AppleScriptLexer', 'RexxLexer', 'MOOCodeLexer', 'HybrisLexer']
class LuaLexer(RegexLexer):
"""
For `Lua <http://www.lua.org>`_ source code.
Additional options accepted:
`func_name_highlighting`
If given and ``True``, highlight builtin function names
(default: ``True``).
`disabled_modules`
If given, must be a list of module names whose function names
should not be highlighted. By default all modules are highlighted.
To get a list of allowed modules have a look into the
`_lua_builtins` module:
.. sourcecode:: pycon
>>> from pygments.lexers._lua_builtins import MODULES
>>> MODULES.keys()
['string', 'coroutine', 'modules', 'io', 'basic', ...]
"""
name = 'Lua'
aliases = ['lua']
filenames = ['*.lua', '*.wlua']
mimetypes = ['text/x-lua', 'application/x-lua']
tokens = {
'root': [
# lua allows a file to start with a shebang
(r'#!(.*?)$', Comment.Preproc),
default('base'),
],
'base': [
(r'(?s)--\[(=*)\[.*?\]\1\]', Comment.Multiline),
('--.*$', Comment.Single),
(r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number.Float),
(r'(?i)\d+e[+-]?\d+', Number.Float),
('(?i)0x[0-9a-f]*', Number.Hex),
(r'\d+', Number.Integer),
(r'\n', Text),
(r'[^\S\n]', Text),
# multiline strings
(r'(?s)\[(=*)\[.*?\]\1\]', String),
(r'(==|~=|<=|>=|\.\.\.|\.\.|[=+\-*/%^<>#])', Operator),
(r'[\[\]{}().,:;]', Punctuation),
(r'(and|or|not)\b', Operator.Word),
('(break|do|else|elseif|end|for|if|in|repeat|return|then|until|'
r'while)\b', Keyword),
(r'(local)\b', Keyword.Declaration),
(r'(true|false|nil)\b', Keyword.Constant),
(r'(function)\b', Keyword, 'funcname'),
(r'[A-Za-z_]\w*(\.[A-Za-z_]\w*)?', Name),
("'", String.Single, combined('stringescape', 'sqs')),
('"', String.Double, combined('stringescape', 'dqs'))
],
'funcname': [
(r'\s+', Text),
('(?:([A-Za-z_]\w*)(\.))?([A-Za-z_]\w*)',
bygroups(Name.Class, Punctuation, Name.Function), '#pop'),
# inline function
('\(', Punctuation, '#pop'),
],
# if I understand correctly, every character is valid in a lua string,
# so this state is only for later corrections
'string': [
('.', String)
],
'stringescape': [
(r'''\\([abfnrtv\\"']|\d{1,3})''', String.Escape)
],
'sqs': [
("'", String, '#pop'),
include('string')
],
'dqs': [
('"', String, '#pop'),
include('string')
]
}
def __init__(self, **options):
self.func_name_highlighting = get_bool_opt(
options, 'func_name_highlighting', True)
self.disabled_modules = get_list_opt(options, 'disabled_modules', [])
self._functions = set()
if self.func_name_highlighting:
from pygments.lexers._lua_builtins import MODULES
for mod, func in iteritems(MODULES):
if mod not in self.disabled_modules:
self._functions.update(func)
RegexLexer.__init__(self, **options)
def get_tokens_unprocessed(self, text):
for index, token, value in \
RegexLexer.get_tokens_unprocessed(self, text):
if token is Name:
if value in self._functions:
yield index, Name.Builtin, value
continue
elif '.' in value:
a, b = value.split('.')
yield index, Name, a
yield index + len(a), Punctuation, u'.'
yield index + len(a) + 1, Name, b
continue
yield index, token, value
class MoonScriptLexer(LuaLexer):
"""
For `MoonScript <http://moonscript.org>`_ source code.
.. versionadded:: 1.5
"""
name = "MoonScript"
aliases = ["moon", "moonscript"]
filenames = ["*.moon"]
mimetypes = ['text/x-moonscript', 'application/x-moonscript']
tokens = {
'root': [
(r'#!(.*?)$', Comment.Preproc),
default('base'),
],
'base': [
('--.*$', Comment.Single),
(r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number.Float),
(r'(?i)\d+e[+-]?\d+', Number.Float),
(r'(?i)0x[0-9a-f]*', Number.Hex),
(r'\d+', Number.Integer),
(r'\n', Text),
(r'[^\S\n]+', Text),
(r'(?s)\[(=*)\[.*?\]\1\]', String),
(r'(->|=>)', Name.Function),
(r':[a-zA-Z_]\w*', Name.Variable),
(r'(==|!=|~=|<=|>=|\.\.\.|\.\.|[=+\-*/%^<>#!.\\:])', Operator),
(r'[;,]', Punctuation),
(r'[\[\]{}()]', Keyword.Type),
(r'[a-zA-Z_]\w*:', Name.Variable),
(words((
'class', 'extends', 'if', 'then', 'super', 'do', 'with',
'import', 'export', 'while', 'elseif', 'return', 'for', 'in',
'from', 'when', 'using', 'else', 'and', 'or', 'not', 'switch',
'break'), suffix=r'\b'),
Keyword),
(r'(true|false|nil)\b', Keyword.Constant),
(r'(and|or|not)\b', Operator.Word),
(r'(self)\b', Name.Builtin.Pseudo),
(r'@@?([a-zA-Z_]\w*)?', Name.Variable.Class),
(r'[A-Z]\w*', Name.Class), # proper name
(r'[A-Za-z_]\w*(\.[A-Za-z_]\w*)?', Name),
("'", String.Single, combined('stringescape', 'sqs')),
('"', String.Double, combined('stringescape', 'dqs'))
],
'stringescape': [
(r'''\\([abfnrtv\\"']|\d{1,3})''', String.Escape)
],
'sqs': [
("'", String.Single, '#pop'),
(".", String)
],
'dqs': [
('"', String.Double, '#pop'),
(".", String)
]
}
def get_tokens_unprocessed(self, text):
# set . as Operator instead of Punctuation
for index, token, value in LuaLexer.get_tokens_unprocessed(self, text):
if token == Punctuation and value == ".":
token = Operator
yield index, token, value
class ChaiscriptLexer(RegexLexer):
"""
For `ChaiScript <http://chaiscript.com/>`_ source code.
.. versionadded:: 2.0
"""
name = 'ChaiScript'
aliases = ['chai', 'chaiscript']
filenames = ['*.chai']
mimetypes = ['text/x-chaiscript', 'application/x-chaiscript']
flags = re.DOTALL | re.MULTILINE
tokens = {
'commentsandwhitespace': [
(r'\s+', Text),
(r'//.*?\n', Comment.Single),
(r'/\*.*?\*/', Comment.Multiline),
(r'^\#.*?\n', Comment.Single)
],
'slashstartsregex': [
include('commentsandwhitespace'),
(r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/'
r'([gim]+\b|\B)', String.Regex, '#pop'),
(r'(?=/)', Text, ('#pop', 'badregex')),
default('#pop')
],
'badregex': [
(r'\n', Text, '#pop')
],
'root': [
include('commentsandwhitespace'),
(r'\n', Text),
(r'[^\S\n]+', Text),
(r'\+\+|--|~|&&|\?|:|\|\||\\(?=\n)|\.\.'
r'(<<|>>>?|==?|!=?|[-<>+*%&|^/])=?', Operator, 'slashstartsregex'),
(r'[{(\[;,]', Punctuation, 'slashstartsregex'),
(r'[})\].]', Punctuation),
(r'[=+\-*/]', Operator),
(r'(for|in|while|do|break|return|continue|if|else|'
r'throw|try|catch'
r')\b', Keyword, 'slashstartsregex'),
(r'(var)\b', Keyword.Declaration, 'slashstartsregex'),
(r'(attr|def|fun)\b', Keyword.Reserved),
(r'(true|false)\b', Keyword.Constant),
(r'(eval|throw)\b', Name.Builtin),
(r'`\S+`', Name.Builtin),
(r'[$a-zA-Z_]\w*', Name.Other),
(r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
(r'0x[0-9a-fA-F]+', Number.Hex),
(r'[0-9]+', Number.Integer),
(r'"', String.Double, 'dqstring'),
(r"'(\\\\|\\'|[^'])*'", String.Single),
],
'dqstring': [
(r'\$\{[^"}]+?\}', String.Interpol),
(r'\$', String.Double),
(r'\\\\', String.Double),
(r'\\"', String.Double),
(r'[^\\"$]+', String.Double),
(r'"', String.Double, '#pop'),
],
}
class LSLLexer(RegexLexer):
"""
For Second Life's Linden Scripting Language source code.
.. versionadded:: 2.0
"""
name = 'LSL'
aliases = ['lsl']
filenames = ['*.lsl']
mimetypes = ['text/x-lsl']
flags = re.MULTILINE
lsl_keywords = r'\b(?:do|else|for|if|jump|return|while)\b'
lsl_types = r'\b(?:float|integer|key|list|quaternion|rotation|string|vector)\b'
lsl_states = r'\b(?:(?:state)\s+\w+|default)\b'
lsl_events = r'\b(?:state_(?:entry|exit)|touch(?:_(?:start|end))?|(?:land_)?collision(?:_(?:start|end))?|timer|listen|(?:no_)?sensor|control|(?:not_)?at_(?:rot_)?target|money|email|run_time_permissions|changed|attach|dataserver|moving_(?:start|end)|link_message|(?:on|object)_rez|remote_data|http_re(?:sponse|quest)|path_update|transaction_result)\b'
lsl_functions_builtin = r'\b(?:ll(?:ReturnObjectsBy(?:ID|Owner)|Json(?:2List|[GS]etValue|ValueType)|Sin|Cos|Tan|Atan2|Sqrt|Pow|Abs|Fabs|Frand|Floor|Ceil|Round|Vec(?:Mag|Norm|Dist)|Rot(?:Between|2(?:Euler|Fwd|Left|Up))|(?:Euler|Axes)2Rot|Whisper|(?:Region|Owner)?Say|Shout|Listen(?:Control|Remove)?|Sensor(?:Repeat|Remove)?|Detected(?:Name|Key|Owner|Type|Pos|Vel|Grab|Rot|Group|LinkNumber)|Die|Ground|Wind|(?:[GS]et)(?:AnimationOverride|MemoryLimit|PrimMediaParams|ParcelMusicURL|Object(?:Desc|Name)|PhysicsMaterial|Status|Scale|Color|Alpha|Texture|Pos|Rot|Force|Torque)|ResetAnimationOverride|(?:Scale|Offset|Rotate)Texture|(?:Rot)?Target(?:Remove)?|(?:Stop)?MoveToTarget|Apply(?:Rotational)?Impulse|Set(?:KeyframedMotion|ContentType|RegionPos|(?:Angular)?Velocity|Buoyancy|HoverHeight|ForceAndTorque|TimerEvent|ScriptState|Damage|TextureAnim|Sound(?:Queueing|Radius)|Vehicle(?:Type|(?:Float|Vector|Rotation)Param)|(?:Touch|Sit)?Text|Camera(?:Eye|At)Offset|PrimitiveParams|ClickAction|Link(?:Alpha|Color|PrimitiveParams(?:Fast)?|Texture(?:Anim)?|Camera|Media)|RemoteScriptAccessPin|PayPrice|LocalRot)|ScaleByFactor|Get(?:(?:Max|Min)ScaleFactor|ClosestNavPoint|StaticPath|SimStats|Env|PrimitiveParams|Link(?:PrimitiveParams|Number(?:OfSides)?|Key|Name|Media)|HTTPHeader|FreeURLs|Object(?:Details|PermMask|PrimCount)|Parcel(?:MaxPrims|Details|Prim(?:Count|Owners))|Attached|(?:SPMax|Free|Used)Memory|Region(?:Name|TimeDilation|FPS|Corner|AgentCount)|Root(?:Position|Rotation)|UnixTime|(?:Parcel|Region)Flags|(?:Wall|GMT)clock|SimulatorHostname|BoundingBox|GeometricCenter|Creator|NumberOf(?:Prims|NotecardLines|Sides)|Animation(?:List)?|(?:Camera|Local)(?:Pos|Rot)|Vel|Accel|Omega|Time(?:stamp|OfDay)|(?:Object|CenterOf)?Mass|MassMKS|Energy|Owner|(?:Owner)?Key|SunDirection|Texture(?:Offset|Scale|Rot)|Inventory(?:Number|Name|Key|Type|Creator|PermMask)|Permissions(?:Key)?|StartParameter|List(?:Length|EntryType)|Date|Agent(?:Size|Info|Language|List)|LandOwnerAt|NotecardLine|Script(?:Name|State))|(?:Get|Reset|GetAndReset)Time|PlaySound(?:Slave)?|LoopSound(?:Master|Slave)?|(?:Trigger|Stop|Preload)Sound|(?:(?:Get|Delete)Sub|Insert)String|To(?:Upper|Lower)|Give(?:InventoryList|Money)|RezObject|(?:Stop)?LookAt|Sleep|CollisionFilter|(?:Take|Release)Controls|DetachFromAvatar|AttachToAvatar(?:Temp)?|InstantMessage|(?:GetNext)?Email|StopHover|MinEventDelay|RotLookAt|String(?:Length|Trim)|(?:Start|Stop)Animation|TargetOmega|RequestPermissions|(?:Create|Break)Link|BreakAllLinks|(?:Give|Remove)Inventory|Water|PassTouches|Request(?:Agent|Inventory)Data|TeleportAgent(?:Home|GlobalCoords)?|ModifyLand|CollisionSound|ResetScript|MessageLinked|PushObject|PassCollisions|AxisAngle2Rot|Rot2(?:Axis|Angle)|A(?:cos|sin)|AngleBetween|AllowInventoryDrop|SubStringIndex|List2(?:CSV|Integer|Json|Float|String|Key|Vector|Rot|List(?:Strided)?)|DeleteSubList|List(?:Statistics|Sort|Randomize|(?:Insert|Find|Replace)List)|EdgeOfWorld|AdjustSoundVolume|Key2Name|TriggerSoundLimited|EjectFromLand|(?:CSV|ParseString)2List|OverMyLand|SameGroup|UnSit|Ground(?:Slope|Normal|Contour)|GroundRepel|(?:Set|Remove)VehicleFlags|(?:AvatarOn)?(?:Link)?SitTarget|Script(?:Danger|Profiler)|Dialog|VolumeDetect|ResetOtherScript|RemoteLoadScriptPin|(?:Open|Close)RemoteDataChannel|SendRemoteData|RemoteDataReply|(?:Integer|String)ToBase64|XorBase64|Log(?:10)?|Base64To(?:String|Integer)|ParseStringKeepNulls|RezAtRoot|RequestSimulatorData|ForceMouselook|(?:Load|Release|(?:E|Une)scape)URL|ParcelMedia(?:CommandList|Query)|ModPow|MapDestination|(?:RemoveFrom|AddTo|Reset)Land(?:Pass|Ban)List|(?:Set|Clear)CameraParams|HTTP(?:Request|Response)|TextBox|DetectedTouch(?:UV|Face|Pos|(?:N|Bin)ormal|ST)|(?:MD5|SHA1|DumpList2)String|Request(?:Secure)?URL|Clear(?:Prim|Link)Media|(?:Link)?ParticleSystem|(?:Get|Request)(?:Username|DisplayName)|RegionSayTo|CastRay|GenerateKey|TransferLindenDollars|ManageEstateAccess|(?:Create|Delete)Character|ExecCharacterCmd|Evade|FleeFrom|NavigateTo|PatrolPoints|Pursue|UpdateCharacter|WanderWithin))\b'
lsl_constants_float = r'\b(?:DEG_TO_RAD|PI(?:_BY_TWO)?|RAD_TO_DEG|SQRT2|TWO_PI)\b'
lsl_constants_integer = r'\b(?:JSON_APPEND|STATUS_(?:PHYSICS|ROTATE_[XYZ]|PHANTOM|SANDBOX|BLOCK_GRAB(?:_OBJECT)?|(?:DIE|RETURN)_AT_EDGE|CAST_SHADOWS|OK|MALFORMED_PARAMS|TYPE_MISMATCH|BOUNDS_ERROR|NOT_(?:FOUND|SUPPORTED)|INTERNAL_ERROR|WHITELIST_FAILED)|AGENT(?:_(?:BY_(?:LEGACY_|USER)NAME|FLYING|ATTACHMENTS|SCRIPTED|MOUSELOOK|SITTING|ON_OBJECT|AWAY|WALKING|IN_AIR|TYPING|CROUCHING|BUSY|ALWAYS_RUN|AUTOPILOT|LIST_(?:PARCEL(?:_OWNER)?|REGION)))?|CAMERA_(?:PITCH|DISTANCE|BEHINDNESS_(?:ANGLE|LAG)|(?:FOCUS|POSITION)(?:_(?:THRESHOLD|LOCKED|LAG))?|FOCUS_OFFSET|ACTIVE)|ANIM_ON|LOOP|REVERSE|PING_PONG|SMOOTH|ROTATE|SCALE|ALL_SIDES|LINK_(?:ROOT|SET|ALL_(?:OTHERS|CHILDREN)|THIS)|ACTIVE|PASSIVE|SCRIPTED|CONTROL_(?:FWD|BACK|(?:ROT_)?(?:LEFT|RIGHT)|UP|DOWN|(?:ML_)?LBUTTON)|PERMISSION_(?:RETURN_OBJECTS|DEBIT|OVERRIDE_ANIMATIONS|SILENT_ESTATE_MANAGEMENT|TAKE_CONTROLS|TRIGGER_ANIMATION|ATTACH|CHANGE_LINKS|(?:CONTROL|TRACK)_CAMERA|TELEPORT)|INVENTORY_(?:TEXTURE|SOUND|OBJECT|SCRIPT|LANDMARK|CLOTHING|NOTECARD|BODYPART|ANIMATION|GESTURE|ALL|NONE)|CHANGED_(?:INVENTORY|COLOR|SHAPE|SCALE|TEXTURE|LINK|ALLOWED_DROP|OWNER|REGION(?:_START)?|TELEPORT|MEDIA)|OBJECT_(?:(?:PHYSICS|SERVER|STREAMING)_COST|UNKNOWN_DETAIL|CHARACTER_TIME|PHANTOM|PHYSICS|TEMP_ON_REZ|NAME|DESC|POS|PRIM_EQUIVALENCE|RETURN_(?:PARCEL(?:_OWNER)?|REGION)|ROO?T|VELOCITY|OWNER|GROUP|CREATOR|ATTACHED_POINT|RENDER_WEIGHT|PATHFINDING_TYPE|(?:RUNNING|TOTAL)_SCRIPT_COUNT|SCRIPT_(?:MEMORY|TIME))|TYPE_(?:INTEGER|FLOAT|STRING|KEY|VECTOR|ROTATION|INVALID)|(?:DEBUG|PUBLIC)_CHANNEL|ATTACH_(?:AVATAR_CENTER|CHEST|HEAD|BACK|PELVIS|MOUTH|CHIN|NECK|NOSE|BELLY|[LR](?:SHOULDER|HAND|FOOT|EAR|EYE|[UL](?:ARM|LEG)|HIP)|(?:LEFT|RIGHT)_PEC|HUD_(?:CENTER_[12]|TOP_(?:RIGHT|CENTER|LEFT)|BOTTOM(?:_(?:RIGHT|LEFT))?))|LAND_(?:LEVEL|RAISE|LOWER|SMOOTH|NOISE|REVERT)|DATA_(?:ONLINE|NAME|BORN|SIM_(?:POS|STATUS|RATING)|PAYINFO)|PAYMENT_INFO_(?:ON_FILE|USED)|REMOTE_DATA_(?:CHANNEL|REQUEST|REPLY)|PSYS_(?:PART_(?:BF_(?:ZERO|ONE(?:_MINUS_(?:DEST_COLOR|SOURCE_(ALPHA|COLOR)))?|DEST_COLOR|SOURCE_(ALPHA|COLOR))|BLEND_FUNC_(DEST|SOURCE)|FLAGS|(?:START|END)_(?:COLOR|ALPHA|SCALE|GLOW)|MAX_AGE|(?:RIBBON|WIND|INTERP_(?:COLOR|SCALE)|BOUNCE|FOLLOW_(?:SRC|VELOCITY)|TARGET_(?:POS|LINEAR)|EMISSIVE)_MASK)|SRC_(?:MAX_AGE|PATTERN|ANGLE_(?:BEGIN|END)|BURST_(?:RATE|PART_COUNT|RADIUS|SPEED_(?:MIN|MAX))|ACCEL|TEXTURE|TARGET_KEY|OMEGA|PATTERN_(?:DROP|EXPLODE|ANGLE(?:_CONE(?:_EMPTY)?)?)))|VEHICLE_(?:REFERENCE_FRAME|TYPE_(?:NONE|SLED|CAR|BOAT|AIRPLANE|BALLOON)|(?:LINEAR|ANGULAR)_(?:FRICTION_TIMESCALE|MOTOR_DIRECTION)|LINEAR_MOTOR_OFFSET|HOVER_(?:HEIGHT|EFFICIENCY|TIMESCALE)|BUOYANCY|(?:LINEAR|ANGULAR)_(?:DEFLECTION_(?:EFFICIENCY|TIMESCALE)|MOTOR_(?:DECAY_)?TIMESCALE)|VERTICAL_ATTRACTION_(?:EFFICIENCY|TIMESCALE)|BANKING_(?:EFFICIENCY|MIX|TIMESCALE)|FLAG_(?:NO_DEFLECTION_UP|LIMIT_(?:ROLL_ONLY|MOTOR_UP)|HOVER_(?:(?:WATER|TERRAIN|UP)_ONLY|GLOBAL_HEIGHT)|MOUSELOOK_(?:STEER|BANK)|CAMERA_DECOUPLED))|PRIM_(?:TYPE(?:_(?:BOX|CYLINDER|PRISM|SPHERE|TORUS|TUBE|RING|SCULPT))?|HOLE_(?:DEFAULT|CIRCLE|SQUARE|TRIANGLE)|MATERIAL(?:_(?:STONE|METAL|GLASS|WOOD|FLESH|PLASTIC|RUBBER))?|SHINY_(?:NONE|LOW|MEDIUM|HIGH)|BUMP_(?:NONE|BRIGHT|DARK|WOOD|BARK|BRICKS|CHECKER|CONCRETE|TILE|STONE|DISKS|GRAVEL|BLOBS|SIDING|LARGETILE|STUCCO|SUCTION|WEAVE)|TEXGEN_(?:DEFAULT|PLANAR)|SCULPT_(?:TYPE_(?:SPHERE|TORUS|PLANE|CYLINDER|MASK)|FLAG_(?:MIRROR|INVERT))|PHYSICS(?:_(?:SHAPE_(?:CONVEX|NONE|PRIM|TYPE)))?|(?:POS|ROT)_LOCAL|SLICE|TEXT|FLEXIBLE|POINT_LIGHT|TEMP_ON_REZ|PHANTOM|POSITION|SIZE|ROTATION|TEXTURE|NAME|OMEGA|DESC|LINK_TARGET|COLOR|BUMP_SHINY|FULLBRIGHT|TEXGEN|GLOW|MEDIA_(?:ALT_IMAGE_ENABLE|CONTROLS|(?:CURRENT|HOME)_URL|AUTO_(?:LOOP|PLAY|SCALE|ZOOM)|FIRST_CLICK_INTERACT|(?:WIDTH|HEIGHT)_PIXELS|WHITELIST(?:_ENABLE)?|PERMS_(?:INTERACT|CONTROL)|PARAM_MAX|CONTROLS_(?:STANDARD|MINI)|PERM_(?:NONE|OWNER|GROUP|ANYONE)|MAX_(?:URL_LENGTH|WHITELIST_(?:SIZE|COUNT)|(?:WIDTH|HEIGHT)_PIXELS)))|MASK_(?:BASE|OWNER|GROUP|EVERYONE|NEXT)|PERM_(?:TRANSFER|MODIFY|COPY|MOVE|ALL)|PARCEL_(?:MEDIA_COMMAND_(?:STOP|PAUSE|PLAY|LOOP|TEXTURE|URL|TIME|AGENT|UNLOAD|AUTO_ALIGN|TYPE|SIZE|DESC|LOOP_SET)|FLAG_(?:ALLOW_(?:FLY|(?:GROUP_)?SCRIPTS|LANDMARK|TERRAFORM|DAMAGE|CREATE_(?:GROUP_)?OBJECTS)|USE_(?:ACCESS_(?:GROUP|LIST)|BAN_LIST|LAND_PASS_LIST)|LOCAL_SOUND_ONLY|RESTRICT_PUSHOBJECT|ALLOW_(?:GROUP|ALL)_OBJECT_ENTRY)|COUNT_(?:TOTAL|OWNER|GROUP|OTHER|SELECTED|TEMP)|DETAILS_(?:NAME|DESC|OWNER|GROUP|AREA|ID|SEE_AVATARS))|LIST_STAT_(?:MAX|MIN|MEAN|MEDIAN|STD_DEV|SUM(?:_SQUARES)?|NUM_COUNT|GEOMETRIC_MEAN|RANGE)|PAY_(?:HIDE|DEFAULT)|REGION_FLAG_(?:ALLOW_DAMAGE|FIXED_SUN|BLOCK_TERRAFORM|SANDBOX|DISABLE_(?:COLLISIONS|PHYSICS)|BLOCK_FLY|ALLOW_DIRECT_TELEPORT|RESTRICT_PUSHOBJECT)|HTTP_(?:METHOD|MIMETYPE|BODY_(?:MAXLENGTH|TRUNCATED)|CUSTOM_HEADER|PRAGMA_NO_CACHE|VERBOSE_THROTTLE|VERIFY_CERT)|STRING_(?:TRIM(?:_(?:HEAD|TAIL))?)|CLICK_ACTION_(?:NONE|TOUCH|SIT|BUY|PAY|OPEN(?:_MEDIA)?|PLAY|ZOOM)|TOUCH_INVALID_FACE|PROFILE_(?:NONE|SCRIPT_MEMORY)|RC_(?:DATA_FLAGS|DETECT_PHANTOM|GET_(?:LINK_NUM|NORMAL|ROOT_KEY)|MAX_HITS|REJECT_(?:TYPES|AGENTS|(?:NON)?PHYSICAL|LAND))|RCERR_(?:CAST_TIME_EXCEEDED|SIM_PERF_LOW|UNKNOWN)|ESTATE_ACCESS_(?:ALLOWED_(?:AGENT|GROUP)_(?:ADD|REMOVE)|BANNED_AGENT_(?:ADD|REMOVE))|DENSITY|FRICTION|RESTITUTION|GRAVITY_MULTIPLIER|KFM_(?:COMMAND|CMD_(?:PLAY|STOP|PAUSE|SET_MODE)|MODE|FORWARD|LOOP|PING_PONG|REVERSE|DATA|ROTATION|TRANSLATION)|ERR_(?:GENERIC|PARCEL_PERMISSIONS|MALFORMED_PARAMS|RUNTIME_PERMISSIONS|THROTTLED)|CHARACTER_(?:CMD_(?:(?:SMOOTH_)?STOP|JUMP)|DESIRED_(?:TURN_)?SPEED|RADIUS|STAY_WITHIN_PARCEL|LENGTH|ORIENTATION|ACCOUNT_FOR_SKIPPED_FRAMES|AVOIDANCE_MODE|TYPE(?:_(?:[A-D]|NONE))?|MAX_(?:DECEL|TURN_RADIUS|(?:ACCEL|SPEED)))|PURSUIT_(?:OFFSET|FUZZ_FACTOR|GOAL_TOLERANCE|INTERCEPT)|REQUIRE_LINE_OF_SIGHT|FORCE_DIRECT_PATH|VERTICAL|HORIZONTAL|AVOID_(?:CHARACTERS|DYNAMIC_OBSTACLES|NONE)|PU_(?:EVADE_(?:HIDDEN|SPOTTED)|FAILURE_(?:DYNAMIC_PATHFINDING_DISABLED|INVALID_(?:GOAL|START)|NO_(?:NAVMESH|VALID_DESTINATION)|OTHER|TARGET_GONE|(?:PARCEL_)?UNREACHABLE)|(?:GOAL|SLOWDOWN_DISTANCE)_REACHED)|TRAVERSAL_TYPE(?:_(?:FAST|NONE|SLOW))?|CONTENT_TYPE_(?:ATOM|FORM|HTML|JSON|LLSD|RSS|TEXT|XHTML|XML)|GCNP_(?:RADIUS|STATIC)|(?:PATROL|WANDER)_PAUSE_AT_WAYPOINTS|OPT_(?:AVATAR|CHARACTER|EXCLUSION_VOLUME|LEGACY_LINKSET|MATERIAL_VOLUME|OTHER|STATIC_OBSTACLE|WALKABLE)|SIM_STAT_PCT_CHARS_STEPPED)\b'
lsl_constants_integer_boolean = r'\b(?:FALSE|TRUE)\b'
lsl_constants_rotation = r'\b(?:ZERO_ROTATION)\b'
lsl_constants_string = r'\b(?:EOF|JSON_(?:ARRAY|DELETE|FALSE|INVALID|NULL|NUMBER|OBJECT|STRING|TRUE)|NULL_KEY|TEXTURE_(?:BLANK|DEFAULT|MEDIA|PLYWOOD|TRANSPARENT)|URL_REQUEST_(?:GRANTED|DENIED))\b'
lsl_constants_vector = r'\b(?:TOUCH_INVALID_(?:TEXCOORD|VECTOR)|ZERO_VECTOR)\b'
lsl_invalid_broken = r'\b(?:LAND_(?:LARGE|MEDIUM|SMALL)_BRUSH)\b'
lsl_invalid_deprecated = r'\b(?:ATTACH_[LR]PEC|DATA_RATING|OBJECT_ATTACHMENT_(?:GEOMETRY_BYTES|SURFACE_AREA)|PRIM_(?:CAST_SHADOWS|MATERIAL_LIGHT|TYPE_LEGACY)|PSYS_SRC_(?:INNER|OUTER)ANGLE|VEHICLE_FLAG_NO_FLY_UP|ll(?:Cloud|Make(?:Explosion|Fountain|Smoke|Fire)|RemoteDataSetRegion|Sound(?:Preload)?|XorBase64Strings(?:Correct)?))\b'
lsl_invalid_illegal = r'\b(?:event)\b'
lsl_invalid_unimplemented = r'\b(?:CHARACTER_(?:MAX_ANGULAR_(?:ACCEL|SPEED)|TURN_SPEED_MULTIPLIER)|PERMISSION_(?:CHANGE_(?:JOINTS|PERMISSIONS)|RELEASE_OWNERSHIP|REMAP_CONTROLS)|PRIM_PHYSICS_MATERIAL|PSYS_SRC_OBJ_REL_MASK|ll(?:CollisionSprite|(?:Stop)?PointAt|(?:(?:Refresh|Set)Prim)URL|(?:Take|Release)Camera|RemoteLoadScript))\b'
lsl_reserved_godmode = r'\b(?:ll(?:GodLikeRezObject|Set(?:Inventory|Object)PermMask))\b'
lsl_reserved_log = r'\b(?:print)\b'
lsl_operators = r'\+\+|\-\-|<<|>>|&&?|\|\|?|\^|~|[!%<>=*+\-/]=?'
tokens = {
'root':
[
(r'//.*?\n', Comment.Single),
(r'/\*', Comment.Multiline, 'comment'),
(r'"', String.Double, 'string'),
(lsl_keywords, Keyword),
(lsl_types, Keyword.Type),
(lsl_states, Name.Class),
(lsl_events, Name.Builtin),
(lsl_functions_builtin, Name.Function),
(lsl_constants_float, Keyword.Constant),
(lsl_constants_integer, Keyword.Constant),
(lsl_constants_integer_boolean, Keyword.Constant),
(lsl_constants_rotation, Keyword.Constant),
(lsl_constants_string, Keyword.Constant),
(lsl_constants_vector, Keyword.Constant),
(lsl_invalid_broken, Error),
(lsl_invalid_deprecated, Error),
(lsl_invalid_illegal, Error),
(lsl_invalid_unimplemented, Error),
(lsl_reserved_godmode, Keyword.Reserved),
(lsl_reserved_log, Keyword.Reserved),
(r'\b([a-zA-Z_]\w*)\b', Name.Variable),
(r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d*', Number.Float),
(r'(\d+\.\d*|\.\d+)', Number.Float),
(r'0[xX][0-9a-fA-F]+', Number.Hex),
(r'\d+', Number.Integer),
(lsl_operators, Operator),
(r':=?', Error),
(r'[,;{}()\[\]]', Punctuation),
(r'\n+', Whitespace),
(r'\s+', Whitespace)
],
'comment':
[
(r'[^*/]+', Comment.Multiline),
(r'/\*', Comment.Multiline, '#push'),
(r'\*/', Comment.Multiline, '#pop'),
(r'[*/]', Comment.Multiline)
],
'string':
[
(r'\\([nt"\\])', String.Escape),
(r'"', String.Double, '#pop'),
(r'\\.', Error),
(r'[^"\\]+', String.Double),
]
}
class AppleScriptLexer(RegexLexer):
"""
For `AppleScript source code
<http://developer.apple.com/documentation/AppleScript/
Conceptual/AppleScriptLangGuide>`_,
including `AppleScript Studio
<http://developer.apple.com/documentation/AppleScript/
Reference/StudioReference>`_.
Contributed by Andreas Amann <aamann@mac.com>.
.. versionadded:: 1.0
"""
name = 'AppleScript'
aliases = ['applescript']
filenames = ['*.applescript']
flags = re.MULTILINE | re.DOTALL
Identifiers = r'[a-zA-Z]\w*'
# XXX: use words() for all of these
Literals = ('AppleScript', 'current application', 'false', 'linefeed',
'missing value', 'pi', 'quote', 'result', 'return', 'space',
'tab', 'text item delimiters', 'true', 'version')
Classes = ('alias ', 'application ', 'boolean ', 'class ', 'constant ',
'date ', 'file ', 'integer ', 'list ', 'number ', 'POSIX file ',
'real ', 'record ', 'reference ', 'RGB color ', 'script ',
'text ', 'unit types', '(?:Unicode )?text', 'string')
BuiltIn = ('attachment', 'attribute run', 'character', 'day', 'month',
'paragraph', 'word', 'year')
HandlerParams = ('about', 'above', 'against', 'apart from', 'around',
'aside from', 'at', 'below', 'beneath', 'beside',
'between', 'for', 'given', 'instead of', 'on', 'onto',
'out of', 'over', 'since')
Commands = ('ASCII (character|number)', 'activate', 'beep', 'choose URL',
'choose application', 'choose color', 'choose file( name)?',
'choose folder', 'choose from list',
'choose remote application', 'clipboard info',
'close( access)?', 'copy', 'count', 'current date', 'delay',
'delete', 'display (alert|dialog)', 'do shell script',
'duplicate', 'exists', 'get eof', 'get volume settings',
'info for', 'launch', 'list (disks|folder)', 'load script',
'log', 'make', 'mount volume', 'new', 'offset',
'open( (for access|location))?', 'path to', 'print', 'quit',
'random number', 'read', 'round', 'run( script)?',
'say', 'scripting components',
'set (eof|the clipboard to|volume)', 'store script',
'summarize', 'system attribute', 'system info',
'the clipboard', 'time to GMT', 'write', 'quoted form')
References = ('(in )?back of', '(in )?front of', '[0-9]+(st|nd|rd|th)',
'first', 'second', 'third', 'fourth', 'fifth', 'sixth',
'seventh', 'eighth', 'ninth', 'tenth', 'after', 'back',
'before', 'behind', 'every', 'front', 'index', 'last',
'middle', 'some', 'that', 'through', 'thru', 'where', 'whose')
Operators = ("and", "or", "is equal", "equals", "(is )?equal to", "is not",
"isn't", "isn't equal( to)?", "is not equal( to)?",
"doesn't equal", "does not equal", "(is )?greater than",
"comes after", "is not less than or equal( to)?",
"isn't less than or equal( to)?", "(is )?less than",
"comes before", "is not greater than or equal( to)?",
"isn't greater than or equal( to)?",
"(is )?greater than or equal( to)?", "is not less than",
"isn't less than", "does not come before",
"doesn't come before", "(is )?less than or equal( to)?",
"is not greater than", "isn't greater than",
"does not come after", "doesn't come after", "starts? with",
"begins? with", "ends? with", "contains?", "does not contain",
"doesn't contain", "is in", "is contained by", "is not in",
"is not contained by", "isn't contained by", "div", "mod",
"not", "(a )?(ref( to)?|reference to)", "is", "does")
Control = ('considering', 'else', 'error', 'exit', 'from', 'if',
'ignoring', 'in', 'repeat', 'tell', 'then', 'times', 'to',
'try', 'until', 'using terms from', 'while', 'whith',
'with timeout( of)?', 'with transaction', 'by', 'continue',
'end', 'its?', 'me', 'my', 'return', 'of', 'as')
Declarations = ('global', 'local', 'prop(erty)?', 'set', 'get')
Reserved = ('but', 'put', 'returning', 'the')
StudioClasses = ('action cell', 'alert reply', 'application', 'box',
'browser( cell)?', 'bundle', 'button( cell)?', 'cell',
'clip view', 'color well', 'color-panel',
'combo box( item)?', 'control',
'data( (cell|column|item|row|source))?', 'default entry',
'dialog reply', 'document', 'drag info', 'drawer',
'event', 'font(-panel)?', 'formatter',
'image( (cell|view))?', 'matrix', 'menu( item)?', 'item',
'movie( view)?', 'open-panel', 'outline view', 'panel',
'pasteboard', 'plugin', 'popup button',
'progress indicator', 'responder', 'save-panel',
'scroll view', 'secure text field( cell)?', 'slider',
'sound', 'split view', 'stepper', 'tab view( item)?',
'table( (column|header cell|header view|view))',
'text( (field( cell)?|view))?', 'toolbar( item)?',
'user-defaults', 'view', 'window')
StudioEvents = ('accept outline drop', 'accept table drop', 'action',
'activated', 'alert ended', 'awake from nib', 'became key',
'became main', 'begin editing', 'bounds changed',
'cell value', 'cell value changed', 'change cell value',
'change item value', 'changed', 'child of item',
'choose menu item', 'clicked', 'clicked toolbar item',
'closed', 'column clicked', 'column moved',
'column resized', 'conclude drop', 'data representation',
'deminiaturized', 'dialog ended', 'document nib name',
'double clicked', 'drag( (entered|exited|updated))?',
'drop', 'end editing', 'exposed', 'idle', 'item expandable',
'item value', 'item value changed', 'items changed',
'keyboard down', 'keyboard up', 'launched',
'load data representation', 'miniaturized', 'mouse down',
'mouse dragged', 'mouse entered', 'mouse exited',
'mouse moved', 'mouse up', 'moved',
'number of browser rows', 'number of items',
'number of rows', 'open untitled', 'opened', 'panel ended',
'parameters updated', 'plugin loaded', 'prepare drop',
'prepare outline drag', 'prepare outline drop',
'prepare table drag', 'prepare table drop',
'read from file', 'resigned active', 'resigned key',
'resigned main', 'resized( sub views)?',
'right mouse down', 'right mouse dragged',
'right mouse up', 'rows changed', 'scroll wheel',
'selected tab view item', 'selection changed',
'selection changing', 'should begin editing',
'should close', 'should collapse item',
'should end editing', 'should expand item',
'should open( untitled)?',
'should quit( after last window closed)?',
'should select column', 'should select item',
'should select row', 'should select tab view item',
'should selection change', 'should zoom', 'shown',
'update menu item', 'update parameters',
'update toolbar item', 'was hidden', 'was miniaturized',
'will become active', 'will close', 'will dismiss',
'will display browser cell', 'will display cell',
'will display item cell', 'will display outline cell',
'will finish launching', 'will hide', 'will miniaturize',
'will move', 'will open', 'will pop up', 'will quit',
'will resign active', 'will resize( sub views)?',
'will select tab view item', 'will show', 'will zoom',
'write to file', 'zoomed')
StudioCommands = ('animate', 'append', 'call method', 'center',
'close drawer', 'close panel', 'display',
'display alert', 'display dialog', 'display panel', 'go',
'hide', 'highlight', 'increment', 'item for',
'load image', 'load movie', 'load nib', 'load panel',
'load sound', 'localized string', 'lock focus', 'log',
'open drawer', 'path for', 'pause', 'perform action',
'play', 'register', 'resume', 'scroll', 'select( all)?',
'show', 'size to fit', 'start', 'step back',
'step forward', 'stop', 'synchronize', 'unlock focus',
'update')
StudioProperties = ('accepts arrow key', 'action method', 'active',
'alignment', 'allowed identifiers',
'allows branch selection', 'allows column reordering',
'allows column resizing', 'allows column selection',
'allows customization',
'allows editing text attributes',
'allows empty selection', 'allows mixed state',
'allows multiple selection', 'allows reordering',
'allows undo', 'alpha( value)?', 'alternate image',
'alternate increment value', 'alternate title',
'animation delay', 'associated file name',
'associated object', 'auto completes', 'auto display',
'auto enables items', 'auto repeat',
'auto resizes( outline column)?',
'auto save expanded items', 'auto save name',
'auto save table columns', 'auto saves configuration',
'auto scroll', 'auto sizes all columns to fit',
'auto sizes cells', 'background color', 'bezel state',
'bezel style', 'bezeled', 'border rect', 'border type',
'bordered', 'bounds( rotation)?', 'box type',
'button returned', 'button type',
'can choose directories', 'can choose files',
'can draw', 'can hide',
'cell( (background color|size|type))?', 'characters',
'class', 'click count', 'clicked( data)? column',
'clicked data item', 'clicked( data)? row',
'closeable', 'collating', 'color( (mode|panel))',
'command key down', 'configuration',
'content(s| (size|view( margins)?))?', 'context',
'continuous', 'control key down', 'control size',
'control tint', 'control view',
'controller visible', 'coordinate system',
'copies( on scroll)?', 'corner view', 'current cell',
'current column', 'current( field)? editor',
'current( menu)? item', 'current row',
'current tab view item', 'data source',
'default identifiers', 'delta (x|y|z)',
'destination window', 'directory', 'display mode',
'displayed cell', 'document( (edited|rect|view))?',
'double value', 'dragged column', 'dragged distance',
'dragged items', 'draws( cell)? background',
'draws grid', 'dynamically scrolls', 'echos bullets',
'edge', 'editable', 'edited( data)? column',
'edited data item', 'edited( data)? row', 'enabled',
'enclosing scroll view', 'ending page',
'error handling', 'event number', 'event type',
'excluded from windows menu', 'executable path',
'expanded', 'fax number', 'field editor', 'file kind',
'file name', 'file type', 'first responder',
'first visible column', 'flipped', 'floating',
'font( panel)?', 'formatter', 'frameworks path',
'frontmost', 'gave up', 'grid color', 'has data items',
'has horizontal ruler', 'has horizontal scroller',
'has parent data item', 'has resize indicator',
'has shadow', 'has sub menu', 'has vertical ruler',
'has vertical scroller', 'header cell', 'header view',
'hidden', 'hides when deactivated', 'highlights by',
'horizontal line scroll', 'horizontal page scroll',
'horizontal ruler view', 'horizontally resizable',
'icon image', 'id', 'identifier',
'ignores multiple clicks',
'image( (alignment|dims when disabled|frame style|scaling))?',
'imports graphics', 'increment value',
'indentation per level', 'indeterminate', 'index',
'integer value', 'intercell spacing', 'item height',
'key( (code|equivalent( modifier)?|window))?',
'knob thickness', 'label', 'last( visible)? column',
'leading offset', 'leaf', 'level', 'line scroll',
'loaded', 'localized sort', 'location', 'loop mode',
'main( (bunde|menu|window))?', 'marker follows cell',
'matrix mode', 'maximum( content)? size',
'maximum visible columns',
'menu( form representation)?', 'miniaturizable',
'miniaturized', 'minimized image', 'minimized title',
'minimum column width', 'minimum( content)? size',
'modal', 'modified', 'mouse down state',
'movie( (controller|file|rect))?', 'muted', 'name',
'needs display', 'next state', 'next text',
'number of tick marks', 'only tick mark values',
'opaque', 'open panel', 'option key down',
'outline table column', 'page scroll', 'pages across',
'pages down', 'palette label', 'pane splitter',
'parent data item', 'parent window', 'pasteboard',
'path( (names|separator))?', 'playing',
'plays every frame', 'plays selection only', 'position',
'preferred edge', 'preferred type', 'pressure',
'previous text', 'prompt', 'properties',
'prototype cell', 'pulls down', 'rate',
'released when closed', 'repeated',
'requested print time', 'required file type',
'resizable', 'resized column', 'resource path',
'returns records', 'reuses columns', 'rich text',
'roll over', 'row height', 'rulers visible',
'save panel', 'scripts path', 'scrollable',
'selectable( identifiers)?', 'selected cell',
'selected( data)? columns?', 'selected data items?',
'selected( data)? rows?', 'selected item identifier',
'selection by rect', 'send action on arrow key',
'sends action when done editing', 'separates columns',
'separator item', 'sequence number', 'services menu',
'shared frameworks path', 'shared support path',
'sheet', 'shift key down', 'shows alpha',
'shows state by', 'size( mode)?',
'smart insert delete enabled', 'sort case sensitivity',
'sort column', 'sort order', 'sort type',
'sorted( data rows)?', 'sound', 'source( mask)?',
'spell checking enabled', 'starting page', 'state',
'string value', 'sub menu', 'super menu', 'super view',
'tab key traverses cells', 'tab state', 'tab type',
'tab view', 'table view', 'tag', 'target( printer)?',
'text color', 'text container insert',
'text container origin', 'text returned',
'tick mark position', 'time stamp',
'title(d| (cell|font|height|position|rect))?',
'tool tip', 'toolbar', 'trailing offset', 'transparent',
'treat packages as directories', 'truncated labels',
'types', 'unmodified characters', 'update views',
'use sort indicator', 'user defaults',
'uses data source', 'uses ruler',
'uses threaded animation',
'uses title from previous column', 'value wraps',
'version',
'vertical( (line scroll|page scroll|ruler view))?',
'vertically resizable', 'view',
'visible( document rect)?', 'volume', 'width', 'window',
'windows menu', 'wraps', 'zoomable', 'zoomed')
tokens = {
'root': [
(r'\s+', Text),
(u'¬\\n', String.Escape),
(r"'s\s+", Text), # This is a possessive, consider moving
(r'(--|#).*?$', Comment),
(r'\(\*', Comment.Multiline, 'comment'),
(r'[(){}!,.:]', Punctuation),
(u'(«)([^»]+)(»)',
bygroups(Text, Name.Builtin, Text)),
(r'\b((?:considering|ignoring)\s*)'
r'(application responses|case|diacriticals|hyphens|'
r'numeric strings|punctuation|white space)',
bygroups(Keyword, Name.Builtin)),
(u'(-|\\*|\\+|&|≠|>=?|<=?|=|≥|≤|/|÷|\\^)', Operator),
(r"\b(%s)\b" % '|'.join(Operators), Operator.Word),
(r'^(\s*(?:on|end)\s+)'
r'(%s)' % '|'.join(StudioEvents[::-1]),
bygroups(Keyword, Name.Function)),
(r'^(\s*)(in|on|script|to)(\s+)', bygroups(Text, Keyword, Text)),
(r'\b(as )(%s)\b' % '|'.join(Classes),
bygroups(Keyword, Name.Class)),
(r'\b(%s)\b' % '|'.join(Literals), Name.Constant),
(r'\b(%s)\b' % '|'.join(Commands), Name.Builtin),
(r'\b(%s)\b' % '|'.join(Control), Keyword),
(r'\b(%s)\b' % '|'.join(Declarations), Keyword),
(r'\b(%s)\b' % '|'.join(Reserved), Name.Builtin),
(r'\b(%s)s?\b' % '|'.join(BuiltIn), Name.Builtin),
(r'\b(%s)\b' % '|'.join(HandlerParams), Name.Builtin),
(r'\b(%s)\b' % '|'.join(StudioProperties), Name.Attribute),
(r'\b(%s)s?\b' % '|'.join(StudioClasses), Name.Builtin),
(r'\b(%s)\b' % '|'.join(StudioCommands), Name.Builtin),
(r'\b(%s)\b' % '|'.join(References), Name.Builtin),
(r'"(\\\\|\\"|[^"])*"', String.Double),
(r'\b(%s)\b' % Identifiers, Name.Variable),
(r'[-+]?(\d+\.\d*|\d*\.\d+)(E[-+][0-9]+)?', Number.Float),
(r'[-+]?\d+', Number.Integer),
],
'comment': [
('\(\*', Comment.Multiline, '#push'),
('\*\)', Comment.Multiline, '#pop'),
('[^*(]+', Comment.Multiline),
('[*(]', Comment.Multiline),
],
}
class RexxLexer(RegexLexer):
"""
`Rexx <http://www.rexxinfo.org/>`_ is a scripting language available for
a wide range of different platforms with its roots found on mainframe
systems. It is popular for I/O- and data based tasks and can act as glue
language to bind different applications together.
.. versionadded:: 2.0
"""
name = 'Rexx'
aliases = ['rexx', 'arexx']
filenames = ['*.rexx', '*.rex', '*.rx', '*.arexx']
mimetypes = ['text/x-rexx']
flags = re.IGNORECASE
tokens = {
'root': [
(r'\s', Whitespace),
(r'/\*', Comment.Multiline, 'comment'),
(r'"', String, 'string_double'),
(r"'", String, 'string_single'),
(r'[0-9]+(\.[0-9]+)?(e[+-]?[0-9])?', Number),
(r'([a-z_]\w*)(\s*)(:)(\s*)(procedure)\b',
bygroups(Name.Function, Whitespace, Operator, Whitespace,
Keyword.Declaration)),
(r'([a-z_]\w*)(\s*)(:)',
bygroups(Name.Label, Whitespace, Operator)),
include('function'),
include('keyword'),
include('operator'),
(r'[a-z_]\w*', Text),
],
'function': [
(words((
'abbrev', 'abs', 'address', 'arg', 'b2x', 'bitand', 'bitor', 'bitxor',
'c2d', 'c2x', 'center', 'charin', 'charout', 'chars', 'compare',
'condition', 'copies', 'd2c', 'd2x', 'datatype', 'date', 'delstr',
'delword', 'digits', 'errortext', 'form', 'format', 'fuzz', 'insert',
'lastpos', 'left', 'length', 'linein', 'lineout', 'lines', 'max',
'min', 'overlay', 'pos', 'queued', 'random', 'reverse', 'right', 'sign',
'sourceline', 'space', 'stream', 'strip', 'substr', 'subword', 'symbol',
'time', 'trace', 'translate', 'trunc', 'value', 'verify', 'word',
'wordindex', 'wordlength', 'wordpos', 'words', 'x2b', 'x2c', 'x2d',
'xrange'), suffix=r'(\s*)(\()'),
bygroups(Name.Builtin, Whitespace, Operator)),
],
'keyword': [
(r'(address|arg|by|call|do|drop|else|end|exit|for|forever|if|'
r'interpret|iterate|leave|nop|numeric|off|on|options|parse|'
r'pull|push|queue|return|say|select|signal|to|then|trace|until|'
r'while)\b', Keyword.Reserved),
],
'operator': [
(r'(-|//|/|\(|\)|\*\*|\*|\\<<|\\<|\\==|\\=|\\>>|\\>|\\|\|\||\||'
r'&&|&|%|\+|<<=|<<|<=|<>|<|==|=|><|>=|>>=|>>|>|¬<<|¬<|¬==|¬=|'
r'¬>>|¬>|¬|\.|,)', Operator),
],
'string_double': [
(r'[^"\n]+', String),
(r'""', String),
(r'"', String, '#pop'),
(r'\n', Text, '#pop'), # Stray linefeed also terminates strings.
],
'string_single': [
(r'[^\'\n]', String),
(r'\'\'', String),
(r'\'', String, '#pop'),
(r'\n', Text, '#pop'), # Stray linefeed also terminates strings.
],
'comment': [
(r'[^*]+', Comment.Multiline),
(r'\*/', Comment.Multiline, '#pop'),
(r'\*', Comment.Multiline),
]
}
_c = lambda s: re.compile(s, re.MULTILINE)
_ADDRESS_COMMAND_PATTERN = _c(r'^\s*address\s+command\b')
_ADDRESS_PATTERN = _c(r'^\s*address\s+')
_DO_WHILE_PATTERN = _c(r'^\s*do\s+while\b')
_IF_THEN_DO_PATTERN = _c(r'^\s*if\b.+\bthen\s+do\s*$')
_PROCEDURE_PATTERN = _c(r'^\s*([a-z_]\w*)(\s*)(:)(\s*)(procedure)\b')
_ELSE_DO_PATTERN = _c(r'\belse\s+do\s*$')
_PARSE_ARG_PATTERN = _c(r'^\s*parse\s+(upper\s+)?(arg|value)\b')
PATTERNS_AND_WEIGHTS = (
(_ADDRESS_COMMAND_PATTERN, 0.2),
(_ADDRESS_PATTERN, 0.05),
(_DO_WHILE_PATTERN, 0.1),
(_ELSE_DO_PATTERN, 0.1),
(_IF_THEN_DO_PATTERN, 0.1),
(_PROCEDURE_PATTERN, 0.5),
(_PARSE_ARG_PATTERN, 0.2),
)
def analyse_text(text):
"""
Check for inital comment and patterns that distinguish Rexx from other
C-like languages.
"""
if re.search(r'/\*\**\s*rexx', text, re.IGNORECASE):
# Header matches MVS Rexx requirements, this is certainly a Rexx
# script.
return 1.0
elif text.startswith('/*'):
# Header matches general Rexx requirements; the source code might
# still be any language using C comments such as C++, C# or Java.
lowerText = text.lower()
result = sum(weight
for (pattern, weight) in RexxLexer.PATTERNS_AND_WEIGHTS
if pattern.search(lowerText)) + 0.01
return min(result, 1.0)
class MOOCodeLexer(RegexLexer):
"""
For `MOOCode <http://www.moo.mud.org/>`_ (the MOO scripting
language).
.. versionadded:: 0.9
"""
name = 'MOOCode'
filenames = ['*.moo']
aliases = ['moocode', 'moo']
mimetypes = ['text/x-moocode']
tokens = {
'root': [
# Numbers
(r'(0|[1-9][0-9_]*)', Number.Integer),
# Strings
(r'"(\\\\|\\"|[^"])*"', String),
# exceptions
(r'(E_PERM|E_DIV)', Name.Exception),
# db-refs
(r'((#[-0-9]+)|(\$\w+))', Name.Entity),
# Keywords
(r'\b(if|else|elseif|endif|for|endfor|fork|endfork|while'
r'|endwhile|break|continue|return|try'
r'|except|endtry|finally|in)\b', Keyword),
# builtins
(r'(random|length)', Name.Builtin),
# special variables
(r'(player|caller|this|args)', Name.Variable.Instance),
# skip whitespace
(r'\s+', Text),
(r'\n', Text),
# other operators
(r'([!;=,{}&|:.\[\]@()<>?]+)', Operator),
# function call
(r'(\w+)(\()', bygroups(Name.Function, Operator)),
# variables
(r'(\w+)', Text),
]
}
class HybrisLexer(RegexLexer):
"""
For `Hybris <http://www.hybris-lang.org>`_ source code.
.. versionadded:: 1.4
"""
name = 'Hybris'
aliases = ['hybris', 'hy']
filenames = ['*.hy', '*.hyb']
mimetypes = ['text/x-hybris', 'application/x-hybris']
flags = re.MULTILINE | re.DOTALL
tokens = {
'root': [
# method names
(r'^(\s*(?:function|method|operator\s+)+?)'
r'([a-zA-Z_]\w*)'
r'(\s*)(\()', bygroups(Keyword, Name.Function, Text, Operator)),
(r'[^\S\n]+', Text),
(r'//.*?\n', Comment.Single),
(r'/\*.*?\*/', Comment.Multiline),
(r'@[a-zA-Z_][\w.]*', Name.Decorator),
(r'(break|case|catch|next|default|do|else|finally|for|foreach|of|'
r'unless|if|new|return|switch|me|throw|try|while)\b', Keyword),
(r'(extends|private|protected|public|static|throws|function|method|'
r'operator)\b', Keyword.Declaration),
(r'(true|false|null|__FILE__|__LINE__|__VERSION__|__LIB_PATH__|'
r'__INC_PATH__)\b', Keyword.Constant),
(r'(class|struct)(\s+)',
bygroups(Keyword.Declaration, Text), 'class'),
(r'(import|include)(\s+)',
bygroups(Keyword.Namespace, Text), 'import'),
(words((
'gc_collect', 'gc_mm_items', 'gc_mm_usage', 'gc_collect_threshold',
'urlencode', 'urldecode', 'base64encode', 'base64decode', 'sha1', 'crc32', 'sha2',
'md5', 'md5_file', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'exp',
'fabs', 'floor', 'fmod', 'log', 'log10', 'pow', 'sin', 'sinh', 'sqrt', 'tan', 'tanh',
'isint', 'isfloat', 'ischar', 'isstring', 'isarray', 'ismap', 'isalias', 'typeof',
'sizeof', 'toint', 'tostring', 'fromxml', 'toxml', 'binary', 'pack', 'load', 'eval',
'var_names', 'var_values', 'user_functions', 'dyn_functions', 'methods', 'call',
'call_method', 'mknod', 'mkfifo', 'mount', 'umount2', 'umount', 'ticks', 'usleep',
'sleep', 'time', 'strtime', 'strdate', 'dllopen', 'dlllink', 'dllcall', 'dllcall_argv',
'dllclose', 'env', 'exec', 'fork', 'getpid', 'wait', 'popen', 'pclose', 'exit', 'kill',
'pthread_create', 'pthread_create_argv', 'pthread_exit', 'pthread_join', 'pthread_kill',
'smtp_send', 'http_get', 'http_post', 'http_download', 'socket', 'bind', 'listen',
'accept', 'getsockname', 'getpeername', 'settimeout', 'connect', 'server', 'recv',
'send', 'close', 'print', 'println', 'printf', 'input', 'readline', 'serial_open',
'serial_fcntl', 'serial_get_attr', 'serial_get_ispeed', 'serial_get_ospeed',
'serial_set_attr', 'serial_set_ispeed', 'serial_set_ospeed', 'serial_write',
'serial_read', 'serial_close', 'xml_load', 'xml_parse', 'fopen', 'fseek', 'ftell',
'fsize', 'fread', 'fwrite', 'fgets', 'fclose', 'file', 'readdir', 'pcre_replace', 'size',
'pop', 'unmap', 'has', 'keys', 'values', 'length', 'find', 'substr', 'replace', 'split',
'trim', 'remove', 'contains', 'join'), suffix=r'\b'),
Name.Builtin),
(words((
'MethodReference', 'Runner', 'Dll', 'Thread', 'Pipe', 'Process',
'Runnable', 'CGI', 'ClientSocket', 'Socket', 'ServerSocket',
'File', 'Console', 'Directory', 'Exception'), suffix=r'\b'),
Keyword.Type),
(r'"(\\\\|\\"|[^"])*"', String),
(r"'\\.'|'[^\\]'|'\\u[0-9a-f]{4}'", String.Char),
(r'(\.)([a-zA-Z_]\w*)',
bygroups(Operator, Name.Attribute)),
(r'[a-zA-Z_]\w*:', Name.Label),
(r'[a-zA-Z_$]\w*', Name),
(r'[~^*!%&\[\](){}<>|+=:;,./?\-@]+', Operator),
(r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
(r'0x[0-9a-f]+', Number.Hex),
(r'[0-9]+L?', Number.Integer),
(r'\n', Text),
],
'class': [
(r'[a-zA-Z_]\w*', Name.Class, '#pop')
],
'import': [
(r'[\w.]+\*?', Name.Namespace, '#pop')
],
}
|
HuygensING/bioport-tools | refs/heads/master | gerbrandyutils/tests/__init__.py | 17 | ##########################################################################
# Copyright (C) 2009 - 2014 Huygens ING & Gerbrandy S.R.L.
#
# This file is part of bioport.
#
# bioport is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program. If not, see
# <http://www.gnu.org/licenses/gpl-3.0.html>.
##########################################################################
|
yoer/hue | refs/heads/master | apps/spark/src/spark/tests.py | 1198 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. 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.
|
mincoin-project/mincoin | refs/heads/master | contrib/devtools/security-check.py | 120 | #!/usr/bin/env python
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Perform basic ELF security checks on a series of executables.
Exit status will be 0 if successful, and the program will be silent.
Otherwise the exit status will be 1 and it will log which executables failed which checks.
Needs `readelf` (for ELF) and `objdump` (for PE).
'''
from __future__ import division,print_function,unicode_literals
import subprocess
import sys
import os
READELF_CMD = os.getenv('READELF', '/usr/bin/readelf')
OBJDUMP_CMD = os.getenv('OBJDUMP', '/usr/bin/objdump')
NONFATAL = {'HIGH_ENTROPY_VA'} # checks which are non-fatal for now but only generate a warning
def check_ELF_PIE(executable):
'''
Check for position independent executable (PIE), allowing for address space randomization.
'''
p = subprocess.Popen([READELF_CMD, '-h', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
ok = False
for line in stdout.split(b'\n'):
line = line.split()
if len(line)>=2 and line[0] == b'Type:' and line[1] == b'DYN':
ok = True
return ok
def get_ELF_program_headers(executable):
'''Return type and flags for ELF program headers'''
p = subprocess.Popen([READELF_CMD, '-l', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
in_headers = False
count = 0
headers = []
for line in stdout.split(b'\n'):
if line.startswith(b'Program Headers:'):
in_headers = True
if line == b'':
in_headers = False
if in_headers:
if count == 1: # header line
ofs_typ = line.find(b'Type')
ofs_offset = line.find(b'Offset')
ofs_flags = line.find(b'Flg')
ofs_align = line.find(b'Align')
if ofs_typ == -1 or ofs_offset == -1 or ofs_flags == -1 or ofs_align == -1:
raise ValueError('Cannot parse elfread -lW output')
elif count > 1:
typ = line[ofs_typ:ofs_offset].rstrip()
flags = line[ofs_flags:ofs_align].rstrip()
headers.append((typ, flags))
count += 1
return headers
def check_ELF_NX(executable):
'''
Check that no sections are writable and executable (including the stack)
'''
have_wx = False
have_gnu_stack = False
for (typ, flags) in get_ELF_program_headers(executable):
if typ == b'GNU_STACK':
have_gnu_stack = True
if b'W' in flags and b'E' in flags: # section is both writable and executable
have_wx = True
return have_gnu_stack and not have_wx
def check_ELF_RELRO(executable):
'''
Check for read-only relocations.
GNU_RELRO program header must exist
Dynamic section must have BIND_NOW flag
'''
have_gnu_relro = False
for (typ, flags) in get_ELF_program_headers(executable):
# Note: not checking flags == 'R': here as linkers set the permission differently
# This does not affect security: the permission flags of the GNU_RELRO program header are ignored, the PT_LOAD header determines the effective permissions.
# However, the dynamic linker need to write to this area so these are RW.
# Glibc itself takes care of mprotecting this area R after relocations are finished.
# See also http://permalink.gmane.org/gmane.comp.gnu.binutils/71347
if typ == b'GNU_RELRO':
have_gnu_relro = True
have_bindnow = False
p = subprocess.Popen([READELF_CMD, '-d', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
for line in stdout.split(b'\n'):
tokens = line.split()
if len(tokens)>1 and tokens[1] == b'(BIND_NOW)' or (len(tokens)>2 and tokens[1] == b'(FLAGS)' and b'BIND_NOW' in tokens[2]):
have_bindnow = True
return have_gnu_relro and have_bindnow
def check_ELF_Canary(executable):
'''
Check for use of stack canary
'''
p = subprocess.Popen([READELF_CMD, '--dyn-syms', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
ok = False
for line in stdout.split(b'\n'):
if b'__stack_chk_fail' in line:
ok = True
return ok
def get_PE_dll_characteristics(executable):
'''
Get PE DllCharacteristics bits.
Returns a tuple (arch,bits) where arch is 'i386:x86-64' or 'i386'
and bits is the DllCharacteristics value.
'''
p = subprocess.Popen([OBJDUMP_CMD, '-x', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
arch = ''
bits = 0
for line in stdout.split('\n'):
tokens = line.split()
if len(tokens)>=2 and tokens[0] == 'architecture:':
arch = tokens[1].rstrip(',')
if len(tokens)>=2 and tokens[0] == 'DllCharacteristics':
bits = int(tokens[1],16)
return (arch,bits)
IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA = 0x0020
IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE = 0x0040
IMAGE_DLL_CHARACTERISTICS_NX_COMPAT = 0x0100
def check_PE_DYNAMIC_BASE(executable):
'''PIE: DllCharacteristics bit 0x40 signifies dynamicbase (ASLR)'''
(arch,bits) = get_PE_dll_characteristics(executable)
reqbits = IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE
return (bits & reqbits) == reqbits
# On 64 bit, must support high-entropy 64-bit address space layout randomization in addition to DYNAMIC_BASE
# to have secure ASLR.
def check_PE_HIGH_ENTROPY_VA(executable):
'''PIE: DllCharacteristics bit 0x20 signifies high-entropy ASLR'''
(arch,bits) = get_PE_dll_characteristics(executable)
if arch == 'i386:x86-64':
reqbits = IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA
else: # Unnecessary on 32-bit
assert(arch == 'i386')
reqbits = 0
return (bits & reqbits) == reqbits
def check_PE_NX(executable):
'''NX: DllCharacteristics bit 0x100 signifies nxcompat (DEP)'''
(arch,bits) = get_PE_dll_characteristics(executable)
return (bits & IMAGE_DLL_CHARACTERISTICS_NX_COMPAT) == IMAGE_DLL_CHARACTERISTICS_NX_COMPAT
CHECKS = {
'ELF': [
('PIE', check_ELF_PIE),
('NX', check_ELF_NX),
('RELRO', check_ELF_RELRO),
('Canary', check_ELF_Canary)
],
'PE': [
('DYNAMIC_BASE', check_PE_DYNAMIC_BASE),
('HIGH_ENTROPY_VA', check_PE_HIGH_ENTROPY_VA),
('NX', check_PE_NX)
]
}
def identify_executable(executable):
with open(filename, 'rb') as f:
magic = f.read(4)
if magic.startswith(b'MZ'):
return 'PE'
elif magic.startswith(b'\x7fELF'):
return 'ELF'
return None
if __name__ == '__main__':
retval = 0
for filename in sys.argv[1:]:
try:
etype = identify_executable(filename)
if etype is None:
print('%s: unknown format' % filename)
retval = 1
continue
failed = []
warning = []
for (name, func) in CHECKS[etype]:
if not func(filename):
if name in NONFATAL:
warning.append(name)
else:
failed.append(name)
if failed:
print('%s: failed %s' % (filename, ' '.join(failed)))
retval = 1
if warning:
print('%s: warning %s' % (filename, ' '.join(warning)))
except IOError:
print('%s: cannot open' % filename)
retval = 1
exit(retval)
|
junhuac/MQUIC | refs/heads/master | depot_tools/external_bin/gsutil/gsutil_4.15/gsutil/third_party/boto/tests/integration/kinesis/test_kinesis.py | 99 | # Copyright (c) 2013 Amazon.com, Inc. or its affiliates.
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import time
import boto
from tests.compat import unittest
from boto.kinesis.exceptions import ResourceNotFoundException
class TimeoutError(Exception):
pass
class TestKinesis(unittest.TestCase):
def setUp(self):
self.kinesis = boto.connect_kinesis()
def test_kinesis(self):
kinesis = self.kinesis
# Create a new stream
kinesis.create_stream('test', 1)
self.addCleanup(self.kinesis.delete_stream, 'test')
# Wait for the stream to be ready
tries = 0
while tries < 10:
tries += 1
time.sleep(15)
response = kinesis.describe_stream('test')
if response['StreamDescription']['StreamStatus'] == 'ACTIVE':
shard_id = response['StreamDescription']['Shards'][0]['ShardId']
break
else:
raise TimeoutError('Stream is still not active, aborting...')
# Make a tag.
kinesis.add_tags_to_stream(stream_name='test', tags={'foo': 'bar'})
# Check that the correct tag is there.
response = kinesis.list_tags_for_stream(stream_name='test')
self.assertEqual(len(response['Tags']), 1)
self.assertEqual(response['Tags'][0],
{'Key':'foo', 'Value': 'bar'})
# Remove the tag and ensure it is removed.
kinesis.remove_tags_from_stream(stream_name='test', tag_keys=['foo'])
response = kinesis.list_tags_for_stream(stream_name='test')
self.assertEqual(len(response['Tags']), 0)
# Get ready to process some data from the stream
response = kinesis.get_shard_iterator('test', shard_id, 'TRIM_HORIZON')
shard_iterator = response['ShardIterator']
# Write some data to the stream
data = 'Some data ...'
record = {
'Data': data,
'PartitionKey': data,
}
response = kinesis.put_record('test', data, data)
response = kinesis.put_records([record, record.copy()], 'test')
# Wait for the data to show up
tries = 0
num_collected = 0
num_expected_records = 3
collected_records = []
while tries < 100:
tries += 1
time.sleep(1)
response = kinesis.get_records(shard_iterator)
shard_iterator = response['NextShardIterator']
for record in response['Records']:
if 'Data' in record:
collected_records.append(record['Data'])
num_collected += 1
if num_collected >= num_expected_records:
self.assertEqual(num_expected_records, num_collected)
break
else:
raise TimeoutError('No records found, aborting...')
# Read the data, which should be the same as what we wrote
for record in collected_records:
self.assertEqual(data, record)
def test_describe_non_existent_stream(self):
with self.assertRaises(ResourceNotFoundException) as cm:
self.kinesis.describe_stream('this-stream-shouldnt-exist')
# Assert things about the data we passed along.
self.assertEqual(cm.exception.error_code, None)
self.assertTrue('not found' in cm.exception.message)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.