code
stringlengths 2
1.05M
| repo_name
stringlengths 5
104
| path
stringlengths 4
251
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
"""
This is revision from 3058ab9d9d4875589638cc45e84b59e7e1d7c9c3 of
https://github.com/ojii/django-load.
ANY changes to this file, be it upstream fixes or changes for the cms *must* be
documented clearly within this file with comments.
For documentation on how to use the functions described in this file, please
refer to http://django-load.readthedocs.org/en/latest/index.html.
"""
import imp
import traceback # changed
from django.conf import settings
from django.utils.importlib import import_module
def get_module(app, modname, verbose, failfast):
"""
Internal function to load a module from a single app.
"""
module_name = '%s.%s' % (app, modname)
# the module *should* exist - raise an error if it doesn't
app_mod = import_module(app)
try:
imp.find_module(modname, app_mod.__path__)
except ImportError:
# this ImportError will be due to the module not existing
# so here we can silently ignore it. But an ImportError
# when we import_module() should not be ignored
if failfast:
raise
elif verbose:
print(u"Could not find %r from %r" % (modname, app)) # changed
traceback.print_exc() # changed
return None
module = import_module(module_name)
if verbose:
print(u"Loaded %r from %r" % (modname, app))
return module
def load(modname, verbose=False, failfast=False):
"""
Loads all modules with name 'modname' from all installed apps.
If verbose is True, debug information will be printed to stdout.
If failfast is True, import errors will not be surpressed.
"""
for app in settings.INSTALLED_APPS:
get_module(app, modname, verbose, failfast)
def iterload(modname, verbose=False, failfast=False):
"""
Loads all modules with name 'modname' from all installed apps and returns
and iterator of those modules.
If verbose is True, debug information will be printed to stdout.
If failfast is True, import errors will not be surpressed.
"""
for app in settings.INSTALLED_APPS:
module = get_module(app, modname, verbose, failfast)
if module:
yield module
def load_object(import_path):
"""
Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the
likes.
Import paths should be: "mypackage.mymodule.MyObject". It then imports the
module up until the last dot and tries to get the attribute after that dot
from the imported module.
If the import path does not contain any dots, a TypeError is raised.
If the module cannot be imported, an ImportError is raised.
If the attribute does not exist in the module, a AttributeError is raised.
"""
if '.' not in import_path:
raise TypeError(
"'import_path' argument to 'django_load.core.load_object' must "
"contain at least one dot."
)
module_name, object_name = import_path.rsplit('.', 1)
module = import_module(module_name)
return getattr(module, object_name)
def iterload_objects(import_paths):
"""
Load a list of objects.
"""
for import_path in import_paths:
yield load_object(import_path)
def get_subclasses(c):
"""
Get all subclasses of a given class
"""
subclasses = c.__subclasses__()
for d in list(subclasses):
subclasses.extend(get_subclasses(d))
return subclasses
|
SurfasJones/djcmsrc3
|
venv/lib/python2.7/site-packages/cms/utils/django_load.py
|
Python
|
mit
| 3,456
|
#!/usr/bin/python
# Import required Python libraries
import RPi.GPIO as GPIO
import time
# Use BM GPIO references instead of physical pin numbers
GPIO.setmode(GPIO.BOARD)
GaragePin = 11
GPIO.setup(GaragePin, GPIO.OUT)
GPIO.output(GaragePin, GPIO.HIGH)
def trigger():
GPIO.output(GaragePin, GPIO.LOW)
time.sleep(0.5)
GPIO.output(GaragePin, GPIO.HIGH)
GPIO.cleanup()
try:
trigger()
except KeyboardInterrupt:
print " Quit" # Reset GPIO settings
|
JayJanarthanan/RPi-Garage-Opener
|
garage-node/door.py
|
Python
|
mit
| 497
|
from vision import *
from vision.alearn import marginals
from vision import visualize, model
from vision.toymaker import *
import os
import multiprocessing
import logging
import random
import ImageColor
import pickle
logging.basicConfig(level = logging.INFO)
#g = frameiterator("/scratch/vatic/uci-basketball")
#b = [Box(39, 215, 39 + 38, 215 + 95, 15744),
# #Box(303, 223, 303 + 38, 223 + 95, 15793)]
# Box(488, 247, 488 + 38, 247 + 95, 15895)]
#g = frameiterator("/scratch/vatic/uci-basketball")
#b = [Box(283, 259, 283 + 57, 259 + 99, 42785),
# Box(489, 243, 489 + 47, 243 + 114, 42897)]
#stop = 42907
#g = frameiterator("/scratch/virat/frames/VIRAT_S_000003")
#b = [Box(346, 170, 17 + 346, 170 + 42, 275)]
#stop = 450
#g = frameiterator("/scratch/vatic/syn-yi-levels")
#b = [Box(153, 124, 153 + 61, 124 + 148, 0)]
#b2 = [Box(153, 124, 153 + 61, 124 + 148, 0),
# Box(550, 82, 550 + 61, 82 + 148, 756)]
#stop = 1349
#g = frameiterator("/scratch/vatic/syn-bounce-level")
#b = [Box(365, 70, 365 + 63, 70 + 297, 278)]
#b = [Box(365, 70, 365 + 63, 70 + 297, 278),
# Box(624, 56, 624 + 66, 56 + 318, 1655)]
#
#stop = 1768
g = frameiterator("/scratch/vatic/syn-occlusion2")
b = [Box(592, 48, 592 + 103, 48 + 326, 20)]
stop = 22
g = frameiterator("/scratch/virat/frames/VIRAT_S_000302_04_000453_000484")
b = [Box(156, 96, 156 + 50, 96 + 24, 270),
Box(391, 83, 391 + 48, 83 + 22, 459)]
stop = 500
pool = multiprocessing.Pool(24)
frame, score, path, marginals = marginals.pick(b, g,
last = stop,
pool = pool,
pairwisecost = .01,
dim = (40, 40),
sigma = 1,
erroroverlap = 0.5,
hogbin = 8,
clickradius = 10,
c = 1)
pickle.dump(marginals, open("occlusion.pkl", "w"))
visualize.save(visualize.highlight_paths(g, [path]), lambda x: "tmp/path{0}.jpg".format(x))
print "frame {0} with score {1}".format(frame, score)
|
WangDequan/pyvision
|
experiments/marginals.py
|
Python
|
mit
| 2,264
|
# Copyright (C) 2007 Sadique Puthen <sputhenp@redhat.com>
# This file is part of the sos project: https://github.com/sosreport/sos
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# version 2 of the GNU General Public License.
#
# See the LICENSE file in the source distribution for further information.
from sos.report.plugins import Plugin, RedHatPlugin
class Smartcard(Plugin, RedHatPlugin):
short_desc = 'PKCS#11 smart cards'
plugin_name = 'smartcard'
profiles = ('security', 'identity', 'hardware')
files = ('/etc/pam_pkcs11/pam_pkcs11.conf',)
packages = ('pam_pkcs11', 'pcsc-tools', 'opensc')
def setup(self):
self.add_copy_spec([
"/etc/reader.conf",
"/etc/reader.conf.d/",
"/etc/pam_pkcs11/",
"/etc/opensc-*.conf"
])
self.add_cmd_output([
"pklogin_finder debug",
"ls -nl /usr/lib*/pam_pkcs11/",
"pcsc_scan",
"pkcs11-tool --show-info",
"pkcs11-tool --list-mechanisms",
"pkcs11-tool --list-slots",
"pkcs11-tool --list-objects"
])
self.add_forbidden_path("/etc/pam_pkcs11/nssdb/key[3-4].db")
# vim: set et ts=4 sw=4 :
|
slashdd/sos
|
sos/report/plugins/smartcard.py
|
Python
|
gpl-2.0
| 1,326
|
#!/usr/bin/env python
__author__ = 'jsommers@colgate.edu'
from abc import ABCMeta, abstractmethod
class FlowExporter(object):
__metaclass__ = ABCMeta
def __init__(self, rname):
self.routername = str(rname)
@abstractmethod
def exportflow(self, ts, flet):
pass
@abstractmethod
def shutdown(self):
pass
## obsolete test code: FIXME
# def main():
# f1 = Flowlet(ipaddr.IPAddress('10.0.1.1'), ipaddr.IPAddress('192.168.5.2'), 17, 5, 42)
# f1.flowstart = time.time()
# f1.flowend = time.time() + 10
# f1.srcport = 2345
# f1.dstport = 6789
# f2 = copy.copy(f1)
# f2.flowend = time.time() + 20
# f2.ipproto = 6
# f2.tcpflags = 0xff
# f2.srcport = 9999
# f2.dstport = 80
# f2.iptos = 0x08
# textexp = text_export_factory('testrouter')
# textexp.exportflow(time.time(),f1)
# textexp.exportflow(time.time(),f2)
# textexp.shutdown()
# if __name__ == '__main__':
# main()
|
ashishtanwer/DFS
|
flowexport/flowexporter.py
|
Python
|
gpl-2.0
| 986
|
# -*- coding: utf-8 -*-
#
# test_stdp_nn_synapses.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# NEST is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see <http://www.gnu.org/licenses/>.
# This script tests the stdp_nn_symm_synapse, stdp_nn_pre_centered_synapse,
# and stdp_nn_restr_synapse in NEST.
import nest
import unittest
from math import exp
@nest.ll_api.check_stack
class STDPNNSynapsesTest(unittest.TestCase):
"""
Test the weight change by STDP
with three nearest-neighbour spike pairing schemes.
The test is performed by generating two Poisson spike trains,
feeding them to NEST as presynaptic and postsynaptic,
then reconstructing the expected weight change outside of NEST
and comparing the actual weight change to the expected one.
The outside-of-NEST STDP implementation made here is not very beautiful,
but deliberately made so in order to be as independent from NEST as
possible: it does not involve additional variables for eligibility traces.
Instead, it directly iterates through the spike history.
"""
def setUp(self):
self.resolution = 0.1 # [ms]
self.presynaptic_firing_rate = 20.0 # [Hz]
self.postsynaptic_firing_rate = 20.0 # [Hz]
self.simulation_duration = 1e+4 # [ms]
self.hardcoded_trains_length = 15. # [ms]
self.synapse_parameters = {
"receptor_type": 1,
"delay": self.resolution,
# STDP constants
"lambda": 0.01,
"alpha": 0.85,
"mu_plus": 0.0,
"mu_minus": 0.0,
"tau_plus": 16.8,
"Wmax": 1.0,
# initial weight
"weight": 0.5
}
self.neuron_parameters = {
"tau_minus": 33.7
}
def do_nest_simulation_and_compare_to_reproduced_weight(self,
pairing_scheme):
synapse_model = "stdp_" + pairing_scheme + "_synapse"
self.synapse_parameters["synapse_model"] = synapse_model
pre_spikes, post_spikes, weight_by_nest = self.do_the_nest_simulation()
weight_reproduced_independently = self.reproduce_weight_drift(
pre_spikes, post_spikes,
self.synapse_parameters["weight"])
self.assertAlmostEqual(
weight_reproduced_independently,
weight_by_nest,
msg=synapse_model + " test: "
"Resulting synaptic weight %e "
"differs from expected %e" % (
weight_by_nest, weight_reproduced_independently))
def do_the_nest_simulation(self):
"""
This function is where calls to NEST reside.
Returns the generated pre- and post spike sequences
and the resulting weight established by STDP.
"""
nest.set_verbosity('M_WARNING')
nest.ResetKernel()
nest.resolution = self.resolution
neurons = nest.Create(
"parrot_neuron",
2,
params=self.neuron_parameters)
presynaptic_neuron = neurons[0]
postsynaptic_neuron = neurons[1]
generators = nest.Create(
"poisson_generator",
2,
params=({"rate": self.presynaptic_firing_rate,
"stop": (self.simulation_duration - self.hardcoded_trains_length)},
{"rate": self.postsynaptic_firing_rate,
"stop": (self.simulation_duration - self.hardcoded_trains_length)}))
presynaptic_generator = generators[0]
postsynaptic_generator = generators[1]
# While the random sequences, fairly long, would supposedly
# reveal small differences in the weight change between NEST
# and ours, some low-probability events (say, coinciding
# spikes) can well not have occured. To generate and
# test every possible combination of pre/post precedence, we
# append some hardcoded spike sequences:
# pre: 1 5 6 7 9 11 12 13
# post: 2 3 4 8 9 10 12
(
hardcoded_pre_times,
hardcoded_post_times
) = [
[
self.simulation_duration - self.hardcoded_trains_length + t
for t in train
] for train in (
(1, 5, 6, 7, 9, 11, 12, 13),
(2, 3, 4, 8, 9, 10, 12)
)
]
spike_senders = nest.Create(
"spike_generator",
2,
params=({"spike_times": hardcoded_pre_times},
{"spike_times": hardcoded_post_times})
)
pre_spike_generator = spike_senders[0]
post_spike_generator = spike_senders[1]
# The recorder is to save the randomly generated spike trains.
spike_recorder = nest.Create("spike_recorder")
nest.Connect(presynaptic_generator + pre_spike_generator, presynaptic_neuron,
syn_spec={"synapse_model": "static_synapse"})
nest.Connect(postsynaptic_generator + post_spike_generator, postsynaptic_neuron,
syn_spec={"synapse_model": "static_synapse"})
nest.Connect(presynaptic_neuron + postsynaptic_neuron, spike_recorder,
syn_spec={"synapse_model": "static_synapse"})
# The synapse of interest itself
nest.Connect(presynaptic_neuron, postsynaptic_neuron,
syn_spec=self.synapse_parameters)
plastic_synapse_of_interest = nest.GetConnections(synapse_model=self.synapse_parameters["synapse_model"])
nest.Simulate(self.simulation_duration)
all_spikes = nest.GetStatus(spike_recorder, keys='events')[0]
pre_spikes = all_spikes['times'][all_spikes['senders'] == presynaptic_neuron.tolist()[0]]
post_spikes = all_spikes['times'][all_spikes['senders'] == postsynaptic_neuron.tolist()[0]]
weight = nest.GetStatus(plastic_synapse_of_interest, keys='weight')[0]
return (pre_spikes, post_spikes, weight)
def reproduce_weight_drift(self, _pre_spikes, _post_spikes,
_initial_weight):
"""
Returns the total weight change of the synapse
computed outside of NEST.
The implementation imitates a step-based simulation: evolving time, we
trigger a weight update when the time equals one of the spike moments.
"""
# These are defined just for convenience,
# STDP is evaluated on exact times nonetheless
pre_spikes_forced_to_grid = [int(t / self.resolution) for t in _pre_spikes]
post_spikes_forced_to_grid = [int(t / self.resolution) for t in _post_spikes]
t_previous_pre = -1
t_previous_post = -1
w = _initial_weight
n_steps = int(self.simulation_duration / self.resolution)
for time_in_simulation_steps in range(n_steps):
if time_in_simulation_steps in pre_spikes_forced_to_grid:
# A presynaptic spike occured now.
# Adjusting the current time to make it exact.
t = _pre_spikes[pre_spikes_forced_to_grid.index(time_in_simulation_steps)]
# Evaluating the depression rule.
if self.synapse_parameters["synapse_model"] == "stdp_nn_restr_synapse":
current_nearest_neighbour_pair_is_suitable = (
t_previous_post > t_previous_pre)
# If '<', t_previous_post has already been paired
# with t_previous_pre, thus due to the restricted
# pairing scheme we do not account it.
if (self.synapse_parameters["synapse_model"] == "stdp_nn_symm_synapse" or
self.synapse_parameters["synapse_model"] == "stdp_nn_pre_centered_synapse"):
# The current pre-spike is simply paired with the
# nearest post-spike.
current_nearest_neighbour_pair_is_suitable = True
if (current_nearest_neighbour_pair_is_suitable and t_previous_post != -1):
# Otherwise, if == -1, there have been
# no post-spikes yet, and nothing to pair with.
w = self.depress(t_previous_post - t, w)
# Memorizing the current pre-spike to account it
# further with the next post-spike.
t_previous_pre = t
if time_in_simulation_steps in post_spikes_forced_to_grid:
# A postsynaptic spike occured now.
# Adjusting the current time to make it exact.
t = _post_spikes[post_spikes_forced_to_grid.index(time_in_simulation_steps)]
# A post-spike is actually accounted in STDP only after
# it backpropagates through the dendrite.
t += self.synapse_parameters["delay"]
# Evaluating the facilitation rule.
if self.synapse_parameters["synapse_model"] == "stdp_nn_symm_synapse":
if t_previous_pre != -1: # otherwise nothing to pair with
w = self.facilitate(t - t_previous_pre, w)
if self.synapse_parameters["synapse_model"] == "stdp_nn_restr_synapse":
if t_previous_pre != -1: # if == -1, nothing to pair with
if t_previous_pre > t_previous_post:
# if '<', t_previous_pre has already been
# paired with t_previous_post, thus due to the
# restricted pairing scheme we do not account it.
w = self.facilitate(t - t_previous_pre, w)
if self.synapse_parameters["synapse_model"] == "stdp_nn_pre_centered_synapse":
if t_previous_pre != -1: # if == -1, nothing to pair with
# Going through all preceding presynaptic spikes
# that are later than the previous post.
i = list(_pre_spikes).index(t_previous_pre)
while i >= 0:
if _pre_spikes[i] <= t_previous_post:
# _pre_spikes[i] has already been
# paired with t_previous_post,
# thus we do not account it.
break
w = self.facilitate(t - _pre_spikes[i], w)
i -= 1
# Memorizing the current post-spike to account it further
# with the next pre-spike.
t_previous_post = t
return w
def facilitate(self, _delta_t, w):
if _delta_t == 0:
return w
w += (
self.synapse_parameters["lambda"] *
((1 - w / self.synapse_parameters["Wmax"])**self.synapse_parameters["mu_plus"]) *
exp(-1 * _delta_t / self.synapse_parameters["tau_plus"])
)
if w > self.synapse_parameters["Wmax"]:
w = self.synapse_parameters["Wmax"]
return w
def depress(self, _delta_t, w):
if _delta_t == 0:
return w
w -= (
self.synapse_parameters["lambda"] *
self.synapse_parameters["alpha"] *
((w / self.synapse_parameters["Wmax"])**self.synapse_parameters["mu_minus"]) *
exp(_delta_t / self.neuron_parameters["tau_minus"])
)
if w < 0:
w = 0
return w
def test_nn_symm_synapse(self):
self.do_nest_simulation_and_compare_to_reproduced_weight("nn_symm")
def test_nn_pre_centered_synapse(self):
self.do_nest_simulation_and_compare_to_reproduced_weight("nn_pre_centered")
def test_nn_restr_synapse(self):
self.do_nest_simulation_and_compare_to_reproduced_weight("nn_restr")
def suite():
# makeSuite is sort of obsolete http://bugs.python.org/issue2721
# using loadTestsFromTestCase instead.
suite = unittest.TestLoader().loadTestsFromTestCase(STDPNNSynapsesTest)
return unittest.TestSuite([suite])
def run():
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite())
if __name__ == "__main__":
run()
|
sdiazpier/nest-simulator
|
testsuite/pytests/test_stdp_nn_synapses.py
|
Python
|
gpl-2.0
| 12,892
|
# -*- coding: utf-8 -*-
#
# Copyright 2004-2006 Zuza Software Foundation
#
# This file is part of translate.
#
# translate 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.
#
# translate 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/>.
"""Code to perform various operations, mostly on po files."""
|
phlax/translate
|
translate/tools/__init__.py
|
Python
|
gpl-2.0
| 801
|
# -*- coding: utf-8 -*-
from translate.filters import autocorrect
class TestAutocorrect:
def correct(self, msgid, msgstr, expected):
"""helper to run correct function from autocorrect module"""
corrected = autocorrect.correct(msgid, msgstr)
print(repr(msgid))
print(repr(msgstr))
print(msgid.encode('utf-8'))
print(msgstr.encode('utf-8'))
print((corrected or u"").encode('utf-8'))
assert corrected == expected
def test_empty_target(self):
"""test that we do nothing with an empty target"""
self.correct(u"String...", u"", None)
def test_correct_ellipsis(self):
"""test that we convert single … or ... to match source and target"""
self.correct(u"String...", u"Translated…", u"Translated...")
self.correct(u"String…", u"Translated...", u"Translated…")
def test_correct_spacestart_spaceend(self):
"""test that we can correct leading and trailing space errors"""
self.correct(u"Simple string", u"Dimpled ring ", u"Dimpled ring")
self.correct(u"Simple string", u" Dimpled ring", u"Dimpled ring")
self.correct(u" Simple string", u"Dimpled ring", u" Dimpled ring")
self.correct(u"Simple string ", u"Dimpled ring", u"Dimpled ring ")
def test_correct_start_capitals(self):
"""test that we can correct the starting capital"""
self.correct(u"Simple string", u"dimpled ring", u"Dimpled ring")
self.correct(u"simple string", u"Dimpled ring", u"dimpled ring")
def test_correct_end_punc(self):
"""test that we can correct end punctuation"""
self.correct(u"Simple string:", u"Dimpled ring", u"Dimpled ring:")
#self.correct(u"Simple string: ", u"Dimpled ring", u"Dimpled ring: ")
self.correct(u"Simple string.", u"Dimpled ring", u"Dimpled ring.")
#self.correct(u"Simple string. ", u"Dimpled ring", u"Dimpled ring. ")
self.correct(u"Simple string?", u"Dimpled ring", u"Dimpled ring?")
def test_correct_combinations(self):
"""test that we can correct combinations of failures"""
self.correct(u"Simple string:", u"Dimpled ring ", u"Dimpled ring:")
self.correct(u"simple string ", u"Dimpled ring", u"dimpled ring ")
self.correct(u"Simple string...", u"dimpled ring..", u"Dimpled ring...")
self.correct(u"Simple string:", u"Dimpled ring ", u"Dimpled ring:")
def test_nothing_to_do(self):
"""test that when nothing changes we return None"""
self.correct(u"Some text", u"A translation", None)
|
diorcety/translate
|
translate/filters/test_autocorrect.py
|
Python
|
gpl-2.0
| 2,599
|
#!/usr/bin/env python
#-*- coding: utf-8 -*-
###########################################################################
## ##
## Copyrights Frédéric Rodrigo 2013 ##
## ##
## This program is free software: you can redistribute it and/or modify ##
## it under the terms of the GNU General Public License as published by ##
## the Free Software Foundation, either version 3 of the License, or ##
## (at your option) any later version. ##
## ##
## This program is distributed in the hope that it will be useful, ##
## but WITHOUT ANY WARRANTY; without even the implied warranty of ##
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ##
## GNU General Public License for more details. ##
## ##
## You should have received a copy of the GNU General Public License ##
## along with this program. If not, see <http://www.gnu.org/licenses/>. ##
## ##
###########################################################################
from modules.OsmoseTranslation import T_
from .Analyser_Osmosis import Analyser_Osmosis
sql00 = """
CREATE TEMP TABLE restrictions AS
SELECT
id,
tags,
SUM(CASE WHEN member_role = 'from' AND member_type = 'W' THEN 1 ELSE 0 END) AS nwfrom,
SUM(CASE WHEN member_role = 'from' AND member_type != 'W' THEN 1 ELSE 0 END) AS nofrom,
SUM(CASE WHEN member_role = 'to' AND member_type = 'W' THEN 1 ELSE 0 END) AS nwto,
SUM(CASE WHEN member_role = 'to' AND member_type != 'W' THEN 1 ELSE 0 END) AS noto,
SUM(CASE WHEN member_role = 'via' AND member_type = 'N' THEN 1 ELSE 0 END) AS nnvia,
SUM(CASE WHEN member_role = 'via' AND member_type = 'W' THEN 1 ELSE 0 END) AS nwvia,
SUM(CASE WHEN member_role = 'via' AND member_type = 'R' THEN 1 ELSE 0 END) AS nrvia,
FALSE AS bad_member,
FALSE AS bad_continuity,
NULL::INTEGER AS direction
FROM
{0}relations AS relations
JOIN relation_members ON
relations.id = relation_members.relation_id
WHERE
relations.tags?'type' AND
relations.tags->'type' = 'restriction' AND
relations.tags?'restriction'
GROUP BY
relations.id,
relations.tags
"""
sql10 = """
(
SELECT
id,
ST_AsText(relation_locate(id))
FROM
restrictions
WHERE
tags->'restriction' NOT IN ('no_entry', 'no_exit') AND
NOT (
nwfrom = 1 AND
nofrom = 0 AND
nwto = 1 AND
noto = 0 AND
((nnvia = 1 AND nwvia = 0) OR (nnvia = 0 AND nwvia > 0)) AND
nrvia = 0
)
) UNION ALL (
SELECT
id,
ST_AsText(relation_locate(id))
FROM
restrictions
WHERE
tags->'restriction' = 'no_entry' AND
NOT (
nwfrom >= 1 AND
nofrom = 0 AND
nwto = 1 AND
noto = 0 AND
((nnvia = 1 AND nwvia = 0) OR (nnvia = 0 AND nwvia > 0)) AND
nrvia = 0
)
) UNION ALL (
SELECT
id,
ST_AsText(relation_locate(id))
FROM
restrictions
WHERE
tags->'restriction' = 'no_exit' AND
NOT (
nwfrom = 1 AND
nofrom = 0 AND
nwto >= 1 AND
noto = 0 AND
((nnvia = 1 AND nwvia = 0) OR (nnvia = 0 AND nwvia > 0)) AND
nrvia = 0
)
)
"""
sql20 = """
CREATE TEMP TABLE bad_member AS
SELECT DISTINCT ON (restrictions.id, ways.id)
restrictions.id AS rid,
ways.id AS wid,
ways.linestring
FROM
restrictions
JOIN relation_members ON
restrictions.id = relation_members.relation_id AND
relation_members.member_type = 'W' AND
relation_members.member_role IN ('from', 'via', 'to')
JOIN ways ON
ways.id = relation_members.member_id AND
NOT ways.tags?'highway'
WHERE
nwfrom = 1 AND
nofrom = 0 AND
nwto = 1 AND
noto = 0 AND
((nnvia = 1 AND nwvia = 0) OR (nnvia = 0 AND nwvia > 0)) AND
nrvia = 0
ORDER BY
restrictions.id,
ways.id
"""
sql21 = """
UPDATE
restrictions
SET
bad_member = TRUE
FROM
bad_member
WHERE
restrictions.id = bad_member.rid
"""
sql22 = """
SELECT
rid,
wid,
ST_AsText(way_locate(linestring))
FROM
bad_member
"""
sql30 = """
CREATE TEMP TABLE bad_continuity AS
SELECT
restrictions.id AS rid
FROM
restrictions
JOIN relation_members ON
restrictions.id = relation_members.relation_id AND
relation_members.member_type = 'W' AND
relation_members.member_role IN ('from', 'via', 'to')
JOIN highways AS ways ON
ways.id = relation_members.member_id AND
NOT is_area AND
NOT is_construction AND
ST_NPoints(ways.linestring) > 1
WHERE
nwfrom = 1 AND
nofrom = 0 AND
nwto = 1 AND
noto = 0 AND
((nnvia = 1 AND nwvia = 0) OR (nnvia = 0 AND nwvia > 0)) AND
nrvia = 0 AND
NOT bad_member
GROUP BY
restrictions.id
HAVING
ST_NumGeometries(ST_LineMerge(ST_Collect(ways.linestring))) > 1
"""
sql31 = """
UPDATE
restrictions
SET
bad_continuity = TRUE
FROM
bad_continuity
WHERE
restrictions.id = bad_continuity.rid
"""
sql32 = """
SELECT
rid,
ST_AsText(relation_locate(rid))
FROM
bad_continuity
"""
sql40 = """
SELECT
restrictions.id,
ways.id,
ST_AsText(way_locate(ways.linestring))
FROM
restrictions
JOIN relation_members AS rmfrom ON
restrictions.id = rmfrom.relation_id AND
rmfrom.member_role = 'from'
JOIN ways ON
ways.id = rmfrom.member_id AND
ways.tags != ''::hstore AND
ways.tags?'oneway' AND
ways.tags->'oneway' IN ('yes', '-1')
JOIN relation_members AS rmvia ON
restrictions.id = rmvia.relation_id AND
rmvia.member_role = 'via'
JOIN nodes AS via ON
via.id = rmvia.member_id
WHERE
nwfrom = 1 AND
nofrom = 0 AND
nwto = 1 AND
noto = 0 AND
(nnvia = 1 AND nwvia = 0) AND
nrvia = 0 AND
NOT bad_member AND
NOT bad_continuity AND
(
(ways.tags->'oneway' = 'yes' AND ways.nodes[1] = via.id) OR
(ways.tags->'oneway' = '-1' AND ways.nodes[array_length(ways.nodes, 1)] = via.id)
) AND
NOT EXISTS (SELECT * FROM each(ways.tags) WHERE key LIKE 'oneway:%' AND value = 'no');
"""
sql41 = """
SELECT
restrictions.id,
ways.id,
ST_AsText(way_locate(ways.linestring))
FROM
restrictions
JOIN relation_members AS rmfrom ON
restrictions.id = rmfrom.relation_id AND
rmfrom.member_role = 'to'
JOIN ways ON
ways.id = rmfrom.member_id AND
ways.tags != ''::hstore AND
ways.tags?'oneway' AND
ways.tags->'oneway' IN ('yes', '-1')
JOIN relation_members AS rmvia ON
restrictions.id = rmvia.relation_id AND
rmvia.member_role = 'via'
JOIN nodes AS via ON
via.id = rmvia.member_id
WHERE
nwfrom = 1 AND
nofrom = 0 AND
nwto = 1 AND
noto = 0 AND
(nnvia = 1 AND nwvia = 0) AND
nrvia = 0 AND
NOT bad_member AND
NOT bad_continuity AND
(
(ways.tags->'oneway' = 'yes' AND ways.nodes[array_length(ways.nodes, 1)] = via.id) OR
(ways.tags->'oneway' = '-1' AND ways.nodes[1] = via.id)
) AND
NOT EXISTS (SELECT * FROM each(ways.tags) WHERE key LIKE 'oneway:%' AND value = 'no');
"""
sql50 = """
CREATE TEMP TABLE direction AS
SELECT
restrictions.id AS rid,
restrictions.tags->'restriction' AS type,
(CAST(degrees(
CASE
WHEN
ST_Distance(COALESCE(nodes.geom, ways.linestring), ST_PointN(from_.linestring,1)) <
ST_Distance(COALESCE(nodes.geom, ways.linestring), ST_PointN(from_.linestring,ST_NPoints(from_.linestring)))
THEN
ST_Azimuth(ST_PointN(from_.linestring,2), ST_StartPoint(from_.linestring))
ELSE
ST_Azimuth(ST_PointN(from_.linestring,ST_NPoints(from_.linestring)-1), ST_EndPoint(from_.linestring))
END -
CASE
WHEN
ST_Distance(COALESCE(nodes.geom, ways.linestring), ST_StartPoint(to_.linestring)) <
ST_Distance(COALESCE(nodes.geom, ways.linestring), ST_EndPoint(to_.linestring))
THEN
ST_Azimuth(ST_StartPoint(to_.linestring), ST_PointN(to_.linestring,2))
ELSE
ST_Azimuth(ST_EndPoint(to_.linestring), ST_PointN(to_.linestring,ST_NPoints(to_.linestring)-1))
END
) AS INTEGER) + 360*2) % 360 - 180 AS a
FROM
restrictions
JOIN relation_members AS rmfrom ON
restrictions.id = rmfrom.relation_id AND
rmfrom.member_role = 'from'
JOIN ways AS from_ ON
from_.id = rmfrom.member_id
JOIN relation_members AS rmto ON
restrictions.id = rmto.relation_id AND
rmto.member_role = 'to'
JOIN ways AS to_ ON
to_.id = rmto.member_id
LEFT JOIN relation_members AS rmwvia ON
restrictions.id = rmwvia.relation_id AND
rmwvia.member_role = 'via' AND
rmwvia.member_type = 'W'
LEFT JOIN ways ON
ways.id = rmwvia.member_id
LEFT JOIN relation_members AS rmnvia ON
restrictions.id = rmnvia.relation_id AND
rmnvia.member_role = 'via' AND
rmnvia.member_type = 'N'
LEFT JOIN nodes ON
nodes.id = rmnvia.member_id
WHERE
nwfrom = 1 AND
nofrom = 0 AND
nwto = 1 AND
noto = 0 AND
(nnvia = 1 AND nwvia = 0) AND
nrvia = 0 AND
NOT bad_member
"""
sql51 = """
UPDATE
restrictions
SET
direction = a
FROM
direction
WHERE
restrictions.id = direction.rid
"""
sql52 = """
SELECT
rid,
ST_AsText(relation_locate(rid))
FROM
direction
WHERE
(type IN ('only_straight_on', 'no_straight_on') AND abs(a) < 180-60) OR
(type IN ('only_left_turn', 'no_left_turn') AND (a > 0 OR a < -170)) OR
(type IN ('only_right_turn', 'no_right_turn') AND (a < 0 OR a > 170)) OR
(type IN ('no_u_turn') AND abs(a) > 100)
ORDER BY
type
"""
class Analyser_Osmosis_Relation_Restriction(Analyser_Osmosis):
requires_tables_full = ['highways']
requires_tables_diff = ['highways']
def __init__(self, config, logger = None):
Analyser_Osmosis.__init__(self, config, logger)
self.classs_change[1] = self.def_class(item = 3180, level = 2, tags = ['relation', 'restriction', 'fix:survey'],
title = T_('Restriction relation, wrong number of members'),
detail = T_(
'''Some required member are missing, eg. there is a `from` and `via`
role, but missing the `to` role.'''))
self.classs_change[2] = self.def_class(item = 3180, level = 2, tags = ['relation', 'restriction', 'fix:chair'],
title = T_('Restriction relation, bad member type'))
self.classs_change[3] = self.def_class(item = 3180, level = 2, tags = ['relation', 'restriction', 'fix:chair'],
title = T_('Unconnected restriction relation ways'),
fix = T_(
'''The ways in the restriction must be continuous.'''))
self.classs_change[4] = self.def_class(item = 3180, level = 2, tags = ['relation', 'restriction', 'fix:survey'],
title = T_('Restriction relation, bad oneway direction on "from" or "to" member'),
detail = T_(
'''Impossible to reach the restriction by respecting the oneway.'''))
self.classs_change[5] = self.def_class(item = 3180, level = 2, tags = ['relation', 'restriction', 'fix:survey'],
title = T_('Restriction doesn\'t match topology'),
detail = T_(
'''The shape of the paths described by the way does not correspond to the
restriction.'''))
self.callback10 = lambda res: {"class":1, "data":[self.relation_full, self.positionAsText] }
self.callback20 = lambda res: {"class":2, "data":[self.relation_full, self.way_full, self.positionAsText] }
self.callback30 = lambda res: {"class":3, "data":[self.relation_full, self.positionAsText] }
self.callback40 = lambda res: {"class":4, "subclass": 0, "data":[self.relation_full, self.way_full, self.positionAsText] }
self.callback41 = lambda res: {"class":4, "subclass": 1, "data":[self.relation_full, self.way_full, self.positionAsText] }
self.callback50 = lambda res: {"class":5, "data":[self.relation_full, self.positionAsText] }
def analyser_osmosis_full(self):
self.run(sql00.format(""))
self.run(sql10, self.callback10)
self.run(sql20)
self.run(sql21)
self.run(sql22, self.callback20)
self.run(sql30)
self.run(sql31)
self.run(sql32, self.callback30)
self.run(sql40, self.callback40)
self.run(sql41, self.callback41)
self.run(sql50)
self.run(sql51)
self.run(sql52, self.callback50)
def analyser_osmosis_diff(self):
self.run(sql00.format("touched_"))
self.run(sql10, self.callback10)
self.run(sql20)
self.run(sql21)
self.run(sql22, self.callback20)
self.run(sql30)
self.run(sql31)
self.run(sql32, self.callback30)
self.run(sql40, self.callback40)
self.run(sql41, self.callback41)
self.run(sql50)
self.run(sql51)
self.run(sql52, self.callback50)
|
tkasp/osmose-backend
|
analysers/analyser_osmosis_relation_restriction.py
|
Python
|
gpl-3.0
| 13,460
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2014 Peter Oliver <ansible@mavit.org.uk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
---
module: pkg5_publisher
author: Peter Oliver
short_description: Manages Solaris 11 Image Packaging System publishers
version_added: 1.9
description:
- IPS packages are the native packages in Solaris 11 and higher.
- This modules will configure which publishers a client will download IPS
packages from.
options:
name:
description:
- The publisher's name.
required: true
aliases: [ publisher ]
state:
description:
- Whether to ensure that a publisher is present or absent.
required: false
default: present
choices: [ present, absent ]
sticky:
description:
- Packages installed from a sticky repository can only receive updates
from that repository.
required: false
default: null
choices: [ true, false ]
enabled:
description:
- Is the repository enabled or disabled?
required: false
default: null
choices: [ true, false ]
origin:
description:
- A path or URL to the repository.
- Multiple values may be provided.
required: false
default: null
mirror:
description:
- A path or URL to the repository mirror.
- Multiple values may be provided.
required: false
default: null
'''
EXAMPLES = '''
# Fetch packages for the solaris publisher direct from Oracle:
- pkg5_publisher: name=solaris sticky=true origin=https://pkg.oracle.com/solaris/support/
# Configure a publisher for locally-produced packages:
- pkg5_publisher: name=site origin=https://pkg.example.com/site/
'''
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(required=True, aliases=['publisher']),
state=dict(default='present', choices=['present', 'absent']),
sticky=dict(choices=BOOLEANS),
enabled=dict(choices=BOOLEANS),
# search_after=dict(),
# search_before=dict(),
origin=dict(type='list'),
mirror=dict(type='list'),
)
)
for option in ['origin', 'mirror']:
if module.params[option] == ['']:
module.params[option] = []
if module.params['state'] == 'present':
modify_publisher(module, module.params)
else:
unset_publisher(module, module.params['name'])
def modify_publisher(module, params):
name = params['name']
existing = get_publishers(module)
if name in existing:
for option in ['origin', 'mirror', 'sticky', 'enabled']:
if params[option] != None:
if params[option] != existing[name][option]:
return set_publisher(module, params)
else:
return set_publisher(module, params)
module.exit_json()
def set_publisher(module, params):
name = params['name']
args = []
if params['origin'] != None:
args.append('--remove-origin=*')
args.extend(['--add-origin=' + u for u in params['origin']])
if params['mirror'] != None:
args.append('--remove-mirror=*')
args.extend(['--add-mirror=' + u for u in params['mirror']])
if params['sticky'] != None and params['sticky']:
args.append('--sticky')
elif params['sticky'] != None:
args.append('--non-sticky')
if params['enabled'] != None and params['enabled']:
args.append('--enable')
elif params['enabled'] != None:
args.append('--disable')
rc, out, err = module.run_command(
["pkg", "set-publisher"] + args + [name],
check_rc=True
)
response = {
'rc': rc,
'results': [out],
'msg': err,
'changed': True,
}
module.exit_json(**response)
def unset_publisher(module, publisher):
if not publisher in get_publishers(module):
module.exit_json()
rc, out, err = module.run_command(
["pkg", "unset-publisher", publisher],
check_rc=True
)
response = {
'rc': rc,
'results': [out],
'msg': err,
'changed': True,
}
module.exit_json(**response)
def get_publishers(module):
rc, out, err = module.run_command(["pkg", "publisher", "-Ftsv"], True)
lines = out.splitlines()
keys = lines.pop(0).lower().split("\t")
publishers = {}
for line in lines:
values = dict(zip(keys, map(unstringify, line.split("\t"))))
name = values['publisher']
if not name in publishers:
publishers[name] = dict(
(k, values[k]) for k in ['sticky', 'enabled']
)
publishers[name]['origin'] = []
publishers[name]['mirror'] = []
publishers[name][values['type']].append(values['uri'])
return publishers
def unstringify(val):
if val == "-":
return None
elif val == "true":
return True
elif val == "false":
return False
else:
return val
from ansible.module_utils.basic import *
main()
|
mattbernst/polyhartree
|
support/ansible/modules/extras/packaging/os/pkg5_publisher.py
|
Python
|
gpl-3.0
| 5,651
|
# Copyright 2014 Google Inc. All Rights Reserved.
"""Command for getting health status of backend(s) in a backend service."""
from googlecloudsdk.compute.lib import base_classes
from googlecloudsdk.compute.lib import request_helper
from googlecloudsdk.compute.lib import utils
class GetHealth(base_classes.BaseCommand):
"""Get health status of backend(s) in an backend service."""
@staticmethod
def Args(parser):
base_classes.AddFieldsFlag(parser, 'backendServiceGroupHealth')
parser.add_argument(
'name',
help='The name of the backend service.')
@property
def service(self):
return self.compute.backendServices
@property
def resource_type(self):
return 'backendServiceGroupHealth'
def GetBackendService(self, _):
"""Fetches the backend service resource."""
errors = []
objects = list(request_helper.MakeRequests(
requests=[(self.service,
'Get',
self.messages.ComputeBackendServicesGetRequest(
project=self.project,
backendService=self.backend_service_ref.Name()
))],
http=self.http,
batch_url=self.batch_url,
errors=errors,
custom_get_requests=None))
if errors:
utils.RaiseToolException(
errors,
error_message='Could not fetch backend service:')
return objects[0]
def Run(self, args):
"""Returns a list of backendServiceGroupHealth objects."""
self.backend_service_ref = self.CreateGlobalReference(
args.name, resource_type='backendServices')
backend_service = self.GetBackendService(args)
if not backend_service.backends:
return
# Call GetHealth for each group in the backend service
requests = []
for backend in backend_service.backends:
request_message = self.messages.ComputeBackendServicesGetHealthRequest(
resourceGroupReference=self.messages.ResourceGroupReference(
group=backend.group),
project=self.project,
backendService=self.backend_service_ref.Name())
requests.append((self.service, 'GetHealth', request_message))
errors = []
resources = request_helper.MakeRequests(
requests=requests,
http=self.http,
batch_url=self.batch_url,
errors=errors,
custom_get_requests=None)
for resource in resources:
yield resource
if errors:
utils.RaiseToolException(
errors,
error_message='Could not get health for some groups:')
GetHealth.detailed_help = {
'brief': 'Get backend health statuses from a backend service',
'DESCRIPTION': """\
*{command}* is used to request the current health status of
instances in a backend service. Every group in the service
is checked and the health status of each configured instance
is printed.
If a group contains names of instances that don't exist or
instances that haven't yet been pushed to the load-balancing
system, they will not show up. Those that are listed as
``HEALTHY'' are able to receive load-balanced traffic. Those that
are marked as ``UNHEALTHY'' are either failing the configured
health-check or not responding to it.
Since the health checks are performed continuously and in
a distributed manner, the state returned by this command is
the most recent result of a vote of several redundant health
checks. Backend services that do not have a valid global
forwarding rule referencing it will not be health checked and
so will have no health status.
""",
}
|
harshilasu/LinkurApp
|
y/google-cloud-sdk/lib/googlecloudsdk/compute/subcommands/backend_services/get_health.py
|
Python
|
gpl-3.0
| 3,692
|
# -*- coding: utf-8 -*-
import re
from module.network.RequestFactory import getURL
from module.plugins.Hoster import Hoster
def getInfo(urls):
result = []
for url in urls:
html = getURL(url)
if re.search(StreamCz.OFFLINE_PATTERN, html):
# File offline
result.append((url, 0, 1, url))
else:
result.append((url, 0, 2, url))
yield result
class StreamCz(Hoster):
__name__ = "StreamCz"
__type__ = "hoster"
__version__ = "0.20"
__pattern__ = r'https?://(?:www\.)?stream\.cz/[^/]+/\d+'
__description__ = """Stream.cz hoster plugin"""
__license__ = "GPLv3"
__authors__ = [("zoidberg", "zoidberg@mujmail.cz")]
NAME_PATTERN = r'<link rel="video_src" href="http://www\.stream\.cz/\w+/(\d+)-([^"]+)" />'
OFFLINE_PATTERN = r'<h1 class="commonTitle">Str.nku nebylo mo.n. nal.zt \(404\)</h1>'
CDN_PATTERN = r'<param name="flashvars" value="[^"]*&id=(?P<ID>\d+)(?:&cdnLQ=(?P<cdnLQ>\d*))?(?:&cdnHQ=(?P<cdnHQ>\d*))?(?:&cdnHD=(?P<cdnHD>\d*))?&'
def setup(self):
self.resumeDownload = True
self.multiDL = True
def process(self, pyfile):
self.html = self.load(pyfile.url, decode=True)
if re.search(self.OFFLINE_PATTERN, self.html):
self.offline()
m = re.search(self.CDN_PATTERN, self.html)
if m is None:
self.error(_("CDN_PATTERN not found"))
cdn = m.groupdict()
self.logDebug(cdn)
for cdnkey in ("cdnHD", "cdnHQ", "cdnLQ"):
if cdnkey in cdn and cdn[cdnkey] > '':
cdnid = cdn[cdnkey]
break
else:
self.fail(_("Stream URL not found"))
m = re.search(self.NAME_PATTERN, self.html)
if m is None:
self.error(_("NAME_PATTERN not found"))
pyfile.name = "%s-%s.%s.mp4" % (m.group(2), m.group(1), cdnkey[-2:])
download_url = "http://cdn-dispatcher.stream.cz/?id=" + cdnid
self.logInfo(_("STREAM: %s") % cdnkey[-2:], download_url)
self.download(download_url)
|
immenz/pyload
|
module/plugins/hoster/StreamCz.py
|
Python
|
gpl-3.0
| 2,109
|
from coala_utils.string_processing.Core import unescaped_search_for
from coalib.bears.LocalBear import LocalBear
from coalib.bearlib import deprecate_settings
from coalib.bearlib.languages.LanguageDefinition import LanguageDefinition
from coalib.bearlib.spacing.SpacingHelper import SpacingHelper
from coalib.results.SourceRange import SourceRange
from coalib.results.Result import Result, RESULT_SEVERITY
from coalib.results.AbsolutePosition import AbsolutePosition
from coalib.results.Diff import Diff
from bears.general.AnnotationBear import AnnotationBear
class IndentationBear(LocalBear):
AUTHORS = {'The coala developers'}
AUTHORS_EMAILS = {'coala-devel@googlegroups.com'}
LICENSE = 'AGPL-3.0'
CAN_FIX = {'Formatting'}
BEAR_DEPS = {AnnotationBear} # pragma: no cover
@deprecate_settings(indent_size='tab_width')
def run(self,
filename,
file,
dependency_results: dict,
language: str,
use_spaces: bool=True,
indent_size: int=SpacingHelper.DEFAULT_TAB_WIDTH,
coalang_dir: str=None):
"""
It is a generic indent bear, which looks for a start and end
indent specifier, example: ``{ : }`` where "{" is the start indent
specifier and "}" is the end indent specifier. If the end-specifier
is not given, this bear looks for unindents within the code to
correctly figure out indentation.
It also figures out hanging indents and absolute indentation of
function params or list elements.
It does not however support indents based on keywords yet.
for example:
if(something)
does not get indented
undergoes no change.
WARNING: The IndentationBear is experimental right now, you can report
any issues found to https://github.com/coala/coala-bears
:param filename:
Name of the file that needs to be checked.
:param file:
File that needs to be checked in the form of a list of strings.
:param dependency_results:
Results given by the AnnotationBear.
:param language:
Language to be used for indentation.
:param use_spaces:
Insert spaces instead of tabs for indentation.
:param indent_size:
Number of spaces per indentation level.
:param coalang_dir:
Full path of external directory containing the coalang
file for language.
"""
lang_settings_dict = LanguageDefinition(
language, coalang_dir=coalang_dir)
annotation_dict = dependency_results[AnnotationBear.name][0].contents
# sometimes can't convert strings with ':' to dict correctly
if ':' in dict(lang_settings_dict['indent_types']).keys():
indent_types = dict(lang_settings_dict['indent_types'])
indent_types[':'] = ''
else:
indent_types = dict(lang_settings_dict['indent_types'])
encapsulators = (dict(lang_settings_dict['encapsulators']) if
'encapsulators' in lang_settings_dict else {})
encaps_pos = []
for encapsulator in encapsulators:
encaps_pos += self.get_specified_block_range(
file, filename,
encapsulator, encapsulators[encapsulator],
annotation_dict)
encaps_pos = tuple(sorted(encaps_pos, key=lambda x: x.start.line))
comments = dict(lang_settings_dict['comment_delimiter'])
comments.update(
dict(lang_settings_dict['multiline_comment_delimiters']))
try:
indent_levels = self.get_indent_levels(
file, filename,
indent_types, annotation_dict, encaps_pos, comments)
# This happens only in case of unmatched indents or
# ExpectedIndentError.
except (UnmatchedIndentError, ExpectedIndentError) as e:
yield Result(self, str(e), severity=RESULT_SEVERITY.MAJOR)
return
absolute_indent_levels = self.get_absolute_indent_of_range(
file, filename,
encaps_pos, annotation_dict)
insert = ' '*indent_size if use_spaces else '\t'
no_indent_file = self._get_no_indent_file(file)
new_file = self._get_basic_indent_file(no_indent_file,
indent_levels,
insert)
new_file = self._get_absolute_indent_file(new_file,
absolute_indent_levels,
indent_levels,
insert)
if new_file != list(file):
wholediff = Diff.from_string_arrays(file, new_file)
for diff in wholediff.split_diff():
yield Result(
self,
'The indentation could be changed to improve readability.',
severity=RESULT_SEVERITY.INFO,
affected_code=(diff.range(filename),),
diffs={filename: diff})
def _get_no_indent_file(self, file):
no_indent_file = [line.lstrip() if line.lstrip() else '\n'
for line_nr, line in enumerate(file)]
return no_indent_file
def _get_basic_indent_file(self, no_indent_file, indent_levels, insert):
new_file = []
for line_nr, line in enumerate(no_indent_file):
new_file.append(insert*indent_levels[line_nr] + line
if line is not '\n' else '\n')
return new_file
def _get_absolute_indent_file(self,
indented_file,
absolute_indent_levels,
indent_levels,
insert):
for _range, indent in absolute_indent_levels:
prev_indent = get_indent_of_line(indented_file,
_range.start.line - 1,
length=False)
prev_indent_level = indent_levels[_range.start.line - 1]
for line in range(_range.start.line, _range.end.line):
new_line = (prev_indent + ' '*indent +
insert*(indent_levels[line] - prev_indent_level) +
indented_file[line].lstrip())
indented_file[line] = new_line if new_line.strip() != ''\
else '\n'
return indented_file
def get_absolute_indent_of_range(self,
file,
filename,
encaps_pos,
annotation_dict):
"""
Gets the absolute indentation of all the encapsulators.
:param file: A tuple of strings.
:param filename: Name of file.
:param encaps_pos: A tuple ofSourceRanges of code regions
trapped in between a matching pair of
encapsulators.
:param annotation_dict: A dictionary containing sourceranges of all the
strings and comments within a file.
:return: A tuple of tuples with first element as the
range of encapsulator and second element as the
indent of its elements.
"""
indent_of_range = []
for encaps in encaps_pos:
indent = get_element_indent(file, encaps)
indent_of_range.append((encaps, indent))
return tuple(indent_of_range)
def get_indent_levels(self,
file,
filename,
indent_types,
annotation_dict,
encapsulators,
comments):
"""
Gets the level of indentation of each line.
:param file: File that needs to be checked in the form of
a list of strings.
:param filename: Name of the file that needs to be checked.
:param indent_types: A dictionary with keys as start of indent and
values as their corresponding closing indents.
:param annotation_dict: A dictionary containing sourceranges of all the
strings and comments within a file.
:param encapsulators: A tuple of sourceranges of all encapsulators of
a language.
:param comments: A dict containing all the types of comment
specifiers in a language.
:return: A tuple containing the levels of indentation of
each line.
"""
ranges = []
for indent_specifier in indent_types:
if indent_types[indent_specifier]:
ranges += self.get_specified_block_range(
file, filename,
indent_specifier, indent_types[indent_specifier],
annotation_dict)
else:
ranges += self.get_unspecified_block_range(
file, filename,
indent_specifier, annotation_dict, encapsulators, comments)
ranges = sorted(ranges, key=lambda x: x.start.line)
indent_levels = []
indent, next_indent = 0, 0
for line in range(0, len(file)):
indent = next_indent
for _range in ranges:
if _range.start.line == line + 1:
next_indent += 1
first_ch = file[line].lstrip()[:1]
if(_range.end.line == line + 1 and
first_ch in indent_types.values()):
indent -= 1
next_indent -= 1
elif _range.end.line == line + 1:
next_indent -= 1
indent_levels.append(indent)
return tuple(indent_levels)
def get_specified_block_range(self,
file,
filename,
open_specifier,
close_specifier,
annotation_dict):
"""
Gets a sourceranges of all the indentation blocks present inside the
file.
:param file: File that needs to be checked in the form of
a list of strings.
:param filename: Name of the file that needs to be checked.
:param open_specifier: A character or string indicating that the
block has begun.
:param close_specifier: A character or string indicating that the block
has ended.
:param annotation_dict: A dictionary containing sourceranges of all the
strings and comments within a file.
:return: A tuple whith the first source range being
the range of the outermost indentation while
last being the range of the most
nested/innermost indentation.
Equal level indents appear in the order of
first encounter or left to right.
"""
ranges = []
open_pos = list(self.get_valid_sequences(
file, open_specifier, annotation_dict))
close_pos = list(self.get_valid_sequences(
file, close_specifier, annotation_dict))
number_of_encaps = len(open_pos)
if number_of_encaps != len(close_pos):
raise UnmatchedIndentError(open_specifier, close_specifier)
if number_of_encaps == 0:
return ()
stack = []
text = ''.join(file)
open_counter = close_counter = position = 0
op_limit = cl_limit = False
for position in range(len(text)):
if not op_limit:
if open_pos[open_counter].position == position:
stack.append(open_pos[open_counter])
open_counter += 1
if open_counter == number_of_encaps:
op_limit = True
if not cl_limit:
if close_pos[close_counter].position == position:
try:
op = stack.pop()
except IndexError:
raise UnmatchedIndentError(open_specifier,
close_specifier)
ranges.append(SourceRange.from_values(
filename,
start_line=op.line,
start_column=op.column,
end_line=close_pos[close_counter].line,
end_column=close_pos[close_counter].column))
close_counter += 1
if close_counter == number_of_encaps:
cl_limit = True
return tuple(ranges)
def get_unspecified_block_range(self,
file,
filename,
indent_specifier,
annotation_dict,
encapsulators,
comments):
"""
Gets the range of all blocks which do not have an un-indent specifer.
:param file: File that needs to be checked in the form of
a list of strings.
:param filename: Name of the file that needs to be checked.
:param indent_specifier: A character or string indicating that the
indentation should begin.
:param annotation_dict: A dictionary containing sourceranges of all the
strings and comments within a file.
:param encapsulators: A tuple of sourceranges of all encapsulators of
a language.
:param comments: A dict containing all the types of comments
specifiers in a language.
:return: A tuple of SourceRanges of blocks without
un-indent specifiers.
"""
specifiers = list(self.get_valid_sequences(
file,
indent_specifier,
annotation_dict,
encapsulators,
check_ending=True))
_range = []
for specifier in specifiers:
current_line = specifier.line
indent = get_indent_of_specifier(file, current_line, encapsulators)
unindent_line = get_first_unindent(indent,
file,
current_line,
annotation_dict,
encapsulators,
comments)
if unindent_line == specifier.line:
raise ExpectedIndentError(specifier.line)
_range.append(SourceRange.from_values(
filename,
start_line=specifier.line, start_column=None,
end_line=unindent_line, end_column=None))
return tuple(_range)
@staticmethod
def get_valid_sequences(file,
sequence,
annotation_dict,
encapsulators=None,
check_ending=False):
"""
A vaild sequence is a sequence that is outside of comments or strings.
:param file: File that needs to be checked in the form of
a list of strings.
:param sequence: Sequence whose validity is to be checked.
:param annotation_dict: A dictionary containing sourceranges of all the
strings and comments within a file.
:param encapsulators: A tuple of SourceRanges of code regions
trapped in between a matching pair of
encapsulators.
:param check_ending: Check whether sequence falls at the end of the
line.
:return: A tuple of AbsolutePosition's of all occurances
of sequence outside of string's and comments.
"""
file_string = ''.join(file)
# tuple since order is important
sequence_positions = tuple()
for sequence_match in unescaped_search_for(sequence, file_string):
valid = True
sequence_position = AbsolutePosition(
file, sequence_match.start())
sequence_line_text = file[sequence_position.line - 1]
# ignore if within string
for string in annotation_dict['strings']:
if(gt_eq(sequence_position, string.start) and
lt_eq(sequence_position, string.end)):
valid = False
# ignore if within comments
for comment in annotation_dict['comments']:
if(gt_eq(sequence_position, comment.start) and
lt_eq(sequence_position, comment.end)):
valid = False
if(comment.start.line == sequence_position.line and
comment.end.line == sequence_position.line and
check_ending):
sequence_line_text = sequence_line_text[
:comment.start.column - 1] + sequence_line_text[
comment.end.column-1:]
if encapsulators:
for encapsulator in encapsulators:
if(gt_eq(sequence_position, encapsulator.start) and
lt_eq(sequence_position, encapsulator.end)):
valid = False
if not sequence_line_text.rstrip().endswith(':') and check_ending:
valid = False
if valid:
sequence_positions += (sequence_position,)
return sequence_positions
def get_indent_of_specifier(file, current_line, encapsulators):
"""
Get indentation of the indent specifer itself.
:param file: A tuple of strings.
:param current_line: Line number of indent specifier (initial 1)
:param encapsulators: A tuple with all the ranges of encapsulators
:return: Indentation of the specifier.
"""
start = current_line
_range = 0
while (_range < len(encapsulators) and
encapsulators[_range].end.line <= current_line):
if current_line == encapsulators[_range].end.line:
if encapsulators[_range].start.line < start:
start = encapsulators[_range].start.line
_range += 1
return len(file[start - 1]) - len(file[start - 1].lstrip())
def get_first_unindent(indent,
file,
start_line,
annotation_dict,
encapsulators,
comments):
"""
Get the first case of a valid unindentation.
:param indent: No. of spaces to check unindent against.
:param file: A tuple of strings.
:param start_line: The line from where to start searching for
unindent.
:param annotation_dict: A dictionary containing sourceranges of all the
strings and comments within a file.
:param encapsulators: A tuple of SourceRanges of code regions trapped in
between a matching pair of encapsulators.
:param comments: A dict containing all the types of comments
specifiers in a language.
:return: The line where unindent is found (intial 0).
"""
line_nr = start_line
while line_nr < len(file):
valid = True
for comment in annotation_dict['comments']:
if(comment.start.line < line_nr + 1 and
comment.end.line >= line_nr + 1):
valid = False
first_char = file[line_nr].lstrip()[0] if file[line_nr].strip()\
else ''
if first_char in comments:
valid = False
for encapsulator in encapsulators:
if(encapsulator.start.line < line_nr + 1 and
encapsulator.end.line >= line_nr + 1):
valid = False
line_indent = len(file[line_nr]) - len(file[line_nr].lstrip())
if line_indent <= indent and valid:
return line_nr
line_nr += 1
return line_nr
# TODO remove these once https://github.com/coala/coala/issues/2377
# gets a fix
def lt_eq(absolute, source):
if absolute.line == source.line:
return absolute.column <= source.column
return absolute.line < source.line
def gt_eq(absolute, source):
if absolute.line == source.line:
return absolute.column >= source.column
return absolute.line > source.line
def get_element_indent(file, encaps):
"""
Gets indent of elements inside encapsulator.
:param file: A tuple of strings.
:param encaps: SourceRange of an encapsulator.
:return: The number of spaces params are indented relative to
the start line of encapsulator.
"""
line_nr = encaps.start.line - 1
start_indent = get_indent_of_line(file, line_nr)
if len(file[line_nr].rstrip()) <= encaps.start.column:
indent = get_indent_of_line(file, line_nr + 1)
else:
indent = encaps.start.column
indent = indent - start_indent if indent > start_indent else 0
return indent
def get_indent_of_line(file, line, length=True):
indent = len(file[line]) - len(file[line].lstrip())
if length:
return indent
else:
return file[line][:indent]
class ExpectedIndentError(Exception):
def __init__(self, line):
Exception.__init__(self, 'Expected indent after line: ' + str(line))
class UnmatchedIndentError(Exception):
def __init__(self, open_indent, close_indent):
Exception.__init__(self, 'Unmatched ' + open_indent + ', ' +
close_indent + ' pair')
|
sounak98/coala-bears
|
bears/general/IndentationBear.py
|
Python
|
agpl-3.0
| 22,844
|
#
# 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.
from typing import Any, Callable, Dict, Optional
from airflow.exceptions import AirflowException
from airflow.providers.http.hooks.http import HttpHook
from airflow.sensors.base import BaseSensorOperator
class HttpSensor(BaseSensorOperator):
"""
Executes a HTTP GET statement and returns False on failure caused by
404 Not Found or `response_check` returning False.
HTTP Error codes other than 404 (like 403) or Connection Refused Error
would raise an exception and fail the sensor itself directly (no more poking).
To avoid failing the task for other codes than 404, the argument ``extra_option``
can be passed with the value ``{'check_response': False}``. It will make the ``response_check``
be execute for any http status code.
The response check can access the template context to the operator:
def response_check(response, task_instance):
# The task_instance is injected, so you can pull data form xcom
# Other context variables such as dag, ds, execution_date are also available.
xcom_data = task_instance.xcom_pull(task_ids='pushing_task')
# In practice you would do something more sensible with this data..
print(xcom_data)
return True
HttpSensor(task_id='my_http_sensor', ..., response_check=response_check)
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:HttpSensor`
:param http_conn_id: The :ref:`http connection<howto/connection:http>` to run the
sensor against
:type http_conn_id: str
:param method: The HTTP request method to use
:type method: str
:param endpoint: The relative part of the full url
:type endpoint: str
:param request_params: The parameters to be added to the GET url
:type request_params: a dictionary of string key/value pairs
:param headers: The HTTP headers to be added to the GET request
:type headers: a dictionary of string key/value pairs
:param response_check: A check against the 'requests' response object.
The callable takes the response object as the first positional argument
and optionally any number of keyword arguments available in the context dictionary.
It should return True for 'pass' and False otherwise.
:type response_check: A lambda or defined function.
:param extra_options: Extra options for the 'requests' library, see the
'requests' documentation (options to modify timeout, ssl, etc.)
:type extra_options: A dictionary of options, where key is string and value
depends on the option that's being modified.
"""
template_fields = ('endpoint', 'request_params', 'headers')
def __init__(
self,
*,
endpoint: str,
http_conn_id: str = 'http_default',
method: str = 'GET',
request_params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, Any]] = None,
response_check: Optional[Callable[..., bool]] = None,
extra_options: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> None:
super().__init__(**kwargs)
self.endpoint = endpoint
self.http_conn_id = http_conn_id
self.request_params = request_params or {}
self.headers = headers or {}
self.extra_options = extra_options or {}
self.response_check = response_check
self.hook = HttpHook(method=method, http_conn_id=http_conn_id)
def poke(self, context: Dict[Any, Any]) -> bool:
from airflow.utils.operator_helpers import make_kwargs_callable
self.log.info('Poking: %s', self.endpoint)
try:
response = self.hook.run(
self.endpoint,
data=self.request_params,
headers=self.headers,
extra_options=self.extra_options,
)
if self.response_check:
kwargs_callable = make_kwargs_callable(self.response_check)
return kwargs_callable(response, **context)
except AirflowException as exc:
if str(exc).startswith("404"):
return False
raise exc
return True
|
apache/incubator-airflow
|
airflow/providers/http/sensors/http.py
|
Python
|
apache-2.0
| 5,045
|
#!/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.
from django.conf.urls import patterns, url
# Navigator API
urlpatterns = patterns('metadata.navigator_api',
url(r'^api/navigator/search_entities/?$', 'search_entities', name='search_entities'),
url(r'^api/navigator/find_entity/?$', 'find_entity', name='find_entity'),
url(r'^api/navigator/get_entity/?$', 'get_entity', name='get_entity'),
url(r'^api/navigator/add_tags/?$', 'add_tags', name='add_tags'),
url(r'^api/navigator/delete_tags/?$', 'delete_tags', name='delete_tags'),
url(r'^api/navigator/update_properties/?$', 'update_properties', name='update_properties'),
url(r'^api/navigator/delete_properties/?$', 'delete_properties', name='delete_properties'),
url(r'^api/navigator/lineage/?$', 'get_lineage', name='get_lineage'),
)
# Optimizer API
urlpatterns += patterns('metadata.optimizer_api',
url(r'^api/optimizer_api/top_tables/?$', 'top_tables', name='top_tables'),
url(r'^api/optimizer_api/table_details/?$', 'table_details', name='table_details'),
url(r'^api/optimizer_api/query_compatibility/?$', 'query_compatibility', name='query_compatibility'),
url(r'^api/optimizer_api/upload_history/?$', 'upload_history', name='upload_history'),
url(r'^api/optimizer_api/query_complexity/?$', 'query_complexity', name='query_complexity'),
url(r'^api/optimizer_api/popular_values/?$', 'popular_values', name='popular_values'),
url(r'^api/optimizer_api/similar_queries/?$', 'similar_queries', name='similar_queries'),
)
|
lumig242/Hue-Integration-with-CDAP
|
desktop/libs/metadata/src/metadata/urls.py
|
Python
|
apache-2.0
| 2,246
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2012 VMware, Inc.
# Copyright (c) 2011 Citrix Systems, Inc.
# Copyright 2011 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Utility functions for ESX Networking.
"""
from nova import exception
from nova.openstack.common import log as logging
from nova.virt.vmwareapi import error_util
from nova.virt.vmwareapi import vim_util
from nova.virt.vmwareapi import vm_util
LOG = logging.getLogger(__name__)
def get_network_with_the_name(session, network_name="vmnet0", cluster=None):
"""
Gets reference to the network whose name is passed as the
argument.
"""
host = vm_util.get_host_ref(session, cluster)
if cluster is not None:
vm_networks_ret = session._call_method(vim_util,
"get_dynamic_property", cluster,
"ClusterComputeResource",
"network")
else:
vm_networks_ret = session._call_method(vim_util,
"get_dynamic_property", host,
"HostSystem", "network")
# Meaning there are no networks on the host. suds responds with a ""
# in the parent property field rather than a [] in the
# ManagedObjectReference property field of the parent
if not vm_networks_ret:
return None
vm_networks = vm_networks_ret.ManagedObjectReference
network_obj = {}
LOG.debug(vm_networks)
for network in vm_networks:
# Get network properties
if network._type == 'DistributedVirtualPortgroup':
props = session._call_method(vim_util,
"get_dynamic_property", network,
"DistributedVirtualPortgroup", "config")
# NOTE(asomya): This only works on ESXi if the port binding is
# set to ephemeral
if props.name == network_name:
network_obj['type'] = 'DistributedVirtualPortgroup'
network_obj['dvpg'] = props.key
dvs_props = session._call_method(vim_util,
"get_dynamic_property",
props.distributedVirtualSwitch,
"VmwareDistributedVirtualSwitch", "uuid")
network_obj['dvsw'] = dvs_props
else:
props = session._call_method(vim_util,
"get_dynamic_property", network,
"Network", "summary.name")
if props == network_name:
network_obj['type'] = 'Network'
network_obj['name'] = network_name
if (len(network_obj) > 0):
return network_obj
else:
return None
def get_vswitch_for_vlan_interface(session, vlan_interface, cluster=None):
"""
Gets the vswitch associated with the physical network adapter
with the name supplied.
"""
# Get the list of vSwicthes on the Host System
host_mor = vm_util.get_host_ref(session, cluster)
vswitches_ret = session._call_method(vim_util,
"get_dynamic_property", host_mor,
"HostSystem", "config.network.vswitch")
# Meaning there are no vSwitches on the host. Shouldn't be the case,
# but just doing code check
if not vswitches_ret:
return
vswitches = vswitches_ret.HostVirtualSwitch
# Get the vSwitch associated with the network adapter
for elem in vswitches:
try:
for nic_elem in elem.pnic:
if str(nic_elem).split('-')[-1].find(vlan_interface) != -1:
return elem.name
# Catching Attribute error as a vSwitch may not be associated with a
# physical NIC.
except AttributeError:
pass
def check_if_vlan_interface_exists(session, vlan_interface, cluster=None):
"""Checks if the vlan_interface exists on the esx host."""
host_mor = vm_util.get_host_ref(session, cluster)
physical_nics_ret = session._call_method(vim_util,
"get_dynamic_property", host_mor,
"HostSystem", "config.network.pnic")
# Meaning there are no physical nics on the host
if not physical_nics_ret:
return False
physical_nics = physical_nics_ret.PhysicalNic
for pnic in physical_nics:
if vlan_interface == pnic.device:
return True
return False
def get_vlanid_and_vswitch_for_portgroup(session, pg_name, cluster=None):
"""Get the vlan id and vswicth associated with the port group."""
host_mor = vm_util.get_host_ref(session, cluster)
port_grps_on_host_ret = session._call_method(vim_util,
"get_dynamic_property", host_mor,
"HostSystem", "config.network.portgroup")
if not port_grps_on_host_ret:
msg = _("ESX SOAP server returned an empty port group "
"for the host system in its response")
LOG.error(msg)
raise exception.NovaException(msg)
port_grps_on_host = port_grps_on_host_ret.HostPortGroup
for p_gp in port_grps_on_host:
if p_gp.spec.name == pg_name:
p_grp_vswitch_name = p_gp.vswitch.split("-")[-1]
return p_gp.spec.vlanId, p_grp_vswitch_name
def create_port_group(session, pg_name, vswitch_name, vlan_id=0, cluster=None):
"""
Creates a port group on the host system with the vlan tags
supplied. VLAN id 0 means no vlan id association.
"""
client_factory = session._get_vim().client.factory
add_prt_grp_spec = vm_util.get_add_vswitch_port_group_spec(
client_factory,
vswitch_name,
pg_name,
vlan_id)
host_mor = vm_util.get_host_ref(session, cluster)
network_system_mor = session._call_method(vim_util,
"get_dynamic_property", host_mor,
"HostSystem", "configManager.networkSystem")
LOG.debug(_("Creating Port Group with name %s on "
"the ESX host") % pg_name)
try:
session._call_method(session._get_vim(),
"AddPortGroup", network_system_mor,
portgrp=add_prt_grp_spec)
except error_util.VimFaultException as exc:
# There can be a race condition when two instances try
# adding port groups at the same time. One succeeds, then
# the other one will get an exception. Since we are
# concerned with the port group being created, which is done
# by the other call, we can ignore the exception.
if error_util.FAULT_ALREADY_EXISTS not in exc.fault_list:
raise exception.NovaException(exc)
LOG.debug(_("Created Port Group with name %s on "
"the ESX host") % pg_name)
|
DirectXMan12/nova-hacking
|
nova/virt/vmwareapi/network_util.py
|
Python
|
apache-2.0
| 7,343
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import uuid
import nose.exc
from keystone.common import sql
from keystone import config
from keystone import test
import test_keystoneclient
CONF = config.CONF
class KcMasterSqlTestCase(test_keystoneclient.KcMasterTestCase):
def config(self, config_files):
super(KcMasterSqlTestCase, self).config([
test.etcdir('keystone.conf.sample'),
test.testsdir('test_overrides.conf'),
test.testsdir('backend_sql.conf')])
def tearDown(self):
sql.set_global_engine(None)
super(KcMasterSqlTestCase, self).tearDown()
def test_endpoint_crud(self):
from keystoneclient import exceptions as client_exceptions
client = self.get_client(admin=True)
service = client.services.create(name=uuid.uuid4().hex,
service_type=uuid.uuid4().hex,
description=uuid.uuid4().hex)
endpoint_region = uuid.uuid4().hex
invalid_service_id = uuid.uuid4().hex
endpoint_publicurl = uuid.uuid4().hex
endpoint_internalurl = uuid.uuid4().hex
endpoint_adminurl = uuid.uuid4().hex
# a non-existent service ID should trigger a 404
self.assertRaises(client_exceptions.NotFound,
client.endpoints.create,
region=endpoint_region,
service_id=invalid_service_id,
publicurl=endpoint_publicurl,
adminurl=endpoint_adminurl,
internalurl=endpoint_internalurl)
endpoint = client.endpoints.create(region=endpoint_region,
service_id=service.id,
publicurl=endpoint_publicurl,
adminurl=endpoint_adminurl,
internalurl=endpoint_internalurl)
self.assertEquals(endpoint.region, endpoint_region)
self.assertEquals(endpoint.service_id, service.id)
self.assertEquals(endpoint.publicurl, endpoint_publicurl)
self.assertEquals(endpoint.internalurl, endpoint_internalurl)
self.assertEquals(endpoint.adminurl, endpoint_adminurl)
client.endpoints.delete(id=endpoint.id)
self.assertRaises(client_exceptions.NotFound, client.endpoints.delete,
id=endpoint.id)
def test_endpoint_create_404(self):
from keystoneclient import exceptions as client_exceptions
client = self.get_client(admin=True)
self.assertRaises(client_exceptions.NotFound,
client.endpoints.create,
region=uuid.uuid4().hex,
service_id=uuid.uuid4().hex,
publicurl=uuid.uuid4().hex,
adminurl=uuid.uuid4().hex,
internalurl=uuid.uuid4().hex)
def test_endpoint_delete_404(self):
from keystoneclient import exceptions as client_exceptions
client = self.get_client(admin=True)
self.assertRaises(client_exceptions.NotFound,
client.endpoints.delete,
id=uuid.uuid4().hex)
def test_policy_crud(self):
# FIXME(dolph): this test was written prior to the v3 implementation of
# the client and essentially refers to a non-existent
# policy manager in the v2 client. this test needs to be
# moved to a test suite running against the v3 api
raise nose.exc.SkipTest('Written prior to v3 client; needs refactor')
from keystoneclient import exceptions as client_exceptions
client = self.get_client(admin=True)
policy_blob = uuid.uuid4().hex
policy_type = uuid.uuid4().hex
service = client.services.create(
name=uuid.uuid4().hex,
service_type=uuid.uuid4().hex,
description=uuid.uuid4().hex)
endpoint = client.endpoints.create(
service_id=service.id,
region=uuid.uuid4().hex,
adminurl=uuid.uuid4().hex,
internalurl=uuid.uuid4().hex,
publicurl=uuid.uuid4().hex)
# create
policy = client.policies.create(
blob=policy_blob,
type=policy_type,
endpoint=endpoint.id)
self.assertEquals(policy_blob, policy.policy)
self.assertEquals(policy_type, policy.type)
self.assertEquals(endpoint.id, policy.endpoint_id)
policy = client.policies.get(policy=policy.id)
self.assertEquals(policy_blob, policy.policy)
self.assertEquals(policy_type, policy.type)
self.assertEquals(endpoint.id, policy.endpoint_id)
endpoints = [x for x in client.endpoints.list() if x.id == endpoint.id]
endpoint = endpoints[0]
self.assertEquals(policy_blob, policy.policy)
self.assertEquals(policy_type, policy.type)
self.assertEquals(endpoint.id, policy.endpoint_id)
# update
policy_blob = uuid.uuid4().hex
policy_type = uuid.uuid4().hex
endpoint = client.endpoints.create(
service_id=service.id,
region=uuid.uuid4().hex,
adminurl=uuid.uuid4().hex,
internalurl=uuid.uuid4().hex,
publicurl=uuid.uuid4().hex)
policy = client.policies.update(
policy=policy.id,
blob=policy_blob,
type=policy_type,
endpoint=endpoint.id)
policy = client.policies.get(policy=policy.id)
self.assertEquals(policy_blob, policy.policy)
self.assertEquals(policy_type, policy.type)
self.assertEquals(endpoint.id, policy.endpoint_id)
# delete
client.policies.delete(policy=policy.id)
self.assertRaises(
client_exceptions.NotFound,
client.policies.get,
policy=policy.id)
policies = [x for x in client.policies.list() if x.id == policy.id]
self.assertEquals(len(policies), 0)
|
ioram7/keystone-federado-pgid2013
|
tests/test_keystoneclient_sql.py
|
Python
|
apache-2.0
| 6,768
|
# Copyright (c) 2014 VMware, 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.
"""
Datastore utility functions
"""
import posixpath
from oslo.vmware import exceptions as vexc
from oslo.vmware import pbm
from nova import exception
from nova.i18n import _, _LE, _LI
from nova.openstack.common import log as logging
from nova.virt.vmwareapi import constants
from nova.virt.vmwareapi import vim_util
from nova.virt.vmwareapi import vm_util
LOG = logging.getLogger(__name__)
ALL_SUPPORTED_DS_TYPES = frozenset([constants.DATASTORE_TYPE_VMFS,
constants.DATASTORE_TYPE_NFS,
constants.DATASTORE_TYPE_VSAN])
class Datastore(object):
def __init__(self, ref, name, capacity=None, freespace=None):
"""Datastore object holds ref and name together for convenience.
:param ref: a vSphere reference to a datastore
:param name: vSphere unique name for this datastore
:param capacity: (optional) capacity in bytes of this datastore
:param freespace: (optional) free space in bytes of datastore
"""
if name is None:
raise ValueError(_("Datastore name cannot be None"))
if ref is None:
raise ValueError(_("Datastore reference cannot be None"))
if freespace is not None and capacity is None:
raise ValueError(_("Invalid capacity"))
if capacity is not None and freespace is not None:
if capacity < freespace:
raise ValueError(_("Capacity is smaller than free space"))
self._ref = ref
self._name = name
self._capacity = capacity
self._freespace = freespace
@property
def ref(self):
return self._ref
@property
def name(self):
return self._name
@property
def capacity(self):
return self._capacity
@property
def freespace(self):
return self._freespace
def build_path(self, *paths):
"""Constructs and returns a DatastorePath.
:param paths: list of path components, for constructing a path relative
to the root directory of the datastore
:return: a DatastorePath object
"""
return DatastorePath(self._name, *paths)
def __str__(self):
return '[%s]' % self._name
class DatastorePath(object):
"""Class for representing a directory or file path in a vSphere datatore.
This provides various helper methods to access components and useful
variants of the datastore path.
Example usage:
DatastorePath("datastore1", "_base/foo", "foo.vmdk") creates an
object that describes the "[datastore1] _base/foo/foo.vmdk" datastore
file path to a virtual disk.
Note:
* Datastore path representations always uses forward slash as separator
(hence the use of the posixpath module).
* Datastore names are enclosed in square brackets.
* Path part of datastore path is relative to the root directory
of the datastore, and is always separated from the [ds_name] part with
a single space.
"""
VMDK_EXTENSION = "vmdk"
def __init__(self, datastore_name, *paths):
if datastore_name is None or datastore_name == '':
raise ValueError(_("datastore name empty"))
self._datastore_name = datastore_name
self._rel_path = ''
if paths:
if None in paths:
raise ValueError(_("path component cannot be None"))
self._rel_path = posixpath.join(*paths)
def __str__(self):
"""Full datastore path to the file or directory."""
if self._rel_path != '':
return "[%s] %s" % (self._datastore_name, self.rel_path)
return "[%s]" % self._datastore_name
def __repr__(self):
return "%s(%s, %s)" % (self.__class__.__name__,
self.datastore, self.rel_path)
@property
def datastore(self):
return self._datastore_name
@property
def parent(self):
return DatastorePath(self.datastore, posixpath.dirname(self._rel_path))
@property
def basename(self):
return posixpath.basename(self._rel_path)
@property
def dirname(self):
return posixpath.dirname(self._rel_path)
@property
def rel_path(self):
return self._rel_path
def join(self, *paths):
if paths:
if None in paths:
raise ValueError(_("path component cannot be None"))
return DatastorePath(self.datastore,
posixpath.join(self._rel_path, *paths))
return self
def __eq__(self, other):
return (isinstance(other, DatastorePath) and
self._datastore_name == other._datastore_name and
self._rel_path == other._rel_path)
def __hash__(self):
return str(self).__hash__()
@classmethod
def parse(cls, datastore_path):
"""Constructs a DatastorePath object given a datastore path string."""
if not datastore_path:
raise ValueError(_("datastore path empty"))
spl = datastore_path.split('[', 1)[1].split(']', 1)
path = ""
if len(spl) == 1:
datastore_name = spl[0]
else:
datastore_name, path = spl
return cls(datastore_name, path.strip())
# NOTE(mdbooth): this convenience function is temporarily duplicated in
# vm_util. The correct fix is to handle paginated results as they are returned
# from the relevant vim_util function. However, vim_util is currently
# effectively deprecated as we migrate to oslo.vmware. This duplication will be
# removed when we fix it properly in oslo.vmware.
def _get_token(results):
"""Get the token from the property results."""
return getattr(results, 'token', None)
def _select_datastore(session, data_stores, best_match, datastore_regex=None,
storage_policy=None,
allowed_ds_types=ALL_SUPPORTED_DS_TYPES):
"""Find the most preferable datastore in a given RetrieveResult object.
:param session: vmwareapi session
:param data_stores: a RetrieveResult object from vSphere API call
:param best_match: the current best match for datastore
:param datastore_regex: an optional regular expression to match names
:param storage_policy: storage policy for the datastore
:param allowed_ds_types: a list of acceptable datastore type names
:return: datastore_ref, datastore_name, capacity, freespace
"""
if storage_policy:
matching_ds = _filter_datastores_matching_storage_policy(
session, data_stores, storage_policy)
if not matching_ds:
return best_match
else:
matching_ds = data_stores
# data_stores is actually a RetrieveResult object from vSphere API call
for obj_content in matching_ds.objects:
# the propset attribute "need not be set" by returning API
if not hasattr(obj_content, 'propSet'):
continue
propdict = vm_util.propset_dict(obj_content.propSet)
if _is_datastore_valid(propdict, datastore_regex, allowed_ds_types):
new_ds = Datastore(
ref=obj_content.obj,
name=propdict['summary.name'],
capacity=propdict['summary.capacity'],
freespace=propdict['summary.freeSpace'])
# favor datastores with more free space
if (best_match is None or
new_ds.freespace > best_match.freespace):
best_match = new_ds
return best_match
def _is_datastore_valid(propdict, datastore_regex, ds_types):
"""Checks if a datastore is valid based on the following criteria.
Criteria:
- Datastore is accessible
- Datastore is not in maintenance mode (optional)
- Datastore's type is one of the given ds_types
- Datastore matches the supplied regex (optional)
:param propdict: datastore summary dict
:param datastore_regex : Regex to match the name of a datastore.
"""
# Local storage identifier vSphere doesn't support CIFS or
# vfat for datastores, therefore filtered
return (propdict.get('summary.accessible') and
(propdict.get('summary.maintenanceMode') is None or
propdict.get('summary.maintenanceMode') == 'normal') and
propdict['summary.type'] in ds_types and
(datastore_regex is None or
datastore_regex.match(propdict['summary.name'])))
def get_datastore(session, cluster, datastore_regex=None,
storage_policy=None,
allowed_ds_types=ALL_SUPPORTED_DS_TYPES):
"""Get the datastore list and choose the most preferable one."""
datastore_ret = session._call_method(
vim_util,
"get_dynamic_property", cluster,
"ClusterComputeResource", "datastore")
# If there are no hosts in the cluster then an empty string is
# returned
if not datastore_ret:
raise exception.DatastoreNotFound()
data_store_mors = datastore_ret.ManagedObjectReference
data_stores = session._call_method(vim_util,
"get_properties_for_a_collection_of_objects",
"Datastore", data_store_mors,
["summary.type", "summary.name",
"summary.capacity", "summary.freeSpace",
"summary.accessible",
"summary.maintenanceMode"])
best_match = None
while data_stores:
best_match = _select_datastore(session,
data_stores,
best_match,
datastore_regex,
storage_policy,
allowed_ds_types)
token = _get_token(data_stores)
if not token:
break
data_stores = session._call_method(vim_util,
"continue_to_get_objects",
token)
if best_match:
return best_match
if storage_policy:
raise exception.DatastoreNotFound(
_("Storage policy %s did not match any datastores")
% storage_policy)
elif datastore_regex:
raise exception.DatastoreNotFound(
_("Datastore regex %s did not match any datastores")
% datastore_regex.pattern)
else:
raise exception.DatastoreNotFound()
def _get_allowed_datastores(data_stores, datastore_regex):
allowed = []
for obj_content in data_stores.objects:
# the propset attribute "need not be set" by returning API
if not hasattr(obj_content, 'propSet'):
continue
propdict = vm_util.propset_dict(obj_content.propSet)
if _is_datastore_valid(propdict,
datastore_regex,
ALL_SUPPORTED_DS_TYPES):
allowed.append(Datastore(ref=obj_content.obj,
name=propdict['summary.name']))
return allowed
def get_available_datastores(session, cluster=None, datastore_regex=None):
"""Get the datastore list and choose the first local storage."""
if cluster:
mobj = cluster
resource_type = "ClusterComputeResource"
else:
mobj = vm_util.get_host_ref(session)
resource_type = "HostSystem"
ds = session._call_method(vim_util, "get_dynamic_property", mobj,
resource_type, "datastore")
if not ds:
return []
data_store_mors = ds.ManagedObjectReference
# NOTE(garyk): use utility method to retrieve remote objects
data_stores = session._call_method(vim_util,
"get_properties_for_a_collection_of_objects",
"Datastore", data_store_mors,
["summary.type", "summary.name", "summary.accessible",
"summary.maintenanceMode"])
allowed = []
while data_stores:
allowed.extend(_get_allowed_datastores(data_stores, datastore_regex))
token = _get_token(data_stores)
if not token:
break
data_stores = session._call_method(vim_util,
"continue_to_get_objects",
token)
return allowed
def get_allowed_datastore_types(disk_type):
if disk_type == constants.DISK_TYPE_STREAM_OPTIMIZED:
return ALL_SUPPORTED_DS_TYPES
return ALL_SUPPORTED_DS_TYPES - frozenset([constants.DATASTORE_TYPE_VSAN])
def file_delete(session, ds_path, dc_ref):
LOG.debug("Deleting the datastore file %s", ds_path)
vim = session.vim
file_delete_task = session._call_method(
vim,
"DeleteDatastoreFile_Task",
vim.service_content.fileManager,
name=str(ds_path),
datacenter=dc_ref)
session._wait_for_task(file_delete_task)
LOG.debug("Deleted the datastore file")
def disk_move(session, dc_ref, src_file, dst_file):
"""Moves the source virtual disk to the destination.
The list of possible faults that the server can return on error
include:
* CannotAccessFile: Thrown if the source file or folder cannot be
moved because of insufficient permissions.
* FileAlreadyExists: Thrown if a file with the given name already
exists at the destination.
* FileFault: Thrown if there is a generic file error
* FileLocked: Thrown if the source file or folder is currently
locked or in use.
* FileNotFound: Thrown if the file or folder specified by sourceName
is not found.
* InvalidDatastore: Thrown if the operation cannot be performed on
the source or destination datastores.
* NoDiskSpace: Thrown if there is not enough space available on the
destination datastore.
* RuntimeFault: Thrown if any type of runtime fault is thrown that
is not covered by the other faults; for example,
a communication error.
"""
LOG.debug("Moving virtual disk from %(src)s to %(dst)s.",
{'src': src_file, 'dst': dst_file})
move_task = session._call_method(
session.vim,
"MoveVirtualDisk_Task",
session.vim.service_content.virtualDiskManager,
sourceName=str(src_file),
sourceDatacenter=dc_ref,
destName=str(dst_file),
destDatacenter=dc_ref,
force=False)
session._wait_for_task(move_task)
LOG.info(_LI("Moved virtual disk from %(src)s to %(dst)s."),
{'src': src_file, 'dst': dst_file})
def file_move(session, dc_ref, src_file, dst_file):
"""Moves the source file or folder to the destination.
The list of possible faults that the server can return on error
include:
* CannotAccessFile: Thrown if the source file or folder cannot be
moved because of insufficient permissions.
* FileAlreadyExists: Thrown if a file with the given name already
exists at the destination.
* FileFault: Thrown if there is a generic file error
* FileLocked: Thrown if the source file or folder is currently
locked or in use.
* FileNotFound: Thrown if the file or folder specified by sourceName
is not found.
* InvalidDatastore: Thrown if the operation cannot be performed on
the source or destination datastores.
* NoDiskSpace: Thrown if there is not enough space available on the
destination datastore.
* RuntimeFault: Thrown if any type of runtime fault is thrown that
is not covered by the other faults; for example,
a communication error.
"""
LOG.debug("Moving file from %(src)s to %(dst)s.",
{'src': src_file, 'dst': dst_file})
vim = session.vim
move_task = session._call_method(
vim,
"MoveDatastoreFile_Task",
vim.service_content.fileManager,
sourceName=str(src_file),
sourceDatacenter=dc_ref,
destinationName=str(dst_file),
destinationDatacenter=dc_ref)
session._wait_for_task(move_task)
LOG.debug("File moved")
def search_datastore_spec(client_factory, file_name):
"""Builds the datastore search spec."""
search_spec = client_factory.create('ns0:HostDatastoreBrowserSearchSpec')
search_spec.matchPattern = [file_name]
return search_spec
def file_exists(session, ds_browser, ds_path, file_name):
"""Check if the file exists on the datastore."""
client_factory = session.vim.client.factory
search_spec = search_datastore_spec(client_factory, file_name)
search_task = session._call_method(session.vim,
"SearchDatastore_Task",
ds_browser,
datastorePath=str(ds_path),
searchSpec=search_spec)
try:
task_info = session._wait_for_task(search_task)
except vexc.FileNotFoundException:
return False
file_exists = (getattr(task_info.result, 'file', False) and
task_info.result.file[0].path == file_name)
return file_exists
def mkdir(session, ds_path, dc_ref):
"""Creates a directory at the path specified. If it is just "NAME",
then a directory with this name is created at the topmost level of the
DataStore.
"""
LOG.debug("Creating directory with path %s", ds_path)
session._call_method(session.vim, "MakeDirectory",
session.vim.service_content.fileManager,
name=str(ds_path), datacenter=dc_ref,
createParentDirectories=True)
LOG.debug("Created directory with path %s", ds_path)
def get_sub_folders(session, ds_browser, ds_path):
"""Return a set of subfolders for a path on a datastore.
If the path does not exist then an empty set is returned.
"""
search_task = session._call_method(
session.vim,
"SearchDatastore_Task",
ds_browser,
datastorePath=str(ds_path))
try:
task_info = session._wait_for_task(search_task)
except vexc.FileNotFoundException:
return set()
# populate the folder entries
if hasattr(task_info.result, 'file'):
return set([file.path for file in task_info.result.file])
return set()
def _filter_datastores_matching_storage_policy(session, data_stores,
storage_policy):
"""Get datastores matching the given storage policy.
:param data_stores: the list of retrieve result wrapped datastore objects
:param storage_policy: the storage policy name
:return the list of datastores conforming to the given storage policy
"""
profile_id = pbm.get_profile_id_by_name(session, storage_policy)
if profile_id:
factory = session.pbm.client.factory
ds_mors = [oc.obj for oc in data_stores.objects]
hubs = pbm.convert_datastores_to_hubs(factory, ds_mors)
matching_hubs = pbm.filter_hubs_by_profile(session, hubs,
profile_id)
if matching_hubs:
matching_ds = pbm.filter_datastores_by_hubs(matching_hubs,
ds_mors)
object_contents = [oc for oc in data_stores.objects
if oc.obj in matching_ds]
data_stores.objects = object_contents
return data_stores
LOG.error(_LE("Unable to retrieve storage policy with name %s"),
storage_policy)
|
Metaswitch/calico-nova
|
nova/virt/vmwareapi/ds_util.py
|
Python
|
apache-2.0
| 20,387
|
#!/usr/bin/env python
#
# GrovePi Hardware Test
# Connect Buzzer to Port D8
# Connect Button to Analog Port A0
#
# The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.grovepi.com
#
# Have a question about this example? Ask on the forums here: http://www.dexterindustries.com/forum/?forum=grovepi
#
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2015 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
import time
import grovepi
# Connect the Grove Button to Analog Port 0.
button = 0
buzzer = 8
grovepi.pinMode(button,"INPUT")
while True:
try:
butt_val = grovepi.digitalRead(button)
print (butt_val)
if butt_val > 0:
grovepi.digitalWrite(buzzer,1)
print ('start')
time.sleep(1)
else:
grovepi.digitalWrite(buzzer,0)
time.sleep(.5)
except IOError:
print ("Error")
|
gerald-yang/ubuntu-iotivity-demo
|
snappy/grovepi/pygrovepi/GrovePi_Hardware_Test.py
|
Python
|
apache-2.0
| 1,976
|
# -*- encoding: utf-8 -*-
import codecs
import os
import posixpath
import shutil
import sys
import tempfile
import warnings
from StringIO import StringIO
from django.template import loader, Context
from django.conf import settings
from django.core.cache.backends.base import BaseCache, CacheKeyWarning
from django.core.exceptions import ImproperlyConfigured
from django.core.files.storage import default_storage
from django.core.management import call_command
from django.test import TestCase
from django.test.utils import override_settings
from django.utils.encoding import smart_unicode
from django.utils.functional import empty
from django.utils._os import rmtree_errorhandler
from django.contrib.staticfiles import finders, storage
TEST_ROOT = os.path.dirname(__file__)
TEST_SETTINGS = {
'DEBUG': True,
'MEDIA_URL': '/media/',
'STATIC_URL': '/static/',
'MEDIA_ROOT': os.path.join(TEST_ROOT, 'project', 'site_media', 'media'),
'STATIC_ROOT': os.path.join(TEST_ROOT, 'project', 'site_media', 'static'),
'STATICFILES_DIRS': (
os.path.join(TEST_ROOT, 'project', 'documents'),
('prefix', os.path.join(TEST_ROOT, 'project', 'prefixed')),
),
'STATICFILES_FINDERS': (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
),
}
from django.contrib.staticfiles.management.commands.collectstatic import Command as CollectstaticCommand
class BaseStaticFilesTestCase(object):
"""
Test case with a couple utility assertions.
"""
def setUp(self):
# Clear the cached default_storage out, this is because when it first
# gets accessed (by some other test), it evaluates settings.MEDIA_ROOT,
# since we're planning on changing that we need to clear out the cache.
default_storage._wrapped = empty
storage.staticfiles_storage._wrapped = empty
testfiles_path = os.path.join(TEST_ROOT, 'apps', 'test', 'static', 'test')
# To make sure SVN doesn't hangs itself with the non-ASCII characters
# during checkout, we actually create one file dynamically.
self._nonascii_filepath = os.path.join(testfiles_path, u'fi\u015fier.txt')
with codecs.open(self._nonascii_filepath, 'w', 'utf-8') as f:
f.write(u"fi\u015fier in the app dir")
# And also create the stupid hidden file to dwarf the setup.py's
# package data handling.
self._hidden_filepath = os.path.join(testfiles_path, '.hidden')
with codecs.open(self._hidden_filepath, 'w', 'utf-8') as f:
f.write("should be ignored")
self._backup_filepath = os.path.join(
TEST_ROOT, 'project', 'documents', 'test', 'backup~')
with codecs.open(self._backup_filepath, 'w', 'utf-8') as f:
f.write("should be ignored")
def tearDown(self):
os.unlink(self._nonascii_filepath)
os.unlink(self._hidden_filepath)
os.unlink(self._backup_filepath)
def assertFileContains(self, filepath, text):
self.assertIn(text, self._get_file(smart_unicode(filepath)),
u"'%s' not in '%s'" % (text, filepath))
def assertFileNotFound(self, filepath):
self.assertRaises(IOError, self._get_file, filepath)
def render_template(self, template, **kwargs):
if isinstance(template, basestring):
template = loader.get_template_from_string(template)
return template.render(Context(kwargs)).strip()
def static_template_snippet(self, path):
return "{%% load static from staticfiles %%}{%% static '%s' %%}" % path
def assertStaticRenders(self, path, result, **kwargs):
template = self.static_template_snippet(path)
self.assertEqual(self.render_template(template, **kwargs), result)
def assertStaticRaises(self, exc, path, result, **kwargs):
self.assertRaises(exc, self.assertStaticRenders, path, result, **kwargs)
@override_settings(**TEST_SETTINGS)
class StaticFilesTestCase(BaseStaticFilesTestCase, TestCase):
pass
class BaseCollectionTestCase(BaseStaticFilesTestCase):
"""
Tests shared by all file finding features (collectstatic,
findstatic, and static serve view).
This relies on the asserts defined in BaseStaticFilesTestCase, but
is separated because some test cases need those asserts without
all these tests.
"""
def setUp(self):
super(BaseCollectionTestCase, self).setUp()
self.old_root = settings.STATIC_ROOT
settings.STATIC_ROOT = tempfile.mkdtemp(dir=os.environ['DJANGO_TEST_TEMP_DIR'])
self.run_collectstatic()
# Use our own error handler that can handle .svn dirs on Windows
self.addCleanup(shutil.rmtree, settings.STATIC_ROOT,
ignore_errors=True, onerror=rmtree_errorhandler)
def tearDown(self):
settings.STATIC_ROOT = self.old_root
super(BaseCollectionTestCase, self).tearDown()
def run_collectstatic(self, **kwargs):
call_command('collectstatic', interactive=False, verbosity='0',
ignore_patterns=['*.ignoreme'], **kwargs)
def _get_file(self, filepath):
assert filepath, 'filepath is empty.'
filepath = os.path.join(settings.STATIC_ROOT, filepath)
with codecs.open(filepath, "r", "utf-8") as f:
return f.read()
class CollectionTestCase(BaseCollectionTestCase, StaticFilesTestCase):
pass
class TestDefaults(object):
"""
A few standard test cases.
"""
def test_staticfiles_dirs(self):
"""
Can find a file in a STATICFILES_DIRS directory.
"""
self.assertFileContains('test.txt', 'Can we find')
self.assertFileContains(os.path.join('prefix', 'test.txt'), 'Prefix')
def test_staticfiles_dirs_subdir(self):
"""
Can find a file in a subdirectory of a STATICFILES_DIRS
directory.
"""
self.assertFileContains('subdir/test.txt', 'Can we find')
def test_staticfiles_dirs_priority(self):
"""
File in STATICFILES_DIRS has priority over file in app.
"""
self.assertFileContains('test/file.txt', 'STATICFILES_DIRS')
def test_app_files(self):
"""
Can find a file in an app static/ directory.
"""
self.assertFileContains('test/file1.txt', 'file1 in the app dir')
def test_nonascii_filenames(self):
"""
Can find a file with non-ASCII character in an app static/ directory.
"""
self.assertFileContains(u'test/fişier.txt', u'fişier in the app dir')
def test_camelcase_filenames(self):
"""
Can find a file with capital letters.
"""
self.assertFileContains(u'test/camelCase.txt', u'camelCase')
class TestFindStatic(CollectionTestCase, TestDefaults):
"""
Test ``findstatic`` management command.
"""
def _get_file(self, filepath):
_stdout = sys.stdout
sys.stdout = StringIO()
try:
call_command('findstatic', filepath, all=False, verbosity='0')
sys.stdout.seek(0)
lines = [l.strip() for l in sys.stdout.readlines()]
contents = codecs.open(
smart_unicode(lines[1].strip()), "r", "utf-8").read()
finally:
sys.stdout = _stdout
return contents
def test_all_files(self):
"""
Test that findstatic returns all candidate files if run without --first.
"""
_stdout = sys.stdout
sys.stdout = StringIO()
try:
call_command('findstatic', 'test/file.txt', verbosity='0')
sys.stdout.seek(0)
lines = [l.strip() for l in sys.stdout.readlines()]
finally:
sys.stdout = _stdout
self.assertEqual(len(lines), 3) # three because there is also the "Found <file> here" line
self.assertIn('project', lines[1])
self.assertIn('apps', lines[2])
class TestCollection(CollectionTestCase, TestDefaults):
"""
Test ``collectstatic`` management command.
"""
def test_ignore(self):
"""
Test that -i patterns are ignored.
"""
self.assertFileNotFound('test/test.ignoreme')
def test_common_ignore_patterns(self):
"""
Common ignore patterns (*~, .*, CVS) are ignored.
"""
self.assertFileNotFound('test/.hidden')
self.assertFileNotFound('test/backup~')
self.assertFileNotFound('test/CVS')
class TestCollectionClear(CollectionTestCase):
"""
Test the ``--clear`` option of the ``collectstatic`` managemenet command.
"""
def run_collectstatic(self, **kwargs):
clear_filepath = os.path.join(settings.STATIC_ROOT, 'cleared.txt')
with open(clear_filepath, 'w') as f:
f.write('should be cleared')
super(TestCollectionClear, self).run_collectstatic(clear=True)
def test_cleared_not_found(self):
self.assertFileNotFound('cleared.txt')
class TestCollectionExcludeNoDefaultIgnore(CollectionTestCase, TestDefaults):
"""
Test ``--exclude-dirs`` and ``--no-default-ignore`` options of the
``collectstatic`` management command.
"""
def run_collectstatic(self):
super(TestCollectionExcludeNoDefaultIgnore, self).run_collectstatic(
use_default_ignore_patterns=False)
def test_no_common_ignore_patterns(self):
"""
With --no-default-ignore, common ignore patterns (*~, .*, CVS)
are not ignored.
"""
self.assertFileContains('test/.hidden', 'should be ignored')
self.assertFileContains('test/backup~', 'should be ignored')
self.assertFileContains('test/CVS', 'should be ignored')
class TestNoFilesCreated(object):
def test_no_files_created(self):
"""
Make sure no files were create in the destination directory.
"""
self.assertEqual(os.listdir(settings.STATIC_ROOT), [])
class TestCollectionDryRun(CollectionTestCase, TestNoFilesCreated):
"""
Test ``--dry-run`` option for ``collectstatic`` management command.
"""
def run_collectstatic(self):
super(TestCollectionDryRun, self).run_collectstatic(dry_run=True)
class TestCollectionFilesOverride(CollectionTestCase):
"""
Test overriding duplicated files by ``collectstatic`` management command.
Check for proper handling of apps order in INSTALLED_APPS even if file modification
dates are in different order:
'regressiontests.staticfiles_tests.apps.test',
'regressiontests.staticfiles_tests.apps.no_label',
"""
def setUp(self):
self.orig_path = os.path.join(TEST_ROOT, 'apps', 'no_label', 'static', 'file2.txt')
# get modification and access times for no_label/static/file2.txt
self.orig_mtime = os.path.getmtime(self.orig_path)
self.orig_atime = os.path.getatime(self.orig_path)
# prepare duplicate of file2.txt from no_label app
# this file will have modification time older than no_label/static/file2.txt
# anyway it should be taken to STATIC_ROOT because 'test' app is before
# 'no_label' app in INSTALLED_APPS
self.testfile_path = os.path.join(TEST_ROOT, 'apps', 'test', 'static', 'file2.txt')
with open(self.testfile_path, 'w+') as f:
f.write('duplicate of file2.txt')
os.utime(self.testfile_path, (self.orig_atime - 1, self.orig_mtime - 1))
super(TestCollectionFilesOverride, self).setUp()
def tearDown(self):
if os.path.exists(self.testfile_path):
os.unlink(self.testfile_path)
# set back original modification time
os.utime(self.orig_path, (self.orig_atime, self.orig_mtime))
super(TestCollectionFilesOverride, self).tearDown()
def test_ordering_override(self):
"""
Test if collectstatic takes files in proper order
"""
self.assertFileContains('file2.txt', 'duplicate of file2.txt')
# run collectstatic again
self.run_collectstatic()
self.assertFileContains('file2.txt', 'duplicate of file2.txt')
# and now change modification time of no_label/static/file2.txt
# test app is first in INSTALLED_APPS so file2.txt should remain unmodified
mtime = os.path.getmtime(self.testfile_path)
atime = os.path.getatime(self.testfile_path)
os.utime(self.orig_path, (mtime + 1, atime + 1))
# run collectstatic again
self.run_collectstatic()
self.assertFileContains('file2.txt', 'duplicate of file2.txt')
@override_settings(
STATICFILES_STORAGE='regressiontests.staticfiles_tests.storage.DummyStorage',
)
class TestCollectionNonLocalStorage(CollectionTestCase, TestNoFilesCreated):
"""
Tests for #15035
"""
pass
# we set DEBUG to False here since the template tag wouldn't work otherwise
@override_settings(**dict(TEST_SETTINGS,
STATICFILES_STORAGE='django.contrib.staticfiles.storage.CachedStaticFilesStorage',
DEBUG=False,
))
class TestCollectionCachedStorage(BaseCollectionTestCase,
BaseStaticFilesTestCase, TestCase):
"""
Tests for the Cache busting storage
"""
def cached_file_path(self, path):
fullpath = self.render_template(self.static_template_snippet(path))
return fullpath.replace(settings.STATIC_URL, '')
def test_template_tag_return(self):
"""
Test the CachedStaticFilesStorage backend.
"""
self.assertStaticRaises(ValueError,
"does/not/exist.png",
"/static/does/not/exist.png")
self.assertStaticRenders("test/file.txt",
"/static/test/file.dad0999e4f8f.txt")
self.assertStaticRenders("cached/styles.css",
"/static/cached/styles.93b1147e8552.css")
self.assertStaticRenders("path/",
"/static/path/")
self.assertStaticRenders("path/?query",
"/static/path/?query")
def test_template_tag_simple_content(self):
relpath = self.cached_file_path("cached/styles.css")
self.assertEqual(relpath, "cached/styles.93b1147e8552.css")
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertNotIn("cached/other.css", content)
self.assertIn("other.d41d8cd98f00.css", content)
def test_path_with_querystring(self):
relpath = self.cached_file_path("cached/styles.css?spam=eggs")
self.assertEqual(relpath,
"cached/styles.93b1147e8552.css?spam=eggs")
with storage.staticfiles_storage.open(
"cached/styles.93b1147e8552.css") as relfile:
content = relfile.read()
self.assertNotIn("cached/other.css", content)
self.assertIn("other.d41d8cd98f00.css", content)
def test_path_with_fragment(self):
relpath = self.cached_file_path("cached/styles.css#eggs")
self.assertEqual(relpath, "cached/styles.93b1147e8552.css#eggs")
with storage.staticfiles_storage.open(
"cached/styles.93b1147e8552.css") as relfile:
content = relfile.read()
self.assertNotIn("cached/other.css", content)
self.assertIn("other.d41d8cd98f00.css", content)
def test_path_with_querystring_and_fragment(self):
relpath = self.cached_file_path("cached/css/fragments.css")
self.assertEqual(relpath, "cached/css/fragments.75433540b096.css")
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertIn('fonts/font.a4b0478549d0.eot?#iefix', content)
self.assertIn('fonts/font.b8d603e42714.svg#webfontIyfZbseF', content)
self.assertIn('data:font/woff;charset=utf-8;base64,d09GRgABAAAAADJoAA0AAAAAR2QAAQAAAAAAAAAAAAA', content)
self.assertIn('#default#VML', content)
def test_template_tag_absolute(self):
relpath = self.cached_file_path("cached/absolute.css")
self.assertEqual(relpath, "cached/absolute.23f087ad823a.css")
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertNotIn("/static/cached/styles.css", content)
self.assertIn("/static/cached/styles.93b1147e8552.css", content)
self.assertIn('/static/cached/img/relative.acae32e4532b.png', content)
def test_template_tag_denorm(self):
relpath = self.cached_file_path("cached/denorm.css")
self.assertEqual(relpath, "cached/denorm.c5bd139ad821.css")
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertNotIn("..//cached///styles.css", content)
self.assertIn("../cached/styles.93b1147e8552.css", content)
self.assertNotIn("url(img/relative.png )", content)
self.assertIn('url("img/relative.acae32e4532b.png', content)
def test_template_tag_relative(self):
relpath = self.cached_file_path("cached/relative.css")
self.assertEqual(relpath, "cached/relative.2217ea7273c2.css")
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertNotIn("../cached/styles.css", content)
self.assertNotIn('@import "styles.css"', content)
self.assertNotIn('url(img/relative.png)', content)
self.assertIn('url("img/relative.acae32e4532b.png")', content)
self.assertIn("../cached/styles.93b1147e8552.css", content)
def test_template_tag_deep_relative(self):
relpath = self.cached_file_path("cached/css/window.css")
self.assertEqual(relpath, "cached/css/window.9db38d5169f3.css")
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertNotIn('url(img/window.png)', content)
self.assertIn('url("img/window.acae32e4532b.png")', content)
def test_template_tag_url(self):
relpath = self.cached_file_path("cached/url.css")
self.assertEqual(relpath, "cached/url.615e21601e4b.css")
with storage.staticfiles_storage.open(relpath) as relfile:
self.assertIn("https://", relfile.read())
def test_cache_invalidation(self):
name = "cached/styles.css"
hashed_name = "cached/styles.93b1147e8552.css"
# check if the cache is filled correctly as expected
cache_key = storage.staticfiles_storage.cache_key(name)
cached_name = storage.staticfiles_storage.cache.get(cache_key)
self.assertEqual(self.cached_file_path(name), cached_name)
# clearing the cache to make sure we re-set it correctly in the url method
storage.staticfiles_storage.cache.clear()
cached_name = storage.staticfiles_storage.cache.get(cache_key)
self.assertEqual(cached_name, None)
self.assertEqual(self.cached_file_path(name), hashed_name)
cached_name = storage.staticfiles_storage.cache.get(cache_key)
self.assertEqual(cached_name, hashed_name)
def test_post_processing(self):
"""Test that post_processing behaves correctly.
Files that are alterable should always be post-processed; files that
aren't should be skipped.
collectstatic has already been called once in setUp() for this testcase,
therefore we check by verifying behavior on a second run.
"""
collectstatic_args = {
'interactive': False,
'verbosity': '0',
'link': False,
'clear': False,
'dry_run': False,
'post_process': True,
'use_default_ignore_patterns': True,
'ignore_patterns': ['*.ignoreme'],
}
collectstatic_cmd = CollectstaticCommand()
collectstatic_cmd.set_options(**collectstatic_args)
stats = collectstatic_cmd.collect()
self.assertTrue(os.path.join('cached', 'css', 'window.css') in stats['post_processed'])
self.assertTrue(os.path.join('cached', 'css', 'img', 'window.png') in stats['unmodified'])
def test_cache_key_memcache_validation(self):
"""
Handle cache key creation correctly, see #17861.
"""
name = "/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/" + chr(22) + chr(180)
cache_key = storage.staticfiles_storage.cache_key(name)
self.save_warnings_state()
cache_validator = BaseCache({})
warnings.filterwarnings('error', category=CacheKeyWarning)
cache_validator.validate_key(cache_key)
self.restore_warnings_state()
self.assertEqual(cache_key, 'staticfiles:e95bbc36387084582df2a70750d7b351')
if sys.platform != 'win32':
class TestCollectionLinks(CollectionTestCase, TestDefaults):
"""
Test ``--link`` option for ``collectstatic`` management command.
Note that by inheriting ``TestDefaults`` we repeat all
the standard file resolving tests here, to make sure using
``--link`` does not change the file-selection semantics.
"""
def run_collectstatic(self):
super(TestCollectionLinks, self).run_collectstatic(link=True)
def test_links_created(self):
"""
With ``--link``, symbolic links are created.
"""
self.assertTrue(os.path.islink(os.path.join(settings.STATIC_ROOT, 'test.txt')))
class TestServeStatic(StaticFilesTestCase):
"""
Test static asset serving view.
"""
urls = 'regressiontests.staticfiles_tests.urls.default'
def _response(self, filepath):
return self.client.get(
posixpath.join(settings.STATIC_URL, filepath))
def assertFileContains(self, filepath, text):
self.assertContains(self._response(filepath), text)
def assertFileNotFound(self, filepath):
self.assertEqual(self._response(filepath).status_code, 404)
class TestServeDisabled(TestServeStatic):
"""
Test serving static files disabled when DEBUG is False.
"""
def setUp(self):
super(TestServeDisabled, self).setUp()
settings.DEBUG = False
def test_disabled_serving(self):
self.assertRaisesRegexp(ImproperlyConfigured, 'The staticfiles view '
'can only be used in debug mode ', self._response, 'test.txt')
class TestServeStaticWithDefaultURL(TestServeStatic, TestDefaults):
"""
Test static asset serving view with manually configured URLconf.
"""
pass
class TestServeStaticWithURLHelper(TestServeStatic, TestDefaults):
"""
Test static asset serving view with staticfiles_urlpatterns helper.
"""
urls = 'regressiontests.staticfiles_tests.urls.helper'
class TestServeAdminMedia(TestServeStatic):
"""
Test serving media from django.contrib.admin.
"""
def _response(self, filepath):
return self.client.get(
posixpath.join(settings.STATIC_URL, 'admin/', filepath))
def test_serve_admin_media(self):
self.assertFileContains('css/base.css', 'body')
class FinderTestCase(object):
"""
Base finder test mixin.
On Windows, sometimes the case of the path we ask the finders for and the
path(s) they find can differ. Compare them using os.path.normcase() to
avoid false negatives.
"""
def test_find_first(self):
src, dst = self.find_first
found = self.finder.find(src)
self.assertEqual(os.path.normcase(found), os.path.normcase(dst))
def test_find_all(self):
src, dst = self.find_all
found = self.finder.find(src, all=True)
found = [os.path.normcase(f) for f in found]
dst = [os.path.normcase(d) for d in dst]
self.assertEqual(found, dst)
class TestFileSystemFinder(StaticFilesTestCase, FinderTestCase):
"""
Test FileSystemFinder.
"""
def setUp(self):
super(TestFileSystemFinder, self).setUp()
self.finder = finders.FileSystemFinder()
test_file_path = os.path.join(TEST_ROOT, 'project', 'documents', 'test', 'file.txt')
self.find_first = (os.path.join('test', 'file.txt'), test_file_path)
self.find_all = (os.path.join('test', 'file.txt'), [test_file_path])
class TestAppDirectoriesFinder(StaticFilesTestCase, FinderTestCase):
"""
Test AppDirectoriesFinder.
"""
def setUp(self):
super(TestAppDirectoriesFinder, self).setUp()
self.finder = finders.AppDirectoriesFinder()
test_file_path = os.path.join(TEST_ROOT, 'apps', 'test', 'static', 'test', 'file1.txt')
self.find_first = (os.path.join('test', 'file1.txt'), test_file_path)
self.find_all = (os.path.join('test', 'file1.txt'), [test_file_path])
class TestDefaultStorageFinder(StaticFilesTestCase, FinderTestCase):
"""
Test DefaultStorageFinder.
"""
def setUp(self):
super(TestDefaultStorageFinder, self).setUp()
self.finder = finders.DefaultStorageFinder(
storage=storage.StaticFilesStorage(location=settings.MEDIA_ROOT))
test_file_path = os.path.join(settings.MEDIA_ROOT, 'media-file.txt')
self.find_first = ('media-file.txt', test_file_path)
self.find_all = ('media-file.txt', [test_file_path])
class TestMiscFinder(TestCase):
"""
A few misc finder tests.
"""
def setUp(self):
default_storage._wrapped = empty
def test_get_finder(self):
self.assertIsInstance(finders.get_finder(
'django.contrib.staticfiles.finders.FileSystemFinder'),
finders.FileSystemFinder)
def test_get_finder_bad_classname(self):
self.assertRaises(ImproperlyConfigured, finders.get_finder,
'django.contrib.staticfiles.finders.FooBarFinder')
def test_get_finder_bad_module(self):
self.assertRaises(ImproperlyConfigured,
finders.get_finder, 'foo.bar.FooBarFinder')
@override_settings(STATICFILES_DIRS='a string')
def test_non_tuple_raises_exception(self):
"""
We can't determine if STATICFILES_DIRS is set correctly just by
looking at the type, but we can determine if it's definitely wrong.
"""
self.assertRaises(ImproperlyConfigured, finders.FileSystemFinder)
@override_settings(MEDIA_ROOT='')
def test_location_empty(self):
self.assertRaises(ImproperlyConfigured, finders.DefaultStorageFinder)
class TestTemplateTag(StaticFilesTestCase):
def test_template_tag(self):
self.assertStaticRenders("does/not/exist.png",
"/static/does/not/exist.png")
self.assertStaticRenders("testfile.txt", "/static/testfile.txt")
|
leereilly/django-1
|
tests/regressiontests/staticfiles_tests/tests.py
|
Python
|
bsd-3-clause
| 27,280
|
# Generated by Django 2.0.8 on 2018-09-10 13:20
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("order", "0054_move_data_to_order_events")]
operations = [
migrations.RemoveField(model_name="orderhistoryentry", name="order"),
migrations.RemoveField(model_name="orderhistoryentry", name="user"),
migrations.RemoveField(model_name="ordernote", name="order"),
migrations.RemoveField(model_name="ordernote", name="user"),
migrations.DeleteModel(name="OrderHistoryEntry"),
migrations.DeleteModel(name="OrderNote"),
]
|
maferelo/saleor
|
saleor/order/migrations/0055_remove_order_note_order_history_entry.py
|
Python
|
bsd-3-clause
| 617
|
# Copyright (c) 2012-2013 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality of the software
# licensed hereunder. You may use the software subject to the license
# terms below provided that you ensure that this notice is replicated
# unmodified and in its entirety in all distributions of the software,
# modified or unmodified, in source code or in binary form.
#
# Copyright (c) 2004-2006 The Regents of The University of Michigan
# Copyright (c) 2010-2011 Advanced Micro Devices, 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 the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Steve Reinhardt
# Nathan Binkert
# Gabe Black
# Andreas Hansson
#####################################################################
#
# Parameter description classes
#
# The _params dictionary in each class maps parameter names to either
# a Param or a VectorParam object. These objects contain the
# parameter description string, the parameter type, and the default
# value (if any). The convert() method on these objects is used to
# force whatever value is assigned to the parameter to the appropriate
# type.
#
# Note that the default values are loaded into the class's attribute
# space when the parameter dictionary is initialized (in
# MetaSimObject._new_param()); after that point they aren't used.
#
#####################################################################
import copy
import datetime
import re
import sys
import time
import math
import proxy
import ticks
from util import *
def isSimObject(*args, **kwargs):
return SimObject.isSimObject(*args, **kwargs)
def isSimObjectSequence(*args, **kwargs):
return SimObject.isSimObjectSequence(*args, **kwargs)
def isSimObjectClass(*args, **kwargs):
return SimObject.isSimObjectClass(*args, **kwargs)
allParams = {}
class MetaParamValue(type):
def __new__(mcls, name, bases, dct):
cls = super(MetaParamValue, mcls).__new__(mcls, name, bases, dct)
assert name not in allParams
allParams[name] = cls
return cls
# Dummy base class to identify types that are legitimate for SimObject
# parameters.
class ParamValue(object):
__metaclass__ = MetaParamValue
# Generate the code needed as a prerequisite for declaring a C++
# object of this type. Typically generates one or more #include
# statements. Used when declaring parameters of this type.
@classmethod
def cxx_predecls(cls, code):
pass
# Generate the code needed as a prerequisite for including a
# reference to a C++ object of this type in a SWIG .i file.
# Typically generates one or more %import or %include statements.
@classmethod
def swig_predecls(cls, code):
pass
# default for printing to .ini file is regular string conversion.
# will be overridden in some cases
def ini_str(self):
return str(self)
# allows us to blithely call unproxy() on things without checking
# if they're really proxies or not
def unproxy(self, base):
return self
# Regular parameter description.
class ParamDesc(object):
def __init__(self, ptype_str, ptype, *args, **kwargs):
self.ptype_str = ptype_str
# remember ptype only if it is provided
if ptype != None:
self.ptype = ptype
if args:
if len(args) == 1:
self.desc = args[0]
elif len(args) == 2:
self.default = args[0]
self.desc = args[1]
else:
raise TypeError, 'too many arguments'
if kwargs.has_key('desc'):
assert(not hasattr(self, 'desc'))
self.desc = kwargs['desc']
del kwargs['desc']
if kwargs.has_key('default'):
assert(not hasattr(self, 'default'))
self.default = kwargs['default']
del kwargs['default']
if kwargs:
raise TypeError, 'extra unknown kwargs %s' % kwargs
if not hasattr(self, 'desc'):
raise TypeError, 'desc attribute missing'
def __getattr__(self, attr):
if attr == 'ptype':
ptype = SimObject.allClasses[self.ptype_str]
assert isSimObjectClass(ptype)
self.ptype = ptype
return ptype
raise AttributeError, "'%s' object has no attribute '%s'" % \
(type(self).__name__, attr)
def convert(self, value):
if isinstance(value, proxy.BaseProxy):
value.set_param_desc(self)
return value
if not hasattr(self, 'ptype') and isNullPointer(value):
# deferred evaluation of SimObject; continue to defer if
# we're just assigning a null pointer
return value
if isinstance(value, self.ptype):
return value
if isNullPointer(value) and isSimObjectClass(self.ptype):
return value
return self.ptype(value)
def cxx_predecls(self, code):
code('#include <cstddef>')
self.ptype.cxx_predecls(code)
def swig_predecls(self, code):
self.ptype.swig_predecls(code)
def cxx_decl(self, code):
code('${{self.ptype.cxx_type}} ${{self.name}};')
# Vector-valued parameter description. Just like ParamDesc, except
# that the value is a vector (list) of the specified type instead of a
# single value.
class VectorParamValue(list):
__metaclass__ = MetaParamValue
def __setattr__(self, attr, value):
raise AttributeError, \
"Not allowed to set %s on '%s'" % (attr, type(self).__name__)
def ini_str(self):
return ' '.join([v.ini_str() for v in self])
def getValue(self):
return [ v.getValue() for v in self ]
def unproxy(self, base):
if len(self) == 1 and isinstance(self[0], proxy.AllProxy):
return self[0].unproxy(base)
else:
return [v.unproxy(base) for v in self]
class SimObjectVector(VectorParamValue):
# support clone operation
def __call__(self, **kwargs):
return SimObjectVector([v(**kwargs) for v in self])
def clear_parent(self, old_parent):
for v in self:
v.clear_parent(old_parent)
def set_parent(self, parent, name):
if len(self) == 1:
self[0].set_parent(parent, name)
else:
width = int(math.ceil(math.log(len(self))/math.log(10)))
for i,v in enumerate(self):
v.set_parent(parent, "%s%0*d" % (name, width, i))
def has_parent(self):
return reduce(lambda x,y: x and y, [v.has_parent() for v in self])
# return 'cpu0 cpu1' etc. for print_ini()
def get_name(self):
return ' '.join([v._name for v in self])
# By iterating through the constituent members of the vector here
# we can nicely handle iterating over all a SimObject's children
# without having to provide lots of special functions on
# SimObjectVector directly.
def descendants(self):
for v in self:
for obj in v.descendants():
yield obj
def get_config_as_dict(self):
a = []
for v in self:
a.append(v.get_config_as_dict())
return a
# If we are replacing an item in the vector, make sure to set the
# parent reference of the new SimObject to be the same as the parent
# of the SimObject being replaced. Useful to have if we created
# a SimObjectVector of temporary objects that will be modified later in
# configuration scripts.
def __setitem__(self, key, value):
val = self[key]
if value.has_parent():
warn("SimObject %s already has a parent" % value.get_name() +\
" that is being overwritten by a SimObjectVector")
value.set_parent(val.get_parent(), val._name)
super(SimObjectVector, self).__setitem__(key, value)
class VectorParamDesc(ParamDesc):
# Convert assigned value to appropriate type. If the RHS is not a
# list or tuple, it generates a single-element list.
def convert(self, value):
if isinstance(value, (list, tuple)):
# list: coerce each element into new list
tmp_list = [ ParamDesc.convert(self, v) for v in value ]
else:
# singleton: coerce to a single-element list
tmp_list = [ ParamDesc.convert(self, value) ]
if isSimObjectSequence(tmp_list):
return SimObjectVector(tmp_list)
else:
return VectorParamValue(tmp_list)
def swig_module_name(self):
return "%s_vector" % self.ptype_str
def swig_predecls(self, code):
code('%import "${{self.swig_module_name()}}.i"')
def swig_decl(self, code):
code('%module(package="m5.internal") ${{self.swig_module_name()}}')
code('%{')
self.ptype.cxx_predecls(code)
code('%}')
code()
# Make sure the SWIGPY_SLICE_ARG is defined through this inclusion
code('%include "std_container.i"')
code()
self.ptype.swig_predecls(code)
code()
code('%include "std_vector.i"')
code()
ptype = self.ptype_str
cxx_type = self.ptype.cxx_type
code('''\
%typemap(in) std::vector< $cxx_type >::value_type {
if (SWIG_ConvertPtr($$input, (void **)&$$1, $$1_descriptor, 0) == -1) {
if (SWIG_ConvertPtr($$input, (void **)&$$1,
$$descriptor($cxx_type), 0) == -1) {
return NULL;
}
}
}
%typemap(in) std::vector< $cxx_type >::value_type * {
if (SWIG_ConvertPtr($$input, (void **)&$$1, $$1_descriptor, 0) == -1) {
if (SWIG_ConvertPtr($$input, (void **)&$$1,
$$descriptor($cxx_type *), 0) == -1) {
return NULL;
}
}
}
''')
code('%template(vector_$ptype) std::vector< $cxx_type >;')
def cxx_predecls(self, code):
code('#include <vector>')
self.ptype.cxx_predecls(code)
def cxx_decl(self, code):
code('std::vector< ${{self.ptype.cxx_type}} > ${{self.name}};')
class ParamFactory(object):
def __init__(self, param_desc_class, ptype_str = None):
self.param_desc_class = param_desc_class
self.ptype_str = ptype_str
def __getattr__(self, attr):
if self.ptype_str:
attr = self.ptype_str + '.' + attr
return ParamFactory(self.param_desc_class, attr)
# E.g., Param.Int(5, "number of widgets")
def __call__(self, *args, **kwargs):
ptype = None
try:
ptype = allParams[self.ptype_str]
except KeyError:
# if name isn't defined yet, assume it's a SimObject, and
# try to resolve it later
pass
return self.param_desc_class(self.ptype_str, ptype, *args, **kwargs)
Param = ParamFactory(ParamDesc)
VectorParam = ParamFactory(VectorParamDesc)
#####################################################################
#
# Parameter Types
#
# Though native Python types could be used to specify parameter types
# (the 'ptype' field of the Param and VectorParam classes), it's more
# flexible to define our own set of types. This gives us more control
# over how Python expressions are converted to values (via the
# __init__() constructor) and how these values are printed out (via
# the __str__() conversion method).
#
#####################################################################
# String-valued parameter. Just mixin the ParamValue class with the
# built-in str class.
class String(ParamValue,str):
cxx_type = 'std::string'
@classmethod
def cxx_predecls(self, code):
code('#include <string>')
@classmethod
def swig_predecls(cls, code):
code('%include "std_string.i"')
def getValue(self):
return self
# superclass for "numeric" parameter values, to emulate math
# operations in a type-safe way. e.g., a Latency times an int returns
# a new Latency object.
class NumericParamValue(ParamValue):
def __str__(self):
return str(self.value)
def __float__(self):
return float(self.value)
def __long__(self):
return long(self.value)
def __int__(self):
return int(self.value)
# hook for bounds checking
def _check(self):
return
def __mul__(self, other):
newobj = self.__class__(self)
newobj.value *= other
newobj._check()
return newobj
__rmul__ = __mul__
def __div__(self, other):
newobj = self.__class__(self)
newobj.value /= other
newobj._check()
return newobj
def __sub__(self, other):
newobj = self.__class__(self)
newobj.value -= other
newobj._check()
return newobj
# Metaclass for bounds-checked integer parameters. See CheckedInt.
class CheckedIntType(MetaParamValue):
def __init__(cls, name, bases, dict):
super(CheckedIntType, cls).__init__(name, bases, dict)
# CheckedInt is an abstract base class, so we actually don't
# want to do any processing on it... the rest of this code is
# just for classes that derive from CheckedInt.
if name == 'CheckedInt':
return
if not (hasattr(cls, 'min') and hasattr(cls, 'max')):
if not (hasattr(cls, 'size') and hasattr(cls, 'unsigned')):
panic("CheckedInt subclass %s must define either\n" \
" 'min' and 'max' or 'size' and 'unsigned'\n",
name);
if cls.unsigned:
cls.min = 0
cls.max = 2 ** cls.size - 1
else:
cls.min = -(2 ** (cls.size - 1))
cls.max = (2 ** (cls.size - 1)) - 1
# Abstract superclass for bounds-checked integer parameters. This
# class is subclassed to generate parameter classes with specific
# bounds. Initialization of the min and max bounds is done in the
# metaclass CheckedIntType.__init__.
class CheckedInt(NumericParamValue):
__metaclass__ = CheckedIntType
def _check(self):
if not self.min <= self.value <= self.max:
raise TypeError, 'Integer param out of bounds %d < %d < %d' % \
(self.min, self.value, self.max)
def __init__(self, value):
if isinstance(value, str):
self.value = convert.toInteger(value)
elif isinstance(value, (int, long, float, NumericParamValue)):
self.value = long(value)
else:
raise TypeError, "Can't convert object of type %s to CheckedInt" \
% type(value).__name__
self._check()
@classmethod
def cxx_predecls(cls, code):
# most derived types require this, so we just do it here once
code('#include "base/types.hh"')
@classmethod
def swig_predecls(cls, code):
# most derived types require this, so we just do it here once
code('%import "stdint.i"')
code('%import "base/types.hh"')
def getValue(self):
return long(self.value)
class Int(CheckedInt): cxx_type = 'int'; size = 32; unsigned = False
class Unsigned(CheckedInt): cxx_type = 'unsigned'; size = 32; unsigned = True
class Int8(CheckedInt): cxx_type = 'int8_t'; size = 8; unsigned = False
class UInt8(CheckedInt): cxx_type = 'uint8_t'; size = 8; unsigned = True
class Int16(CheckedInt): cxx_type = 'int16_t'; size = 16; unsigned = False
class UInt16(CheckedInt): cxx_type = 'uint16_t'; size = 16; unsigned = True
class Int32(CheckedInt): cxx_type = 'int32_t'; size = 32; unsigned = False
class UInt32(CheckedInt): cxx_type = 'uint32_t'; size = 32; unsigned = True
class Int64(CheckedInt): cxx_type = 'int64_t'; size = 64; unsigned = False
class UInt64(CheckedInt): cxx_type = 'uint64_t'; size = 64; unsigned = True
class Counter(CheckedInt): cxx_type = 'Counter'; size = 64; unsigned = True
class Tick(CheckedInt): cxx_type = 'Tick'; size = 64; unsigned = True
class TcpPort(CheckedInt): cxx_type = 'uint16_t'; size = 16; unsigned = True
class UdpPort(CheckedInt): cxx_type = 'uint16_t'; size = 16; unsigned = True
class Percent(CheckedInt): cxx_type = 'int'; min = 0; max = 100
class Cycles(CheckedInt):
cxx_type = 'Cycles'
size = 64
unsigned = True
def getValue(self):
from m5.internal.core import Cycles
return Cycles(self.value)
class Float(ParamValue, float):
cxx_type = 'double'
def __init__(self, value):
if isinstance(value, (int, long, float, NumericParamValue, Float)):
self.value = float(value)
else:
raise TypeError, "Can't convert object of type %s to Float" \
% type(value).__name__
def getValue(self):
return float(self.value)
class MemorySize(CheckedInt):
cxx_type = 'uint64_t'
size = 64
unsigned = True
def __init__(self, value):
if isinstance(value, MemorySize):
self.value = value.value
else:
self.value = convert.toMemorySize(value)
self._check()
class MemorySize32(CheckedInt):
cxx_type = 'uint32_t'
size = 32
unsigned = True
def __init__(self, value):
if isinstance(value, MemorySize):
self.value = value.value
else:
self.value = convert.toMemorySize(value)
self._check()
class Addr(CheckedInt):
cxx_type = 'Addr'
size = 64
unsigned = True
def __init__(self, value):
if isinstance(value, Addr):
self.value = value.value
else:
try:
self.value = convert.toMemorySize(value)
except TypeError:
self.value = long(value)
self._check()
def __add__(self, other):
if isinstance(other, Addr):
return self.value + other.value
else:
return self.value + other
class AddrRange(ParamValue):
cxx_type = 'AddrRange'
def __init__(self, *args, **kwargs):
# Disable interleaving by default
self.intlvHighBit = 0
self.intlvBits = 0
self.intlvMatch = 0
def handle_kwargs(self, kwargs):
# An address range needs to have an upper limit, specified
# either explicitly with an end, or as an offset using the
# size keyword.
if 'end' in kwargs:
self.end = Addr(kwargs.pop('end'))
elif 'size' in kwargs:
self.end = self.start + Addr(kwargs.pop('size')) - 1
else:
raise TypeError, "Either end or size must be specified"
# Now on to the optional bit
if 'intlvHighBit' in kwargs:
self.intlvHighBit = int(kwargs.pop('intlvHighBit'))
if 'intlvBits' in kwargs:
self.intlvBits = int(kwargs.pop('intlvBits'))
if 'intlvMatch' in kwargs:
self.intlvMatch = int(kwargs.pop('intlvMatch'))
if len(args) == 0:
self.start = Addr(kwargs.pop('start'))
handle_kwargs(self, kwargs)
elif len(args) == 1:
if kwargs:
self.start = Addr(args[0])
handle_kwargs(self, kwargs)
elif isinstance(args[0], (list, tuple)):
self.start = Addr(args[0][0])
self.end = Addr(args[0][1])
else:
self.start = Addr(0)
self.end = Addr(args[0]) - 1
elif len(args) == 2:
self.start = Addr(args[0])
self.end = Addr(args[1])
else:
raise TypeError, "Too many arguments specified"
if kwargs:
raise TypeError, "Too many keywords: %s" % kwargs.keys()
def __str__(self):
return '%s:%s' % (self.start, self.end)
def size(self):
# Divide the size by the size of the interleaving slice
return (long(self.end) - long(self.start) + 1) >> self.intlvBits
@classmethod
def cxx_predecls(cls, code):
Addr.cxx_predecls(code)
code('#include "base/addr_range.hh"')
@classmethod
def swig_predecls(cls, code):
Addr.swig_predecls(code)
def getValue(self):
# Go from the Python class to the wrapped C++ class generated
# by swig
from m5.internal.range import AddrRange
return AddrRange(long(self.start), long(self.end),
int(self.intlvHighBit), int(self.intlvBits),
int(self.intlvMatch))
# Boolean parameter type. Python doesn't let you subclass bool, since
# it doesn't want to let you create multiple instances of True and
# False. Thus this is a little more complicated than String.
class Bool(ParamValue):
cxx_type = 'bool'
def __init__(self, value):
try:
self.value = convert.toBool(value)
except TypeError:
self.value = bool(value)
def getValue(self):
return bool(self.value)
def __str__(self):
return str(self.value)
# implement truth value testing for Bool parameters so that these params
# evaluate correctly during the python configuration phase
def __nonzero__(self):
return bool(self.value)
def ini_str(self):
if self.value:
return 'true'
return 'false'
def IncEthernetAddr(addr, val = 1):
bytes = map(lambda x: int(x, 16), addr.split(':'))
bytes[5] += val
for i in (5, 4, 3, 2, 1):
val,rem = divmod(bytes[i], 256)
bytes[i] = rem
if val == 0:
break
bytes[i - 1] += val
assert(bytes[0] <= 255)
return ':'.join(map(lambda x: '%02x' % x, bytes))
_NextEthernetAddr = "00:90:00:00:00:01"
def NextEthernetAddr():
global _NextEthernetAddr
value = _NextEthernetAddr
_NextEthernetAddr = IncEthernetAddr(_NextEthernetAddr, 1)
return value
class EthernetAddr(ParamValue):
cxx_type = 'Net::EthAddr'
@classmethod
def cxx_predecls(cls, code):
code('#include "base/inet.hh"')
@classmethod
def swig_predecls(cls, code):
code('%include "python/swig/inet.i"')
def __init__(self, value):
if value == NextEthernetAddr:
self.value = value
return
if not isinstance(value, str):
raise TypeError, "expected an ethernet address and didn't get one"
bytes = value.split(':')
if len(bytes) != 6:
raise TypeError, 'invalid ethernet address %s' % value
for byte in bytes:
if not 0 <= int(byte, base=16) <= 0xff:
raise TypeError, 'invalid ethernet address %s' % value
self.value = value
def unproxy(self, base):
if self.value == NextEthernetAddr:
return EthernetAddr(self.value())
return self
def getValue(self):
from m5.internal.params import EthAddr
return EthAddr(self.value)
def ini_str(self):
return self.value
# When initializing an IpAddress, pass in an existing IpAddress, a string of
# the form "a.b.c.d", or an integer representing an IP.
class IpAddress(ParamValue):
cxx_type = 'Net::IpAddress'
@classmethod
def cxx_predecls(cls, code):
code('#include "base/inet.hh"')
@classmethod
def swig_predecls(cls, code):
code('%include "python/swig/inet.i"')
def __init__(self, value):
if isinstance(value, IpAddress):
self.ip = value.ip
else:
try:
self.ip = convert.toIpAddress(value)
except TypeError:
self.ip = long(value)
self.verifyIp()
def __str__(self):
tup = [(self.ip >> i) & 0xff for i in (24, 16, 8, 0)]
return '%d.%d.%d.%d' % tuple(tup)
def __eq__(self, other):
if isinstance(other, IpAddress):
return self.ip == other.ip
elif isinstance(other, str):
try:
return self.ip == convert.toIpAddress(other)
except:
return False
else:
return self.ip == other
def __ne__(self, other):
return not (self == other)
def verifyIp(self):
if self.ip < 0 or self.ip >= (1 << 32):
raise TypeError, "invalid ip address %#08x" % self.ip
def getValue(self):
from m5.internal.params import IpAddress
return IpAddress(self.ip)
# When initializing an IpNetmask, pass in an existing IpNetmask, a string of
# the form "a.b.c.d/n" or "a.b.c.d/e.f.g.h", or an ip and netmask as
# positional or keyword arguments.
class IpNetmask(IpAddress):
cxx_type = 'Net::IpNetmask'
@classmethod
def cxx_predecls(cls, code):
code('#include "base/inet.hh"')
@classmethod
def swig_predecls(cls, code):
code('%include "python/swig/inet.i"')
def __init__(self, *args, **kwargs):
def handle_kwarg(self, kwargs, key, elseVal = None):
if key in kwargs:
setattr(self, key, kwargs.pop(key))
elif elseVal:
setattr(self, key, elseVal)
else:
raise TypeError, "No value set for %s" % key
if len(args) == 0:
handle_kwarg(self, kwargs, 'ip')
handle_kwarg(self, kwargs, 'netmask')
elif len(args) == 1:
if kwargs:
if not 'ip' in kwargs and not 'netmask' in kwargs:
raise TypeError, "Invalid arguments"
handle_kwarg(self, kwargs, 'ip', args[0])
handle_kwarg(self, kwargs, 'netmask', args[0])
elif isinstance(args[0], IpNetmask):
self.ip = args[0].ip
self.netmask = args[0].netmask
else:
(self.ip, self.netmask) = convert.toIpNetmask(args[0])
elif len(args) == 2:
self.ip = args[0]
self.netmask = args[1]
else:
raise TypeError, "Too many arguments specified"
if kwargs:
raise TypeError, "Too many keywords: %s" % kwargs.keys()
self.verify()
def __str__(self):
return "%s/%d" % (super(IpNetmask, self).__str__(), self.netmask)
def __eq__(self, other):
if isinstance(other, IpNetmask):
return self.ip == other.ip and self.netmask == other.netmask
elif isinstance(other, str):
try:
return (self.ip, self.netmask) == convert.toIpNetmask(other)
except:
return False
else:
return False
def verify(self):
self.verifyIp()
if self.netmask < 0 or self.netmask > 32:
raise TypeError, "invalid netmask %d" % netmask
def getValue(self):
from m5.internal.params import IpNetmask
return IpNetmask(self.ip, self.netmask)
# When initializing an IpWithPort, pass in an existing IpWithPort, a string of
# the form "a.b.c.d:p", or an ip and port as positional or keyword arguments.
class IpWithPort(IpAddress):
cxx_type = 'Net::IpWithPort'
@classmethod
def cxx_predecls(cls, code):
code('#include "base/inet.hh"')
@classmethod
def swig_predecls(cls, code):
code('%include "python/swig/inet.i"')
def __init__(self, *args, **kwargs):
def handle_kwarg(self, kwargs, key, elseVal = None):
if key in kwargs:
setattr(self, key, kwargs.pop(key))
elif elseVal:
setattr(self, key, elseVal)
else:
raise TypeError, "No value set for %s" % key
if len(args) == 0:
handle_kwarg(self, kwargs, 'ip')
handle_kwarg(self, kwargs, 'port')
elif len(args) == 1:
if kwargs:
if not 'ip' in kwargs and not 'port' in kwargs:
raise TypeError, "Invalid arguments"
handle_kwarg(self, kwargs, 'ip', args[0])
handle_kwarg(self, kwargs, 'port', args[0])
elif isinstance(args[0], IpWithPort):
self.ip = args[0].ip
self.port = args[0].port
else:
(self.ip, self.port) = convert.toIpWithPort(args[0])
elif len(args) == 2:
self.ip = args[0]
self.port = args[1]
else:
raise TypeError, "Too many arguments specified"
if kwargs:
raise TypeError, "Too many keywords: %s" % kwargs.keys()
self.verify()
def __str__(self):
return "%s:%d" % (super(IpWithPort, self).__str__(), self.port)
def __eq__(self, other):
if isinstance(other, IpWithPort):
return self.ip == other.ip and self.port == other.port
elif isinstance(other, str):
try:
return (self.ip, self.port) == convert.toIpWithPort(other)
except:
return False
else:
return False
def verify(self):
self.verifyIp()
if self.port < 0 or self.port > 0xffff:
raise TypeError, "invalid port %d" % self.port
def getValue(self):
from m5.internal.params import IpWithPort
return IpWithPort(self.ip, self.port)
time_formats = [ "%a %b %d %H:%M:%S %Z %Y",
"%a %b %d %H:%M:%S %Z %Y",
"%Y/%m/%d %H:%M:%S",
"%Y/%m/%d %H:%M",
"%Y/%m/%d",
"%m/%d/%Y %H:%M:%S",
"%m/%d/%Y %H:%M",
"%m/%d/%Y",
"%m/%d/%y %H:%M:%S",
"%m/%d/%y %H:%M",
"%m/%d/%y"]
def parse_time(value):
from time import gmtime, strptime, struct_time, time
from datetime import datetime, date
if isinstance(value, struct_time):
return value
if isinstance(value, (int, long)):
return gmtime(value)
if isinstance(value, (datetime, date)):
return value.timetuple()
if isinstance(value, str):
if value in ('Now', 'Today'):
return time.gmtime(time.time())
for format in time_formats:
try:
return strptime(value, format)
except ValueError:
pass
raise ValueError, "Could not parse '%s' as a time" % value
class Time(ParamValue):
cxx_type = 'tm'
@classmethod
def cxx_predecls(cls, code):
code('#include <time.h>')
@classmethod
def swig_predecls(cls, code):
code('%include "python/swig/time.i"')
def __init__(self, value):
self.value = parse_time(value)
def getValue(self):
from m5.internal.params import tm
c_time = tm()
py_time = self.value
# UNIX is years since 1900
c_time.tm_year = py_time.tm_year - 1900;
# Python starts at 1, UNIX starts at 0
c_time.tm_mon = py_time.tm_mon - 1;
c_time.tm_mday = py_time.tm_mday;
c_time.tm_hour = py_time.tm_hour;
c_time.tm_min = py_time.tm_min;
c_time.tm_sec = py_time.tm_sec;
# Python has 0 as Monday, UNIX is 0 as sunday
c_time.tm_wday = py_time.tm_wday + 1
if c_time.tm_wday > 6:
c_time.tm_wday -= 7;
# Python starts at 1, Unix starts at 0
c_time.tm_yday = py_time.tm_yday - 1;
return c_time
def __str__(self):
return time.asctime(self.value)
def ini_str(self):
return str(self)
def get_config_as_dict(self):
return str(self)
# Enumerated types are a little more complex. The user specifies the
# type as Enum(foo) where foo is either a list or dictionary of
# alternatives (typically strings, but not necessarily so). (In the
# long run, the integer value of the parameter will be the list index
# or the corresponding dictionary value. For now, since we only check
# that the alternative is valid and then spit it into a .ini file,
# there's not much point in using the dictionary.)
# What Enum() must do is generate a new type encapsulating the
# provided list/dictionary so that specific values of the parameter
# can be instances of that type. We define two hidden internal
# classes (_ListEnum and _DictEnum) to serve as base classes, then
# derive the new type from the appropriate base class on the fly.
allEnums = {}
# Metaclass for Enum types
class MetaEnum(MetaParamValue):
def __new__(mcls, name, bases, dict):
assert name not in allEnums
cls = super(MetaEnum, mcls).__new__(mcls, name, bases, dict)
allEnums[name] = cls
return cls
def __init__(cls, name, bases, init_dict):
if init_dict.has_key('map'):
if not isinstance(cls.map, dict):
raise TypeError, "Enum-derived class attribute 'map' " \
"must be of type dict"
# build list of value strings from map
cls.vals = cls.map.keys()
cls.vals.sort()
elif init_dict.has_key('vals'):
if not isinstance(cls.vals, list):
raise TypeError, "Enum-derived class attribute 'vals' " \
"must be of type list"
# build string->value map from vals sequence
cls.map = {}
for idx,val in enumerate(cls.vals):
cls.map[val] = idx
else:
raise TypeError, "Enum-derived class must define "\
"attribute 'map' or 'vals'"
cls.cxx_type = 'Enums::%s' % name
super(MetaEnum, cls).__init__(name, bases, init_dict)
# Generate C++ class declaration for this enum type.
# Note that we wrap the enum in a class/struct to act as a namespace,
# so that the enum strings can be brief w/o worrying about collisions.
def cxx_decl(cls, code):
name = cls.__name__
code('''\
#ifndef __ENUM__${name}__
#define __ENUM__${name}__
namespace Enums {
enum $name {
''')
code.indent(2)
for val in cls.vals:
code('$val = ${{cls.map[val]}},')
code('Num_$name = ${{len(cls.vals)}}')
code.dedent(2)
code('''\
};
extern const char *${name}Strings[Num_${name}];
}
#endif // __ENUM__${name}__
''')
def cxx_def(cls, code):
name = cls.__name__
code('''\
#include "enums/$name.hh"
namespace Enums {
const char *${name}Strings[Num_${name}] =
{
''')
code.indent(2)
for val in cls.vals:
code('"$val",')
code.dedent(2)
code('''
};
} // namespace Enums
''')
def swig_decl(cls, code):
name = cls.__name__
code('''\
%module(package="m5.internal") enum_$name
%{
#include "enums/$name.hh"
%}
%include "enums/$name.hh"
''')
# Base class for enum types.
class Enum(ParamValue):
__metaclass__ = MetaEnum
vals = []
def __init__(self, value):
if value not in self.map:
raise TypeError, "Enum param got bad value '%s' (not in %s)" \
% (value, self.vals)
self.value = value
@classmethod
def cxx_predecls(cls, code):
code('#include "enums/$0.hh"', cls.__name__)
@classmethod
def swig_predecls(cls, code):
code('%import "python/m5/internal/enum_$0.i"', cls.__name__)
def getValue(self):
return int(self.map[self.value])
def __str__(self):
return self.value
# how big does a rounding error need to be before we warn about it?
frequency_tolerance = 0.001 # 0.1%
class TickParamValue(NumericParamValue):
cxx_type = 'Tick'
@classmethod
def cxx_predecls(cls, code):
code('#include "base/types.hh"')
@classmethod
def swig_predecls(cls, code):
code('%import "stdint.i"')
code('%import "base/types.hh"')
def getValue(self):
return long(self.value)
class Latency(TickParamValue):
def __init__(self, value):
if isinstance(value, (Latency, Clock)):
self.ticks = value.ticks
self.value = value.value
elif isinstance(value, Frequency):
self.ticks = value.ticks
self.value = 1.0 / value.value
elif value.endswith('t'):
self.ticks = True
self.value = int(value[:-1])
else:
self.ticks = False
self.value = convert.toLatency(value)
def __getattr__(self, attr):
if attr in ('latency', 'period'):
return self
if attr == 'frequency':
return Frequency(self)
raise AttributeError, "Latency object has no attribute '%s'" % attr
def getValue(self):
if self.ticks or self.value == 0:
value = self.value
else:
value = ticks.fromSeconds(self.value)
return long(value)
# convert latency to ticks
def ini_str(self):
return '%d' % self.getValue()
class Frequency(TickParamValue):
def __init__(self, value):
if isinstance(value, (Latency, Clock)):
if value.value == 0:
self.value = 0
else:
self.value = 1.0 / value.value
self.ticks = value.ticks
elif isinstance(value, Frequency):
self.value = value.value
self.ticks = value.ticks
else:
self.ticks = False
self.value = convert.toFrequency(value)
def __getattr__(self, attr):
if attr == 'frequency':
return self
if attr in ('latency', 'period'):
return Latency(self)
raise AttributeError, "Frequency object has no attribute '%s'" % attr
# convert latency to ticks
def getValue(self):
if self.ticks or self.value == 0:
value = self.value
else:
value = ticks.fromSeconds(1.0 / self.value)
return long(value)
def ini_str(self):
return '%d' % self.getValue()
# A generic Frequency and/or Latency value. Value is stored as a
# latency, just like Latency and Frequency.
class Clock(TickParamValue):
def __init__(self, value):
if isinstance(value, (Latency, Clock)):
self.ticks = value.ticks
self.value = value.value
elif isinstance(value, Frequency):
self.ticks = value.ticks
self.value = 1.0 / value.value
elif value.endswith('t'):
self.ticks = True
self.value = int(value[:-1])
else:
self.ticks = False
self.value = convert.anyToLatency(value)
def __getattr__(self, attr):
if attr == 'frequency':
return Frequency(self)
if attr in ('latency', 'period'):
return Latency(self)
raise AttributeError, "Frequency object has no attribute '%s'" % attr
def getValue(self):
return self.period.getValue()
def ini_str(self):
return self.period.ini_str()
class Voltage(float,ParamValue):
cxx_type = 'double'
def __new__(cls, value):
# convert to voltage
val = convert.toVoltage(value)
return super(cls, Voltage).__new__(cls, val)
def __str__(self):
return str(self.val)
def getValue(self):
value = float(self)
return value
def ini_str(self):
return '%f' % self.getValue()
class NetworkBandwidth(float,ParamValue):
cxx_type = 'float'
def __new__(cls, value):
# convert to bits per second
val = convert.toNetworkBandwidth(value)
return super(cls, NetworkBandwidth).__new__(cls, val)
def __str__(self):
return str(self.val)
def getValue(self):
# convert to seconds per byte
value = 8.0 / float(self)
# convert to ticks per byte
value = ticks.fromSeconds(value)
return float(value)
def ini_str(self):
return '%f' % self.getValue()
class MemoryBandwidth(float,ParamValue):
cxx_type = 'float'
def __new__(cls, value):
# convert to bytes per second
val = convert.toMemoryBandwidth(value)
return super(cls, MemoryBandwidth).__new__(cls, val)
def __str__(self):
return str(self.val)
def getValue(self):
# convert to seconds per byte
value = float(self)
if value:
value = 1.0 / float(self)
# convert to ticks per byte
value = ticks.fromSeconds(value)
return float(value)
def ini_str(self):
return '%f' % self.getValue()
#
# "Constants"... handy aliases for various values.
#
# Special class for NULL pointers. Note the special check in
# make_param_value() above that lets these be assigned where a
# SimObject is required.
# only one copy of a particular node
class NullSimObject(object):
__metaclass__ = Singleton
def __call__(cls):
return cls
def _instantiate(self, parent = None, path = ''):
pass
def ini_str(self):
return 'Null'
def unproxy(self, base):
return self
def set_path(self, parent, name):
pass
def __str__(self):
return 'Null'
def getValue(self):
return None
# The only instance you'll ever need...
NULL = NullSimObject()
def isNullPointer(value):
return isinstance(value, NullSimObject)
# Some memory range specifications use this as a default upper bound.
MaxAddr = Addr.max
MaxTick = Tick.max
AllMemory = AddrRange(0, MaxAddr)
#####################################################################
#
# Port objects
#
# Ports are used to interconnect objects in the memory system.
#
#####################################################################
# Port reference: encapsulates a reference to a particular port on a
# particular SimObject.
class PortRef(object):
def __init__(self, simobj, name, role):
assert(isSimObject(simobj) or isSimObjectClass(simobj))
self.simobj = simobj
self.name = name
self.role = role
self.peer = None # not associated with another port yet
self.ccConnected = False # C++ port connection done?
self.index = -1 # always -1 for non-vector ports
def __str__(self):
return '%s.%s' % (self.simobj, self.name)
def __len__(self):
# Return the number of connected ports, i.e. 0 is we have no
# peer and 1 if we do.
return int(self.peer != None)
# for config.ini, print peer's name (not ours)
def ini_str(self):
return str(self.peer)
# for config.json
def get_config_as_dict(self):
return {'role' : self.role, 'peer' : str(self.peer)}
def __getattr__(self, attr):
if attr == 'peerObj':
# shorthand for proxies
return self.peer.simobj
raise AttributeError, "'%s' object has no attribute '%s'" % \
(self.__class__.__name__, attr)
# Full connection is symmetric (both ways). Called via
# SimObject.__setattr__ as a result of a port assignment, e.g.,
# "obj1.portA = obj2.portB", or via VectorPortElementRef.__setitem__,
# e.g., "obj1.portA[3] = obj2.portB".
def connect(self, other):
if isinstance(other, VectorPortRef):
# reference to plain VectorPort is implicit append
other = other._get_next()
if self.peer and not proxy.isproxy(self.peer):
fatal("Port %s is already connected to %s, cannot connect %s\n",
self, self.peer, other);
self.peer = other
if proxy.isproxy(other):
other.set_param_desc(PortParamDesc())
elif isinstance(other, PortRef):
if other.peer is not self:
other.connect(self)
else:
raise TypeError, \
"assigning non-port reference '%s' to port '%s'" \
% (other, self)
def clone(self, simobj, memo):
if memo.has_key(self):
return memo[self]
newRef = copy.copy(self)
memo[self] = newRef
newRef.simobj = simobj
assert(isSimObject(newRef.simobj))
if self.peer and not proxy.isproxy(self.peer):
peerObj = self.peer.simobj(_memo=memo)
newRef.peer = self.peer.clone(peerObj, memo)
assert(not isinstance(newRef.peer, VectorPortRef))
return newRef
def unproxy(self, simobj):
assert(simobj is self.simobj)
if proxy.isproxy(self.peer):
try:
realPeer = self.peer.unproxy(self.simobj)
except:
print "Error in unproxying port '%s' of %s" % \
(self.name, self.simobj.path())
raise
self.connect(realPeer)
# Call C++ to create corresponding port connection between C++ objects
def ccConnect(self):
from m5.internal.pyobject import connectPorts
if self.role == 'SLAVE':
# do nothing and let the master take care of it
return
if self.ccConnected: # already done this
return
peer = self.peer
if not self.peer: # nothing to connect to
return
# check that we connect a master to a slave
if self.role == peer.role:
raise TypeError, \
"cannot connect '%s' and '%s' due to identical role '%s'" \
% (peer, self, self.role)
try:
# self is always the master and peer the slave
connectPorts(self.simobj.getCCObject(), self.name, self.index,
peer.simobj.getCCObject(), peer.name, peer.index)
except:
print "Error connecting port %s.%s to %s.%s" % \
(self.simobj.path(), self.name,
peer.simobj.path(), peer.name)
raise
self.ccConnected = True
peer.ccConnected = True
# A reference to an individual element of a VectorPort... much like a
# PortRef, but has an index.
class VectorPortElementRef(PortRef):
def __init__(self, simobj, name, role, index):
PortRef.__init__(self, simobj, name, role)
self.index = index
def __str__(self):
return '%s.%s[%d]' % (self.simobj, self.name, self.index)
# A reference to a complete vector-valued port (not just a single element).
# Can be indexed to retrieve individual VectorPortElementRef instances.
class VectorPortRef(object):
def __init__(self, simobj, name, role):
assert(isSimObject(simobj) or isSimObjectClass(simobj))
self.simobj = simobj
self.name = name
self.role = role
self.elements = []
def __str__(self):
return '%s.%s[:]' % (self.simobj, self.name)
def __len__(self):
# Return the number of connected peers, corresponding the the
# length of the elements.
return len(self.elements)
# for config.ini, print peer's name (not ours)
def ini_str(self):
return ' '.join([el.ini_str() for el in self.elements])
# for config.json
def get_config_as_dict(self):
return {'role' : self.role,
'peer' : [el.ini_str() for el in self.elements]}
def __getitem__(self, key):
if not isinstance(key, int):
raise TypeError, "VectorPort index must be integer"
if key >= len(self.elements):
# need to extend list
ext = [VectorPortElementRef(self.simobj, self.name, self.role, i)
for i in range(len(self.elements), key+1)]
self.elements.extend(ext)
return self.elements[key]
def _get_next(self):
return self[len(self.elements)]
def __setitem__(self, key, value):
if not isinstance(key, int):
raise TypeError, "VectorPort index must be integer"
self[key].connect(value)
def connect(self, other):
if isinstance(other, (list, tuple)):
# Assign list of port refs to vector port.
# For now, append them... not sure if that's the right semantics
# or if it should replace the current vector.
for ref in other:
self._get_next().connect(ref)
else:
# scalar assignment to plain VectorPort is implicit append
self._get_next().connect(other)
def clone(self, simobj, memo):
if memo.has_key(self):
return memo[self]
newRef = copy.copy(self)
memo[self] = newRef
newRef.simobj = simobj
assert(isSimObject(newRef.simobj))
newRef.elements = [el.clone(simobj, memo) for el in self.elements]
return newRef
def unproxy(self, simobj):
[el.unproxy(simobj) for el in self.elements]
def ccConnect(self):
[el.ccConnect() for el in self.elements]
# Port description object. Like a ParamDesc object, this represents a
# logical port in the SimObject class, not a particular port on a
# SimObject instance. The latter are represented by PortRef objects.
class Port(object):
# Generate a PortRef for this port on the given SimObject with the
# given name
def makeRef(self, simobj):
return PortRef(simobj, self.name, self.role)
# Connect an instance of this port (on the given SimObject with
# the given name) with the port described by the supplied PortRef
def connect(self, simobj, ref):
self.makeRef(simobj).connect(ref)
# No need for any pre-declarations at the moment as we merely rely
# on an unsigned int.
def cxx_predecls(self, code):
pass
# Declare an unsigned int with the same name as the port, that
# will eventually hold the number of connected ports (and thus the
# number of elements for a VectorPort).
def cxx_decl(self, code):
code('unsigned int port_${{self.name}}_connection_count;')
class MasterPort(Port):
# MasterPort("description")
def __init__(self, *args):
if len(args) == 1:
self.desc = args[0]
self.role = 'MASTER'
else:
raise TypeError, 'wrong number of arguments'
class SlavePort(Port):
# SlavePort("description")
def __init__(self, *args):
if len(args) == 1:
self.desc = args[0]
self.role = 'SLAVE'
else:
raise TypeError, 'wrong number of arguments'
# VectorPort description object. Like Port, but represents a vector
# of connections (e.g., as on a Bus).
class VectorPort(Port):
def __init__(self, *args):
self.isVec = True
def makeRef(self, simobj):
return VectorPortRef(simobj, self.name, self.role)
class VectorMasterPort(VectorPort):
# VectorMasterPort("description")
def __init__(self, *args):
if len(args) == 1:
self.desc = args[0]
self.role = 'MASTER'
VectorPort.__init__(self, *args)
else:
raise TypeError, 'wrong number of arguments'
class VectorSlavePort(VectorPort):
# VectorSlavePort("description")
def __init__(self, *args):
if len(args) == 1:
self.desc = args[0]
self.role = 'SLAVE'
VectorPort.__init__(self, *args)
else:
raise TypeError, 'wrong number of arguments'
# 'Fake' ParamDesc for Port references to assign to the _pdesc slot of
# proxy objects (via set_param_desc()) so that proxy error messages
# make sense.
class PortParamDesc(object):
__metaclass__ = Singleton
ptype_str = 'Port'
ptype = Port
baseEnums = allEnums.copy()
baseParams = allParams.copy()
def clear():
global allEnums, allParams
allEnums = baseEnums.copy()
allParams = baseParams.copy()
__all__ = ['Param', 'VectorParam',
'Enum', 'Bool', 'String', 'Float',
'Int', 'Unsigned', 'Int8', 'UInt8', 'Int16', 'UInt16',
'Int32', 'UInt32', 'Int64', 'UInt64',
'Counter', 'Addr', 'Tick', 'Percent',
'TcpPort', 'UdpPort', 'EthernetAddr',
'IpAddress', 'IpNetmask', 'IpWithPort',
'MemorySize', 'MemorySize32',
'Latency', 'Frequency', 'Clock', 'Voltage',
'NetworkBandwidth', 'MemoryBandwidth',
'AddrRange',
'MaxAddr', 'MaxTick', 'AllMemory',
'Time',
'NextEthernetAddr', 'NULL',
'MasterPort', 'SlavePort',
'VectorMasterPort', 'VectorSlavePort']
import SimObject
|
haowu4682/gem5
|
src/python/m5/params.py
|
Python
|
bsd-3-clause
| 53,864
|
# IDLSave - a python module to read IDL 'save' files
# Copyright (c) 2010 Thomas P. Robitaille
# Many thanks to Craig Markwardt for publishing the Unofficial Format
# Specification for IDL .sav files, without which this Python module would not
# exist (http://cow.physics.wisc.edu/~craigm/idl/savefmt).
# This code was developed by with permission from ITT Visual Information
# Systems. IDL(r) is a registered trademark of ITT Visual Information Systems,
# Inc. for their Interactive Data Language software.
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
import struct
import numpy as np
from numpy.compat import asbytes, asstr
import tempfile
import zlib
import warnings
# Define the different data types that can be found in an IDL save file
DTYPE_DICT = {}
DTYPE_DICT[1] = '>u1'
DTYPE_DICT[2] = '>i2'
DTYPE_DICT[3] = '>i4'
DTYPE_DICT[4] = '>f4'
DTYPE_DICT[5] = '>f8'
DTYPE_DICT[6] = '>c8'
DTYPE_DICT[7] = '|O'
DTYPE_DICT[8] = '|O'
DTYPE_DICT[9] = '>c16'
DTYPE_DICT[12] = '>u2'
DTYPE_DICT[13] = '>u4'
DTYPE_DICT[14] = '>i8'
DTYPE_DICT[15] = '>u8'
# Define the different record types that can be found in an IDL save file
RECTYPE_DICT = {}
RECTYPE_DICT[0] = "START_MARKER"
RECTYPE_DICT[1] = "COMMON_VARIABLE"
RECTYPE_DICT[2] = "VARIABLE"
RECTYPE_DICT[3] = "SYSTEM_VARIABLE"
RECTYPE_DICT[6] = "END_MARKER"
RECTYPE_DICT[10] = "TIMESTAMP"
RECTYPE_DICT[12] = "COMPILED"
RECTYPE_DICT[13] = "IDENTIFICATION"
RECTYPE_DICT[14] = "VERSION"
RECTYPE_DICT[15] = "HEAP_HEADER"
RECTYPE_DICT[16] = "HEAP_DATA"
RECTYPE_DICT[17] = "PROMOTE64"
RECTYPE_DICT[19] = "NOTICE"
# Define a dictionary to contain structure definitions
STRUCT_DICT = {}
def _align_32(f):
'''Align to the next 32-bit position in a file'''
pos = f.tell()
if pos % 4 <> 0:
f.seek(pos + 4 - pos % 4)
return
def _skip_bytes(f, n):
'''Skip `n` bytes'''
f.read(n)
return
def _read_bytes(f, n):
'''Read the next `n` bytes'''
return f.read(n)
def _read_byte(f):
'''Read a single byte'''
return np.uint8(struct.unpack('>B', f.read(4)[:1])[0])
def _read_long(f):
'''Read a signed 32-bit integer'''
return np.int32(struct.unpack('>l', f.read(4))[0])
def _read_int16(f):
'''Read a signed 16-bit integer'''
return np.int16(struct.unpack('>h', f.read(4)[2:4])[0])
def _read_int32(f):
'''Read a signed 32-bit integer'''
return np.int32(struct.unpack('>i', f.read(4))[0])
def _read_int64(f):
'''Read a signed 64-bit integer'''
return np.int64(struct.unpack('>q', f.read(8))[0])
def _read_uint16(f):
'''Read an unsigned 16-bit integer'''
return np.uint16(struct.unpack('>H', f.read(4)[2:4])[0])
def _read_uint32(f):
'''Read an unsigned 32-bit integer'''
return np.uint32(struct.unpack('>I', f.read(4))[0])
def _read_uint64(f):
'''Read an unsigned 64-bit integer'''
return np.uint64(struct.unpack('>Q', f.read(8))[0])
def _read_float32(f):
'''Read a 32-bit float'''
return np.float32(struct.unpack('>f', f.read(4))[0])
def _read_float64(f):
'''Read a 64-bit float'''
return np.float64(struct.unpack('>d', f.read(8))[0])
class Pointer(object):
'''Class used to define pointers'''
def __init__(self, index):
self.index = index
return
def _read_string(f):
'''Read a string'''
length = _read_long(f)
if length > 0:
chars = _read_bytes(f, length)
_align_32(f)
chars = asstr(chars)
else:
chars = None
return chars
def _read_string_data(f):
'''Read a data string (length is specified twice)'''
length = _read_long(f)
if length > 0:
length = _read_long(f)
string = _read_bytes(f, length)
_align_32(f)
else:
string = None
return string
def _read_data(f, dtype):
'''Read a variable with a specified data type'''
if dtype==1:
if _read_int32(f) <> 1:
raise Exception("Error occurred while reading byte variable")
return _read_byte(f)
elif dtype==2:
return _read_int16(f)
elif dtype==3:
return _read_int32(f)
elif dtype==4:
return _read_float32(f)
elif dtype==5:
return _read_float64(f)
elif dtype==6:
real = _read_float32(f)
imag = _read_float32(f)
return np.complex64(real + imag * 1j)
elif dtype==7:
return _read_string_data(f)
elif dtype==8:
raise Exception("Should not be here - please report this")
elif dtype==9:
real = _read_float64(f)
imag = _read_float64(f)
return np.complex128(real + imag * 1j)
elif dtype==10:
return Pointer(_read_int32(f))
elif dtype==11:
raise Exception("Object reference type not implemented")
elif dtype==12:
return _read_uint16(f)
elif dtype==13:
return _read_uint32(f)
elif dtype==14:
return _read_int64(f)
elif dtype==15:
return _read_uint64(f)
else:
raise Exception("Unknown IDL type: %i - please report this" % dtype)
def _read_structure(f, array_desc, struct_desc):
'''
Read a structure, with the array and structure descriptors given as
`array_desc` and `structure_desc` respectively.
'''
nrows = array_desc['nelements']
ncols = struct_desc['ntags']
columns = struct_desc['tagtable']
dtype = []
for col in columns:
if col['structure'] or col['array']:
dtype.append(((col['name'].lower(), col['name']), np.object_))
else:
if col['typecode'] in DTYPE_DICT:
dtype.append(((col['name'].lower(), col['name']),
DTYPE_DICT[col['typecode']]))
else:
raise Exception("Variable type %i not implemented" %
col['typecode'])
structure = np.recarray((nrows, ), dtype=dtype)
for i in range(nrows):
for col in columns:
dtype = col['typecode']
if col['structure']:
structure[col['name']][i] = _read_structure(f, \
struct_desc['arrtable'][col['name']], \
struct_desc['structtable'][col['name']])
elif col['array']:
structure[col['name']][i] = _read_array(f, dtype, \
struct_desc['arrtable'][col['name']])
else:
structure[col['name']][i] = _read_data(f, dtype)
return structure
def _read_array(f, typecode, array_desc):
'''
Read an array of type `typecode`, with the array descriptor given as
`array_desc`.
'''
if typecode in [1, 3, 4, 5, 6, 9, 13, 14, 15]:
if typecode == 1:
nbytes = _read_int32(f)
if nbytes <> array_desc['nbytes']:
raise Exception("Error occurred while reading byte array")
# Read bytes as numpy array
array = np.fromstring(f.read(array_desc['nbytes']), \
dtype=DTYPE_DICT[typecode])
elif typecode in [2, 12]:
# These are 2 byte types, need to skip every two as they are not packed
array = np.fromstring(f.read(array_desc['nbytes']*2), \
dtype=DTYPE_DICT[typecode])[1::2]
else:
# Read bytes into list
array = []
for i in range(array_desc['nelements']):
dtype = typecode
data = _read_data(f, dtype)
array.append(data)
array = np.array(array, dtype=np.object_)
# Reshape array if needed
if array_desc['ndims'] > 1:
dims = array_desc['dims'][:int(array_desc['ndims'])]
dims.reverse()
array = array.reshape(dims)
# Go to next alignment position
_align_32(f)
return array
def _read_record(f):
'''Function to read in a full record'''
record = {}
recpos = f.tell()
record['rectype'] = _read_long(f)
nextrec = _read_uint32(f)
nextrec += _read_uint32(f) * 2**32
_skip_bytes(f, 4)
if not record['rectype'] in RECTYPE_DICT:
raise Exception("Unknown RECTYPE: %i" % record['rectype'])
record['rectype'] = RECTYPE_DICT[record['rectype']]
if record['rectype'] in ["VARIABLE", "HEAP_DATA"]:
if record['rectype'] == "VARIABLE":
record['varname'] = _read_string(f)
else:
record['heap_index'] = _read_long(f)
_skip_bytes(f, 4)
rectypedesc = _read_typedesc(f)
varstart = _read_long(f)
if varstart <> 7:
raise Exception("VARSTART is not 7")
if rectypedesc['structure']:
record['data'] = _read_structure(f, rectypedesc['array_desc'], \
rectypedesc['struct_desc'])
elif rectypedesc['array']:
record['data'] = _read_array(f, rectypedesc['typecode'], \
rectypedesc['array_desc'])
else:
dtype = rectypedesc['typecode']
record['data'] = _read_data(f, dtype)
elif record['rectype'] == "TIMESTAMP":
_skip_bytes(f, 4*256)
record['date'] = _read_string(f)
record['user'] = _read_string(f)
record['host'] = _read_string(f)
elif record['rectype'] == "VERSION":
record['format'] = _read_long(f)
record['arch'] = _read_string(f)
record['os'] = _read_string(f)
record['release'] = _read_string(f)
elif record['rectype'] == "IDENTIFICATON":
record['author'] = _read_string(f)
record['title'] = _read_string(f)
record['idcode'] = _read_string(f)
elif record['rectype'] == "NOTICE":
record['notice'] = _read_string(f)
elif record['rectype'] == "HEAP_HEADER":
record['nvalues'] = _read_long(f)
record['indices'] = []
for i in range(record['nvalues']):
record['indices'].append(_read_long(f))
elif record['rectype'] == "COMMONBLOCK":
record['nvars'] = _read_long(f)
record['name'] = _read_string(f)
record['varnames'] = []
for i in range(record['nvars']):
record['varnames'].append(_read_string(f))
elif record['rectype'] == "END_MARKER":
record['end'] = True
elif record['rectype'] == "UNKNOWN":
warnings.warn("Skipping UNKNOWN record")
elif record['rectype'] == "SYSTEM_VARIABLE":
warnings.warn("Skipping SYSTEM_VARIABLE record")
else:
raise Exception("record['rectype']=%s not implemented" % \
record['rectype'])
f.seek(nextrec)
return record
def _read_typedesc(f):
'''Function to read in a type descriptor'''
typedesc = {}
typedesc['typecode'] = _read_long(f)
typedesc['varflags'] = _read_long(f)
if typedesc['varflags'] & 2 == 2:
raise Exception("System variables not implemented")
typedesc['array'] = typedesc['varflags'] & 4 == 4
typedesc['structure'] = typedesc['varflags'] & 32 == 32
if typedesc['structure']:
typedesc['array_desc'] = _read_arraydesc(f)
typedesc['struct_desc'] = _read_structdesc(f)
elif typedesc['array']:
typedesc['array_desc'] = _read_arraydesc(f)
return typedesc
def _read_arraydesc(f):
'''Function to read in an array descriptor'''
arraydesc = {}
arraydesc['arrstart'] = _read_long(f)
if arraydesc['arrstart'] == 8:
_skip_bytes(f, 4)
arraydesc['nbytes'] = _read_long(f)
arraydesc['nelements'] = _read_long(f)
arraydesc['ndims'] = _read_long(f)
_skip_bytes(f, 8)
arraydesc['nmax'] = _read_long(f)
arraydesc['dims'] = []
for d in range(arraydesc['nmax']):
arraydesc['dims'].append(_read_long(f))
elif arraydesc['arrstart'] == 18:
warnings.warn("Using experimental 64-bit array read")
_skip_bytes(f, 8)
arraydesc['nbytes'] = _read_uint64(f)
arraydesc['nelements'] = _read_uint64(f)
arraydesc['ndims'] = _read_long(f)
_skip_bytes(f, 8)
arraydesc['nmax'] = 8
arraydesc['dims'] = []
for d in range(arraydesc['nmax']):
v = _read_long(f)
if v <> 0:
raise Exception("Expected a zero in ARRAY_DESC")
arraydesc['dims'].append(_read_long(f))
else:
raise Exception("Unknown ARRSTART: %i" % arraydesc['arrstart'])
return arraydesc
def _read_structdesc(f):
'''Function to read in a structure descriptor'''
structdesc = {}
structstart = _read_long(f)
if structstart <> 9:
raise Exception("STRUCTSTART should be 9")
structdesc['name'] = _read_string(f)
structdesc['predef'] = _read_long(f)
structdesc['ntags'] = _read_long(f)
structdesc['nbytes'] = _read_long(f)
if structdesc['predef'] & 1 == 0:
structdesc['tagtable'] = []
for t in range(structdesc['ntags']):
structdesc['tagtable'].append(_read_tagdesc(f))
for tag in structdesc['tagtable']:
tag['name'] = _read_string(f)
structdesc['arrtable'] = {}
for tag in structdesc['tagtable']:
if tag['array']:
structdesc['arrtable'][tag['name']] = _read_arraydesc(f)
structdesc['structtable'] = {}
for tag in structdesc['tagtable']:
if tag['structure']:
structdesc['structtable'][tag['name']] = _read_structdesc(f)
STRUCT_DICT[structdesc['name']] = (structdesc['tagtable'], \
structdesc['arrtable'], \
structdesc['structtable'])
else:
if not structdesc['name'] in STRUCT_DICT:
raise Exception("PREDEF=1 but can't find definition")
structdesc['tagtable'], \
structdesc['arrtable'], \
structdesc['structtable'] = STRUCT_DICT[structdesc['name']]
return structdesc
def _read_tagdesc(f):
'''Function to read in a tag descriptor'''
tagdesc = {}
tagdesc['offset'] = _read_long(f)
if tagdesc['offset'] == -1:
tagdesc['offset'] = _read_uint64(f)
tagdesc['typecode'] = _read_long(f)
tagflags = _read_long(f)
tagdesc['array'] = tagflags & 4 == 4
tagdesc['structure'] = tagflags & 32 == 32
tagdesc['scalar'] = tagdesc['typecode'] in DTYPE_DICT
# Assume '10'x is scalar
return tagdesc
class AttrDict(dict):
'''
A case-insensitive dictionary with access via item, attribute, and call
notations:
>>> d = AttrDict()
>>> d['Variable'] = 123
>>> d['Variable']
123
>>> d.Variable
123
>>> d.variable
123
>>> d('VARIABLE')
123
'''
def __init__(self, init={}):
dict.__init__(self, init)
def __getitem__(self, name):
return super(AttrDict, self).__getitem__(name.lower())
def __setitem__(self, key, value):
return super(AttrDict, self).__setitem__(key.lower(), value)
__getattr__ = __getitem__
__setattr__ = __setitem__
__call__ = __getitem__
def readsav(file_name, idict=None, python_dict=False,
uncompressed_file_name=None, verbose=False):
'''
Read an IDL .sav file
Parameters
----------
file_name : str
Name of the IDL save file.
idict : dict, optional
Dictionary in which to insert .sav file variables
python_dict: bool, optional
By default, the object return is not a Python dictionary, but a
case-insensitive dictionary with item, attribute, and call access
to variables. To get a standard Python dictionary, set this option
to True.
uncompressed_file_name : str, optional
This option only has an effect for .sav files written with the
/compress option. If a file name is specified, compressed .sav
files are uncompressed to this file. Otherwise, readsav will use
the `tempfile` module to determine a temporary filename
automatically, and will remove the temporary file upon successfully
reading it in.
verbose : bool, optional
Whether to print out information about the save file, including
the records read, and available variables.
Returns
----------
idl_dict : AttrDict or dict
If `python_dict` is set to False (default), this function returns a
case-insensitive dictionary with item, attribute, and call access
to variables. If `python_dict` is set to True, this function
returns a Python dictionary with all variable names in lowercase.
If `idict` was specified, then variables are written to the
dictionary specified, and the updated dictionary is returned.
'''
# Initialize record and variable holders
records = []
if python_dict or idict:
variables = {}
else:
variables = AttrDict()
# Open the IDL file
f = open(file_name, 'rb')
# Read the signature, which should be 'SR'
signature = _read_bytes(f, 2)
if signature <> asbytes('SR'):
raise Exception("Invalid SIGNATURE: %s" % signature)
# Next, the record format, which is '\x00\x04' for normal .sav
# files, and '\x00\x06' for compressed .sav files.
recfmt = _read_bytes(f, 2)
if recfmt == asbytes('\x00\x04'):
pass
elif recfmt == asbytes('\x00\x06'):
if verbose:
print "IDL Save file is compressed"
if uncompressed_file_name:
fout = open(uncompressed_file_name, 'w+b')
else:
fout = tempfile.NamedTemporaryFile(suffix='.sav')
if verbose:
print " -> expanding to %s" % fout.name
# Write header
fout.write(asbytes('SR\x00\x04'))
# Cycle through records
while True:
# Read record type
rectype = _read_long(f)
fout.write(struct.pack('>l', int(rectype)))
# Read position of next record and return as int
nextrec = _read_uint32(f)
nextrec += _read_uint32(f) * 2**32
# Read the unknown 4 bytes
unknown = f.read(4)
# Check if the end of the file has been reached
if RECTYPE_DICT[rectype] == 'END_MARKER':
fout.write(struct.pack('>I', int(nextrec) % 2**32))
fout.write(struct.pack('>I', int((nextrec - (nextrec % 2**32)) / 2**32)))
fout.write(unknown)
break
# Find current position
pos = f.tell()
# Decompress record
string = zlib.decompress(f.read(nextrec-pos))
# Find new position of next record
nextrec = fout.tell() + len(string) + 12
# Write out record
fout.write(struct.pack('>I', int(nextrec % 2**32)))
fout.write(struct.pack('>I', int((nextrec - (nextrec % 2**32)) / 2**32)))
fout.write(unknown)
fout.write(string)
# Close the original compressed file
f.close()
# Set f to be the decompressed file, and skip the first four bytes
f = fout
f.seek(4)
else:
raise Exception("Invalid RECFMT: %s" % recfmt)
# Loop through records, and add them to the list
while True:
r = _read_record(f)
records.append(r)
if 'end' in r:
if r['end']:
break
# Close the file
f.close()
# Find heap data variables
heap = {}
for r in records:
if r['rectype'] == "HEAP_DATA":
heap[r['heap_index']] = r['data']
# Find all variables
for r in records:
if r['rectype'] == "VARIABLE":
while isinstance(r['data'], Pointer):
r['data'] = heap[r['data'].index]
variables[r['varname'].lower()] = r['data']
if verbose:
# Print out timestamp info about the file
for record in records:
if record['rectype'] == "TIMESTAMP":
print "-"*50
print "Date: %s" % record['date']
print "User: %s" % record['user']
print "Host: %s" % record['host']
break
# Print out version info about the file
for record in records:
if record['rectype'] == "VERSION":
print "-"*50
print "Format: %s" % record['format']
print "Architecture: %s" % record['arch']
print "Operating System: %s" % record['os']
print "IDL Version: %s" % record['release']
break
# Print out identification info about the file
for record in records:
if record['rectype'] == "IDENTIFICATON":
print "-"*50
print "Author: %s" % record['author']
print "Title: %s" % record['title']
print "ID Code: %s" % record['idcode']
break
print "-"*50
print "Successfully read %i records of which:" % \
(len(records))
# Create convenience list of record types
rectypes = [r['rectype'] for r in records]
for rt in set(rectypes):
if rt <> 'END_MARKER':
print " - %i are of type %s" % (rectypes.count(rt), rt)
print "-"*50
if 'VARIABLE' in rectypes:
print "Available variables:"
for var in variables:
print " - %s [%s]" % (var, type(variables[var]))
print "-"*50
if idict:
for var in variables:
idict[var] = variables[var]
return idict
else:
return variables
|
lesserwhirls/scipy-cwt
|
scipy/io/idl.py
|
Python
|
bsd-3-clause
| 22,855
|
"""A functions module, includes all the standard functions.
Combinatorial - factorial, fibonacci, harmonic, bernoulli...
Elementary - hyperbolic, trigonometric, exponential, floor and ceiling, sqrt...
Special - gamma, zeta,spherical harmonics...
"""
from sympy.functions.combinatorial.factorials import (factorial, factorial2,
rf, ff, binomial, RisingFactorial, FallingFactorial, subfactorial)
from sympy.functions.combinatorial.numbers import (fibonacci, lucas, harmonic,
bernoulli, bell, euler, catalan)
from sympy.functions.elementary.miscellaneous import (sqrt, root, Min, Max,
Id, real_root, cbrt)
from sympy.functions.elementary.complexes import (re, im, sign, Abs,
conjugate, arg, polar_lift, periodic_argument, unbranched_argument,
principal_branch, transpose, adjoint)
from sympy.functions.elementary.trigonometric import (sin, cos, tan,
sec, csc, cot, asin, acos, atan, asec, acsc, acot, atan2)
from sympy.functions.elementary.exponential import (exp_polar, exp, log,
LambertW)
from sympy.functions.elementary.hyperbolic import (sinh, cosh, tanh, coth,
sech, csch, asinh, acosh, atanh, acoth)
from sympy.functions.elementary.integers import floor, ceiling
from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
from sympy.functions.special.error_functions import (erf, erfc, erfi, erf2,
erfinv, erfcinv, erf2inv, Ei, expint, E1, li, Li, Si, Ci, Shi, Chi,
fresnels, fresnelc)
from sympy.functions.special.gamma_functions import (gamma, lowergamma,
uppergamma, polygamma, loggamma, digamma, trigamma)
from sympy.functions.special.zeta_functions import (dirichlet_eta, zeta,
lerchphi, polylog)
from sympy.functions.special.tensor_functions import (Eijk, LeviCivita,
KroneckerDelta)
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
from sympy.functions.special.bsplines import bspline_basis, bspline_basis_set
from sympy.functions.special.bessel import (besselj, bessely, besseli, besselk,
hankel1, hankel2, jn, yn, jn_zeros, airyai, airybi, airyaiprime, airybiprime)
from sympy.functions.special.hyper import hyper, meijerg
from sympy.functions.special.polynomials import (legendre, assoc_legendre,
hermite, chebyshevt, chebyshevu, chebyshevu_root, chebyshevt_root,
laguerre, assoc_laguerre, gegenbauer, jacobi, jacobi_normalized)
from sympy.functions.special.spherical_harmonics import Ynm, Ynm_c, Znm
from sympy.functions.special.elliptic_integrals import (elliptic_k,
elliptic_f, elliptic_e, elliptic_pi)
from sympy.functions.special.beta_functions import beta
ln = log
|
beni55/sympy
|
sympy/functions/__init__.py
|
Python
|
bsd-3-clause
| 2,663
|
#!/usr/bin/env python
"""usage: %prog [options] filename
Parse a document to a tree, with optional profiling
"""
import sys
import os
import traceback
from optparse import OptionParser
from html5lib import html5parser, sanitizer
from html5lib.tokenizer import HTMLTokenizer
from html5lib import treebuilders, serializer, treewalkers
from html5lib import constants
from html5lib import utils
def parse():
optParser = getOptParser()
opts,args = optParser.parse_args()
encoding = 'utf8'
try:
f = args[-1]
# Try opening from the internet
if f.startswith('http://'):
try:
import urllib.request, urllib.parse, urllib.error, cgi
f = urllib.request.urlopen(f)
contentType = f.headers.get('content-type')
if contentType:
(mediaType, params) = cgi.parse_header(contentType)
encoding = params.get('charset')
except:
pass
elif f == '-':
f = sys.stdin
if sys.version_info[0] >= 3:
encoding = None
else:
try:
# Try opening from file system
f = open(f, 'rb')
except IOError as e:
sys.stderr.write('Unable to open file: %s\n' % e)
sys.exit(1)
except IndexError:
sys.stderr.write('No filename provided. Use -h for help\n')
sys.exit(1)
treebuilder = treebuilders.getTreeBuilder(opts.treebuilder)
if opts.sanitize:
tokenizer = sanitizer.HTMLSanitizer
else:
tokenizer = HTMLTokenizer
p = html5parser.HTMLParser(tree=treebuilder, tokenizer=tokenizer, debug=opts.log)
if opts.fragment:
parseMethod = p.parseFragment
else:
parseMethod = p.parse
if opts.profile:
import cProfile
import pstats
cProfile.runctx('run(parseMethod, f, encoding)', None,
{'run': run,
'parseMethod': parseMethod,
'f': f,
'encoding': encoding},
'stats.prof')
# XXX - We should use a temp file here
stats = pstats.Stats('stats.prof')
stats.strip_dirs()
stats.sort_stats('time')
stats.print_stats()
elif opts.time:
import time
t0 = time.time()
document = run(parseMethod, f, encoding)
t1 = time.time()
if document:
printOutput(p, document, opts)
t2 = time.time()
sys.stderr.write('\n\nRun took: %fs (plus %fs to print the output)'%(t1-t0, t2-t1))
else:
sys.stderr.write('\n\nRun took: %fs'%(t1-t0))
else:
document = run(parseMethod, f, encoding)
if document:
printOutput(p, document, opts)
def run(parseMethod, f, encoding):
try:
document = parseMethod(f, encoding=encoding)
except:
document = None
traceback.print_exc()
return document
def printOutput(parser, document, opts):
if opts.encoding:
print('Encoding:', parser.tokenizer.stream.charEncoding)
for item in parser.log:
print(item)
if document is not None:
if opts.xml:
tb = opts.treebuilder.lower()
if tb == 'dom':
document.writexml(sys.stdout, encoding='utf-8')
elif tb == 'lxml':
import lxml.etree
sys.stdout.write(lxml.etree.tostring(document))
elif tb == 'etree':
sys.stdout.write(utils.default_etree.tostring(document))
elif opts.tree:
if not hasattr(document,'__getitem__'):
document = [document]
for fragment in document:
print(parser.tree.testSerializer(fragment))
elif opts.hilite:
sys.stdout.write(document.hilite('utf-8'))
elif opts.html:
kwargs = {}
for opt in serializer.HTMLSerializer.options:
try:
kwargs[opt] = getattr(opts,opt)
except:
pass
if not kwargs['quote_char']:
del kwargs['quote_char']
tokens = treewalkers.getTreeWalker(opts.treebuilder)(document)
if sys.version_info[0] >= 3:
encoding = None
else:
encoding = 'utf-8'
for text in serializer.HTMLSerializer(**kwargs).serialize(tokens, encoding=encoding):
sys.stdout.write(text)
if not text.endswith('\n'): sys.stdout.write('\n')
if opts.error:
errList=[]
for pos, errorcode, datavars in parser.errors:
errList.append('Line %i Col %i'%pos + ' ' + constants.E.get(errorcode, 'Unknown error "%s"' % errorcode) % datavars)
sys.stdout.write('\nParse errors:\n' + '\n'.join(errList)+'\n')
def getOptParser():
parser = OptionParser(usage=__doc__)
parser.add_option('-p', '--profile', action='store_true', default=False,
dest='profile', help='Use the hotshot profiler to '
'produce a detailed log of the run')
parser.add_option('-t', '--time',
action='store_true', default=False, dest='time',
help='Time the run using time.time (may not be accurate on all platforms, especially for short runs)')
parser.add_option('-b', '--treebuilder', action='store', type='string',
dest='treebuilder', default='etree')
parser.add_option('-e', '--error', action='store_true', default=False,
dest='error', help='Print a list of parse errors')
parser.add_option('-f', '--fragment', action='store_true', default=False,
dest='fragment', help='Parse as a fragment')
parser.add_option('', '--tree', action='store_true', default=False,
dest='tree', help='Output as debug tree')
parser.add_option('-x', '--xml', action='store_true', default=False,
dest='xml', help='Output as xml')
parser.add_option('', '--no-html', action='store_false', default=True,
dest='html', help="Don't output html")
parser.add_option('', '--hilite', action='store_true', default=False,
dest='hilite', help='Output as formatted highlighted code.')
parser.add_option('-c', '--encoding', action='store_true', default=False,
dest='encoding', help='Print character encoding used')
parser.add_option('', '--inject-meta-charset', action='store_true',
default=False, dest='inject_meta_charset',
help='inject <meta charset>')
parser.add_option('', '--strip-whitespace', action='store_true',
default=False, dest='strip_whitespace',
help='strip whitespace')
parser.add_option('', '--omit-optional-tags', action='store_true',
default=False, dest='omit_optional_tags',
help='omit optional tags')
parser.add_option('', '--quote-attr-values', action='store_true',
default=False, dest='quote_attr_values',
help='quote attribute values')
parser.add_option('', '--use-best-quote-char', action='store_true',
default=False, dest='use_best_quote_char',
help='use best quote character')
parser.add_option('', '--quote-char', action='store',
default=None, dest='quote_char',
help='quote character')
parser.add_option('', '--no-minimize-boolean-attributes',
action='store_false', default=True,
dest='minimize_boolean_attributes',
help='minimize boolean attributes')
parser.add_option('', '--use-trailing-solidus', action='store_true',
default=False, dest='use_trailing_solidus',
help='use trailing solidus')
parser.add_option('', '--space-before-trailing-solidus',
action='store_true', default=False,
dest='space_before_trailing_solidus',
help='add space before trailing solidus')
parser.add_option('', '--escape-lt-in-attrs', action='store_true',
default=False, dest='escape_lt_in_attrs',
help='escape less than signs in attribute values')
parser.add_option('', '--escape-rcdata', action='store_true',
default=False, dest='escape_rcdata',
help='escape rcdata element values')
parser.add_option('', '--sanitize', action='store_true', default=False,
dest='sanitize', help='sanitize')
parser.add_option('-l', '--log', action='store_true', default=False,
dest='log', help='log state transitions')
return parser
if __name__ == '__main__':
parse()
|
lgp171188/fjord
|
vendor/src/html5lib-python/parse.py
|
Python
|
bsd-3-clause
| 9,103
|
__all__ = ['imread', 'imsave']
import numpy as np
from six import string_types
from PIL import Image
from ...util import img_as_ubyte, img_as_uint
from ...external.tifffile import imread as tif_imread, imsave as tif_imsave
def imread(fname, dtype=None, img_num=None, **kwargs):
"""Load an image from file.
Parameters
----------
fname : str
File name.
dtype : numpy dtype object or string specifier
Specifies data type of array elements.
img_num : int, optional
Specifies which image to read in a file with multiple images
(zero-indexed).
kwargs : keyword pairs, optional
Addition keyword arguments to pass through (only applicable to Tiff
files for now, see `tifffile`'s `imread` function).
Notes
-----
Tiff files are handled by Christophe Golhke's tifffile.py [1]_, and support many
advanced image types including multi-page and floating point.
All other files are read using the Python Imaging Libary.
See PIL docs [2]_ for a list of supported formats.
References
----------
.. [1] http://www.lfd.uci.edu/~gohlke/code/tifffile.py.html
.. [2] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html
"""
if hasattr(fname, 'lower') and dtype is None:
kwargs.setdefault('key', img_num)
if fname.lower().endswith(('.tiff', '.tif')):
return tif_imread(fname, **kwargs)
im = Image.open(fname)
try:
# this will raise an IOError if the file is not readable
im.getdata()[0]
except IOError as e:
site = "http://pillow.readthedocs.org/en/latest/installation.html#external-libraries"
pillow_error_message = str(e)
error_message = ('Could not load "%s" \n'
'Reason: "%s"\n'
'Please see documentation at: %s') % (fname, pillow_error_message, site)
raise ValueError(error_message)
else:
return pil_to_ndarray(im, dtype=dtype, img_num=img_num)
def pil_to_ndarray(im, dtype=None, img_num=None):
"""Import a PIL Image object to an ndarray, in memory.
Parameters
----------
Refer to ``imread``.
"""
frames = []
grayscale = None
i = 0
while 1:
try:
im.seek(i)
except EOFError:
break
frame = im
if img_num is not None and img_num != i:
im.getdata()[0]
i += 1
continue
if im.mode == 'P':
if grayscale is None:
grayscale = _palette_is_grayscale(im)
if grayscale:
frame = im.convert('L')
else:
frame = im.convert('RGB')
elif im.mode == '1':
frame = im.convert('L')
elif 'A' in im.mode:
frame = im.convert('RGBA')
elif im.mode == 'CMYK':
frame = im.convert('RGB')
if im.mode.startswith('I;16'):
shape = im.size
dtype = '>u2' if im.mode.endswith('B') else '<u2'
if 'S' in im.mode:
dtype = dtype.replace('u', 'i')
frame = np.fromstring(frame.tobytes(), dtype)
frame.shape = shape[::-1]
else:
frame = np.array(frame, dtype=dtype)
frames.append(frame)
i += 1
if img_num is not None:
break
if hasattr(im, 'fp') and im.fp:
im.fp.close()
if img_num is None and len(frames) > 1:
return np.array(frames)
elif frames:
return frames[0]
elif img_num:
raise IndexError('Could not find image #%s' % img_num)
def _palette_is_grayscale(pil_image):
"""Return True if PIL image in palette mode is grayscale.
Parameters
----------
pil_image : PIL image
PIL Image that is in Palette mode.
Returns
-------
is_grayscale : bool
True if all colors in image palette are gray.
"""
assert pil_image.mode == 'P'
# get palette as an array with R, G, B columns
palette = np.asarray(pil_image.getpalette()).reshape((256, 3))
# Not all palette colors are used; unused colors have junk values.
start, stop = pil_image.getextrema()
valid_palette = palette[start:stop]
# Image is grayscale if channel differences (R - G and G - B)
# are all zero.
return np.allclose(np.diff(valid_palette), 0)
def ndarray_to_pil(arr, format_str=None):
"""Export an ndarray to a PIL object.
Parameters
----------
Refer to ``imsave``.
"""
if arr.ndim == 3:
arr = img_as_ubyte(arr)
mode = {3: 'RGB', 4: 'RGBA'}[arr.shape[2]]
elif format_str in ['png', 'PNG']:
mode = 'I;16'
mode_base = 'I'
if arr.dtype.kind == 'f':
arr = img_as_uint(arr)
elif arr.max() < 256 and arr.min() >= 0:
arr = arr.astype(np.uint8)
mode = mode_base = 'L'
else:
arr = img_as_uint(arr)
else:
arr = img_as_ubyte(arr)
mode = 'L'
mode_base = 'L'
try:
array_buffer = arr.tobytes()
except AttributeError:
array_buffer = arr.tostring() # Numpy < 1.9
if arr.ndim == 2:
im = Image.new(mode_base, arr.T.shape)
try:
im.frombytes(array_buffer, 'raw', mode)
except AttributeError:
im.fromstring(array_buffer, 'raw', mode) # PIL 1.1.7
else:
image_shape = (arr.shape[1], arr.shape[0])
try:
im = Image.frombytes(mode, image_shape, array_buffer)
except AttributeError:
im = Image.fromstring(mode, image_shape, array_buffer) # PIL 1.1.7
return im
def imsave(fname, arr, format_str=None, **kwargs):
"""Save an image to disk.
Parameters
----------
fname : str or file-like object
Name of destination file.
arr : ndarray of uint8 or float
Array (image) to save. Arrays of data-type uint8 should have
values in [0, 255], whereas floating-point arrays must be
in [0, 1].
format_str: str
Format to save as, this is defaulted to PNG if using a file-like
object; this will be derived from the extension if fname is a string
kwargs: dict
Keyword arguments to the Pillow save function (or tifffile save
function, for Tiff files). These are format dependent. For example,
Pillow's JPEG save function supports an integer ``quality`` argument
with values in [1, 95], while TIFFFile supports a ``compress``
integer argument with values in [0, 9].
Notes
-----
Tiff files are handled by Christophe Golhke's tifffile.py [1]_,
and support many advanced image types including multi-page and
floating point.
All other image formats use the Python Imaging Libary.
See PIL docs [2]_ for a list of other supported formats.
All images besides single channel PNGs are converted using `img_as_uint8`.
Single Channel PNGs have the following behavior:
- Integer values in [0, 255] and Boolean types -> img_as_uint8
- Floating point and other integers -> img_as_uint16
References
----------
.. [1] http://www.lfd.uci.edu/~gohlke/code/tifffile.py.html
.. [2] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html
"""
# default to PNG if file-like object
if not isinstance(fname, string_types) and format_str is None:
format_str = "PNG"
# Check for png in filename
if (isinstance(fname, string_types)
and fname.lower().endswith(".png")):
format_str = "PNG"
arr = np.asanyarray(arr).squeeze()
if arr.dtype.kind == 'b':
arr = arr.astype(np.uint8)
use_tif = False
if hasattr(fname, 'lower'):
if fname.lower().endswith(('.tiff', '.tif')):
use_tif = True
if not format_str is None:
if format_str.lower() in ['tiff', 'tif']:
use_tif = True
if use_tif:
tif_imsave(fname, arr, **kwargs)
return
if arr.ndim not in (2, 3):
raise ValueError("Invalid shape for image array: %s" % arr.shape)
if arr.ndim == 3:
if arr.shape[2] not in (3, 4):
raise ValueError("Invalid number of channels in image array.")
img = ndarray_to_pil(arr, format_str=format_str)
img.save(fname, format=format_str, **kwargs)
|
Britefury/scikit-image
|
skimage/io/_plugins/pil_plugin.py
|
Python
|
bsd-3-clause
| 8,372
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""从汉典网(www.zdic.net)获取所有的汉字,找出拼音库未包含的汉字"""
import logging
from time import sleep
from bs4 import BeautifulSoup
import requests
logger = logging.getLogger(__name__)
def parse_words(html):
"""解析 html 源码,返回汉字列表"""
soup = BeautifulSoup(html)
a_list = soup.find_all('a', attrs={'target': '_blank'})
return [x.text for x in a_list if x.text]
def get_one_page(url, cookies, headers):
r = requests.get(url, headers=headers, cookies=cookies)
cookies.update(r.cookies.get_dict())
return r.text
def main():
import io
from pypinyin.pinyin_dict import pinyin_dict
headers = {
'Referer': 'http://www.zdic.net/z/jbs/zbh/',
'User-Agent': ('Mozilla/5.0 (Windows NT 6.2; rv:26.0) Gecko/20100101 '
'Firefox/26.0'),
}
url_base = 'http://www.zdic.net/z/jbs/zbh/bs/?jzbh=%s|%s'
cookies = requests.get('http://www.zdic.net/z/jbs/zbh/').cookies.get_dict()
word_list = []
timer = 5
for m in range(1, 66): # 总笔画数
sleep(timer)
for page_num in xrange(1, 10000): # 页数
url = url_base % (m, page_num)
logger.debug(url)
html = get_one_page(url, cookies=cookies, headers=headers)
words = parse_words(html)
if not words:
break
for word in words:
if word not in pinyin_dict:
logger.debug(repr(word))
word_list.append(word)
sleep(timer)
with io.open('words.txt', 'w', encoding='utf8') as f:
for word in word_list:
try:
f.write(word)
except Exception as e:
logger.debug(e + '\n' + repr(word))
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('requests').setLevel(logging.ERROR)
main()
|
wuxqing/python-pinyin
|
tools/get_words_from_zdic_by_bh.py
|
Python
|
mit
| 1,984
|
#!/usr/bin/env python2
"""Dump /arc/ppark.narc.
This is an unmaintained one-shot script, only included in the repo for
reference.
"""
import sys
from struct import pack, unpack
import binascii
import pokedex.db
from pokedex.db.tables import PalPark
types = [
'',
'grass',
'fire',
'water',
'bug',
'normal',
'poison',
'electric',
'ground',
'fighting',
'psychic',
'rock',
'ghost',
'ice',
'steel',
'dragon',
'dark',
'flying',
]
areas = {
1: 'forest',
2: 'mountain',
3: 'field',
0x200: 'pond',
0x400: 'sea',
}
session = pokedex.db.connect()()
with open(sys.argv[1], "rb") as f:
f.seek(0x3C)
for i in range(0xb8e // 6):
data = f.read(6)
area, score, rate, t1, t2 = unpack("<HBBBB", data)
print(i+1, binascii.hexlify(data).decode(),
areas[area], score, rate, types[t1], types[t2])
obj = PalPark()
obj.species_id = i+1
obj.area = areas[area]
obj.base_score = score
obj.rate = rate
session.add(obj)
session.commit()
|
DaMouse404/pokedex
|
scripts/palpark.py
|
Python
|
mit
| 1,113
|
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import sys
from nose.plugins.skip import SkipTest
if sys.version_info < (2, 7):
raise SkipTest("F5 Ansible modules require Python >= 2.7")
from ansible.module_utils.basic import AnsibleModule
try:
from library.modules.bigip_wait import Parameters
from library.modules.bigip_wait import ModuleManager
from library.modules.bigip_wait import ArgumentSpec
# In Ansible 2.8, Ansible changed import paths.
from test.units.compat import unittest
from test.units.compat.mock import Mock
from test.units.compat.mock import patch
from test.units.modules.utils import set_module_args
except ImportError:
try:
from ansible.modules.network.f5.bigip_wait import Parameters
from ansible.modules.network.f5.bigip_wait import ModuleManager
from ansible.modules.network.f5.bigip_wait import ArgumentSpec
# Ansible 2.8 imports
from units.compat import unittest
from units.compat.mock import Mock
from units.compat.mock import patch
from units.modules.utils import set_module_args
except ImportError:
raise SkipTest("F5 Ansible modules require the f5-sdk Python library")
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {}
def load_fixture(name):
path = os.path.join(fixture_path, name)
if path in fixture_data:
return fixture_data[path]
with open(path) as f:
data = f.read()
try:
data = json.loads(data)
except Exception:
pass
fixture_data[path] = data
return data
class TestParameters(unittest.TestCase):
def test_module_parameters(self):
args = dict(
delay=3,
timeout=500,
sleep=10,
msg='We timed out during waiting for BIG-IP :-('
)
p = Parameters(params=args)
assert p.delay == 3
assert p.timeout == 500
assert p.sleep == 10
assert p.msg == 'We timed out during waiting for BIG-IP :-('
def test_module_string_parameters(self):
args = dict(
delay='3',
timeout='500',
sleep='10',
msg='We timed out during waiting for BIG-IP :-('
)
p = Parameters(params=args)
assert p.delay == 3
assert p.timeout == 500
assert p.sleep == 10
assert p.msg == 'We timed out during waiting for BIG-IP :-('
class TestManager(unittest.TestCase):
def setUp(self):
self.spec = ArgumentSpec()
self.patcher1 = patch('time.sleep')
self.patcher1.start()
def tearDown(self):
self.patcher1.stop()
def test_wait_already_available(self, *args):
set_module_args(dict(
password='password',
server='localhost',
user='admin'
))
module = AnsibleModule(
argument_spec=self.spec.argument_spec,
supports_check_mode=self.spec.supports_check_mode
)
# Override methods to force specific logic in the module to happen
mm = ModuleManager(module=module)
mm._connect_to_device = Mock(return_value=True)
mm._device_is_rebooting = Mock(return_value=False)
mm._is_mprov_running_on_device = Mock(return_value=False)
mm._get_client_connection = Mock(return_value=True)
results = mm.exec_module()
assert results['changed'] is False
assert results['elapsed'] == 0
|
sgerhart/ansible
|
test/units/modules/network/f5/test_bigip_wait.py
|
Python
|
mit
| 3,721
|
#!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Test setting the YACCVCGFILESUFFIX variable.
"""
import TestSCons
_python_ = TestSCons._python_
test = TestSCons.TestSCons()
test.write('myyacc.py', """\
import getopt
import os.path
import sys
vcg = None
opts, args = getopt.getopt(sys.argv[1:], 'go:')
for o, a in opts:
if o == '-g':
vcg = 1
elif o == '-o':
outfile = open(a, 'wb')
for f in args:
infile = open(f, 'rb')
for l in [l for l in infile.readlines() if l != '/*yacc*/\\n']:
outfile.write(l)
outfile.close()
if vcg:
base, ext = os.path.splitext(args[0])
open(base+'.vcgsuffix', 'wb').write(" ".join(sys.argv)+'\\n')
sys.exit(0)
""")
test.write('SConstruct', """
env = Environment(tools=['default', 'yacc'],
YACC = r'%(_python_)s myyacc.py',
YACCVCGFILESUFFIX = '.vcgsuffix')
env.CXXFile(target = 'aaa', source = 'aaa.yy')
env.CXXFile(target = 'bbb', source = 'bbb.yy', YACCFLAGS = '-g')
""" % locals())
test.write('aaa.yy', "aaa.yy\n/*yacc*/\n")
test.write('bbb.yy', "bbb.yy\n/*yacc*/\n")
test.run(arguments = '.')
test.must_match('aaa.cc', "aaa.yy\n")
test.must_not_exist('aaa.vcg')
test.must_not_exist('aaa.vcgsuffix')
test.must_match('bbb.cc', "bbb.yy\n")
test.must_not_exist('bbb.vcg')
test.must_match('bbb.vcgsuffix', "myyacc.py -g -o bbb.cc bbb.yy\n")
test.up_to_date(arguments = '.')
test.pass_test()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|
timj/scons
|
test/YACC/YACCVCGFILESUFFIX.py
|
Python
|
mit
| 2,645
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import test_crm_activity
from . import test_crm_lead
from . import test_crm_lead_assignment
from . import test_crm_lead_notification
from . import test_crm_lead_convert
from . import test_crm_lead_convert_mass
from . import test_crm_lead_duplicates
from . import test_crm_lead_lost
from . import test_crm_lead_merge
from . import test_crm_lead_multicompany
from . import test_crm_lead_smart_calendar
from . import test_crm_ui
from . import test_crm_pls
from . import test_performances
|
jeremiahyan/odoo
|
addons/crm/tests/__init__.py
|
Python
|
gpl-3.0
| 592
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2012-today OpenERP s.a. (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
try:
import cStringIO as StringIO
except ImportError:
import StringIO
from PIL import Image
from PIL import ImageEnhance
from random import randint
# Preload PIL with the minimal subset of image formats we need
Image.preinit()
Image._initialized = 2
# ----------------------------------------
# Image resizing
# ----------------------------------------
def image_resize_image(base64_source, size=(1024, 1024), encoding='base64', filetype=None, avoid_if_small=False):
""" Function to resize an image. The image will be resized to the given
size, while keeping the aspect ratios, and holes in the image will be
filled with transparent background. The image will not be stretched if
smaller than the expected size.
Steps of the resizing:
- Compute width and height if not specified.
- if avoid_if_small: if both image sizes are smaller than the requested
sizes, the original image is returned. This is used to avoid adding
transparent content around images that we do not want to alter but
just resize if too big. This is used for example when storing images
in the 'image' field: we keep the original image, resized to a maximal
size, without adding transparent content around it if smaller.
- create a thumbnail of the source image through using the thumbnail
function. Aspect ratios are preserved when using it. Note that if the
source image is smaller than the expected size, it will not be
extended, but filled to match the size.
- create a transparent background that will hold the final image.
- paste the thumbnail on the transparent background and center it.
:param base64_source: base64-encoded version of the source
image; if False, returns False
:param size: 2-tuple(width, height). A None value for any of width or
height mean an automatically computed value based respectivelly
on height or width of the source image.
:param encoding: the output encoding
:param filetype: the output filetype, by default the source image's
:type filetype: str, any PIL image format (supported for creation)
:param avoid_if_small: do not resize if image height and width
are smaller than the expected size.
"""
if not base64_source:
return False
if size == (None, None):
return base64_source
image_stream = StringIO.StringIO(base64_source.decode(encoding))
image = Image.open(image_stream)
# store filetype here, as Image.new below will lose image.format
filetype = (filetype or image.format).upper()
filetype = {
'BMP': 'PNG',
}.get(filetype, filetype)
asked_width, asked_height = size
if asked_width is None:
asked_width = int(image.size[0] * (float(asked_height) / image.size[1]))
if asked_height is None:
asked_height = int(image.size[1] * (float(asked_width) / image.size[0]))
size = asked_width, asked_height
# check image size: do not create a thumbnail if avoiding smaller images
if avoid_if_small and image.size[0] <= size[0] and image.size[1] <= size[1]:
return base64_source
if image.size != size:
image = image_resize_and_sharpen(image, size)
if image.mode not in ["1", "L", "P", "RGB", "RGBA"]:
image = image.convert("RGB")
background_stream = StringIO.StringIO()
image.save(background_stream, filetype)
return background_stream.getvalue().encode(encoding)
def image_resize_and_sharpen(image, size, preserve_aspect_ratio=False, factor=2.0):
"""
Create a thumbnail by resizing while keeping ratio.
A sharpen filter is applied for a better looking result.
:param image: PIL.Image.Image()
:param size: 2-tuple(width, height)
:param preserve_aspect_ratio: boolean (default: False)
:param factor: Sharpen factor (default: 2.0)
"""
if image.mode != 'RGBA':
image = image.convert('RGBA')
image.thumbnail(size, Image.ANTIALIAS)
if preserve_aspect_ratio:
size = image.size
sharpener = ImageEnhance.Sharpness(image)
resized_image = sharpener.enhance(factor)
# create a transparent image for background and paste the image on it
image = Image.new('RGBA', size, (255, 255, 255, 0))
image.paste(resized_image, ((size[0] - resized_image.size[0]) / 2, (size[1] - resized_image.size[1]) / 2))
return image
def image_save_for_web(image, fp=None, format=None):
"""
Save image optimized for web usage.
:param image: PIL.Image.Image()
:param fp: File name or file object. If not specified, a bytestring is returned.
:param format: File format if could not be deduced from image.
"""
opt = dict(format=image.format or format)
if image.format == 'PNG':
opt.update(optimize=True)
alpha = False
if image.mode in ('RGBA', 'LA') or (image.mode == 'P' and 'transparency' in image.info):
alpha = image.convert('RGBA').split()[-1]
if image.mode != 'P':
# Floyd Steinberg dithering by default
image = image.convert('RGBA').convert('P', palette=Image.WEB, colors=256)
if alpha:
image.putalpha(alpha)
elif image.format == 'JPEG':
opt.update(optimize=True, quality=80)
if fp:
image.save(fp, **opt)
else:
img = StringIO.StringIO()
image.save(img, **opt)
return img.getvalue()
def image_resize_image_big(base64_source, size=(1024, 1024), encoding='base64', filetype=None, avoid_if_small=True):
""" Wrapper on image_resize_image, to resize images larger than the standard
'big' image size: 1024x1024px.
:param size, encoding, filetype, avoid_if_small: refer to image_resize_image
"""
return image_resize_image(base64_source, size, encoding, filetype, avoid_if_small)
def image_resize_image_medium(base64_source, size=(128, 128), encoding='base64', filetype=None, avoid_if_small=False):
""" Wrapper on image_resize_image, to resize to the standard 'medium'
image size: 180x180.
:param size, encoding, filetype, avoid_if_small: refer to image_resize_image
"""
return image_resize_image(base64_source, size, encoding, filetype, avoid_if_small)
def image_resize_image_small(base64_source, size=(64, 64), encoding='base64', filetype=None, avoid_if_small=False):
""" Wrapper on image_resize_image, to resize to the standard 'small' image
size: 50x50.
:param size, encoding, filetype, avoid_if_small: refer to image_resize_image
"""
return image_resize_image(base64_source, size, encoding, filetype, avoid_if_small)
# ----------------------------------------
# Colors
# ---------------------------------------
def image_colorize(original, randomize=True, color=(255, 255, 255)):
""" Add a color to the transparent background of an image.
:param original: file object on the original image file
:param randomize: randomize the background color
:param color: background-color, if not randomize
"""
# create a new image, based on the original one
original = Image.open(StringIO.StringIO(original))
image = Image.new('RGB', original.size)
# generate the background color, past it as background
if randomize:
color = (randint(32, 224), randint(32, 224), randint(32, 224))
image.paste(color, box=(0, 0) + original.size)
image.paste(original, mask=original)
# return the new image
buffer = StringIO.StringIO()
image.save(buffer, 'PNG')
return buffer.getvalue()
# ----------------------------------------
# Misc image tools
# ---------------------------------------
def image_get_resized_images(base64_source, return_big=False, return_medium=True, return_small=True,
big_name='image', medium_name='image_medium', small_name='image_small',
avoid_resize_big=True, avoid_resize_medium=False, avoid_resize_small=False):
""" Standard tool function that returns a dictionary containing the
big, medium and small versions of the source image. This function
is meant to be used for the methods of functional fields for
models using images.
Default parameters are given to be used for the getter of functional
image fields, for example with res.users or res.partner. It returns
only image_medium and image_small values, to update those fields.
:param base64_source: base64-encoded version of the source
image; if False, all returnes values will be False
:param return_{..}: if set, computes and return the related resizing
of the image
:param {..}_name: key of the resized image in the return dictionary;
'image', 'image_medium' and 'image_small' by default.
:param avoid_resize_[..]: see avoid_if_small parameter
:return return_dict: dictionary with resized images, depending on
previous parameters.
"""
return_dict = dict()
if return_big:
return_dict[big_name] = image_resize_image_big(base64_source, avoid_if_small=avoid_resize_big)
if return_medium:
return_dict[medium_name] = image_resize_image_medium(base64_source, avoid_if_small=avoid_resize_medium)
if return_small:
return_dict[small_name] = image_resize_image_small(base64_source, avoid_if_small=avoid_resize_small)
return return_dict
if __name__=="__main__":
import sys
assert len(sys.argv)==3, 'Usage to Test: image.py SRC.png DEST.png'
img = file(sys.argv[1],'rb').read().encode('base64')
new = image_resize_image(img, (128,100))
file(sys.argv[2], 'wb').write(new.decode('base64'))
|
galtys/odoo
|
openerp/tools/image.py
|
Python
|
agpl-3.0
| 10,791
|
"""
Tests for the API functions in the credit app.
"""
import datetime
import json
import ddt
import httpretty
import mock
import pytz
import six
from django.contrib.auth.models import User
from django.core import mail
from django.db import connection
from django.test.utils import override_settings
from opaque_keys.edx.keys import CourseKey
from course_modes.models import CourseMode
from lms.djangoapps.commerce.tests import TEST_API_URL
from openedx.core.djangoapps.credit import api
from openedx.core.djangoapps.credit.email_utils import get_credit_provider_attribute_values, make_providers_strings
from openedx.core.djangoapps.credit.exceptions import (
CreditRequestNotFound,
InvalidCreditCourse,
InvalidCreditRequirements,
InvalidCreditStatus,
RequestAlreadyCompleted,
UserIsNotEligible
)
from openedx.core.djangoapps.credit.models import (
CreditConfig,
CreditCourse,
CreditEligibility,
CreditProvider,
CreditRequest,
CreditRequirement,
CreditRequirementStatus
)
from openedx.core.djangolib.testing.utils import skip_unless_lms
from student.models import CourseEnrollment
from student.tests.factories import UserFactory
from util.date_utils import from_timestamp
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
TEST_CREDIT_PROVIDER_SECRET_KEY = "931433d583c84ca7ba41784bad3232e6"
TEST_ECOMMERCE_WORKER = 'test_worker'
@override_settings(CREDIT_PROVIDER_SECRET_KEYS={
"hogwarts": TEST_CREDIT_PROVIDER_SECRET_KEY,
"ASU": TEST_CREDIT_PROVIDER_SECRET_KEY,
"MIT": TEST_CREDIT_PROVIDER_SECRET_KEY
})
class CreditApiTestBase(ModuleStoreTestCase):
"""
Base class for test cases of the credit API.
"""
ENABLED_CACHES = ['default', 'mongo_metadata_inheritance', 'loc_cache']
PROVIDER_ID = "hogwarts"
PROVIDER_NAME = "Hogwarts School of Witchcraft and Wizardry"
PROVIDER_URL = "https://credit.example.com/request"
PROVIDER_STATUS_URL = "https://credit.example.com/status"
PROVIDER_DESCRIPTION = "A new model for the Witchcraft and Wizardry School System."
ENABLE_INTEGRATION = True
FULFILLMENT_INSTRUCTIONS = "Sample fulfillment instruction for credit completion."
USER_INFO = {
"username": "bob",
"email": "bob@example.com",
"password": "test_bob",
"full_name": "Bob",
"mailing_address": "123 Fake Street, Cambridge MA",
"country": "US",
}
THUMBNAIL_URL = "https://credit.example.com/logo.png"
PROVIDERS_LIST = [u'Hogwarts School of Witchcraft and Wizardry', u'Arizona State University']
COURSE_API_RESPONSE = {
"id": "course-v1:Demo+Demox+Course",
"url": "http://localhost/api/v2/courses/course-v1:Demo+Demox+Course/",
"name": "dummy edX Demonstration Course",
"verification_deadline": "2023-09-12T23:59:00Z",
"type": "credit",
"products_url": "http://localhost/api/v2/courses/course:Demo+Demox+Course/products/",
"last_edited": "2016-03-06T09:51:10Z",
"products": [
{
"id": 1,
"url": "http://localhost/api/v2/products/11/",
"structure": "child",
"product_class": "Seat",
"title": "",
"price": 1,
"expires": '2016-03-06T09:51:10Z',
"attribute_values": [
{
"name": "certificate_type",
"value": "credit"
},
{
"name": "course_key",
"value": "edX/DemoX/Demo_Course",
},
{
"name": "credit_hours",
"value": 1
},
{
"name": "credit_provider",
"value": "ASU"
},
{
"name": "id_verification_required",
"value": False
}
],
"is_available_to_buy": False,
"stockrecords": []
},
{
"id": 2,
"url": "http://localhost/api/v2/products/10/",
"structure": "child",
"product_class": "Seat",
"title": "",
"price": 1,
"expires": '2016-03-06T09:51:10Z',
"attribute_values": [
{
"name": "certificate_type",
"value": "credit"
},
{
"name": "course_key",
"value": "edX/DemoX/Demo_Course",
},
{
"name": "credit_hours",
"value": 1
},
{
"name": "credit_provider",
"value": PROVIDER_ID
},
{
"name": "id_verification_required",
"value": False
}
],
"is_available_to_buy": False,
"stockrecords": []
}
]
}
def setUp(self):
super(CreditApiTestBase, self).setUp()
self.course = CourseFactory.create(org="edx", course="DemoX", run="Demo_Course")
self.course_key = self.course.id
def add_credit_course(self, course_key=None, enabled=True):
"""Mark the course as a credit """
course_key = course_key or self.course_key
credit_course = CreditCourse.objects.create(course_key=course_key, enabled=enabled)
CreditProvider.objects.get_or_create(
provider_id=self.PROVIDER_ID,
display_name=self.PROVIDER_NAME,
provider_url=self.PROVIDER_URL,
provider_status_url=self.PROVIDER_STATUS_URL,
provider_description=self.PROVIDER_DESCRIPTION,
enable_integration=self.ENABLE_INTEGRATION,
fulfillment_instructions=self.FULFILLMENT_INSTRUCTIONS,
thumbnail_url=self.THUMBNAIL_URL
)
return credit_course
def create_and_enroll_user(self, username, password, course_id=None, mode=CourseMode.VERIFIED):
""" Create and enroll the user in the given course's and given mode."""
if course_id is None:
course_id = self.course_key
user = UserFactory.create(username=username, password=password)
self.enroll(user, course_id, mode)
return user
def enroll(self, user, course_id, mode):
"""Enroll user in given course and mode"""
return CourseEnrollment.enroll(user, course_id, mode=mode)
def _mock_ecommerce_courses_api(self, course_key, body, status=200):
""" Mock GET requests to the ecommerce course API endpoint. """
httpretty.reset()
httpretty.register_uri(
httpretty.GET, '{}/courses/{}/?include_products=1'.format(TEST_API_URL, six.text_type(course_key)),
status=status,
body=json.dumps(body), content_type='application/json',
)
@skip_unless_lms
@ddt.ddt
class CreditRequirementApiTests(CreditApiTestBase):
"""
Test Python API for credit requirements and eligibility.
"""
@ddt.data(
[
{
"namespace": "grade",
"criteria": {
"min_grade": 0.8
}
}
],
[
{
"name": "grade",
"criteria": {
"min_grade": 0.8
}
}
],
[
{
"namespace": "grade",
"name": "grade",
"display_name": "Grade"
}
]
)
def test_set_credit_requirements_invalid_requirements(self, requirements):
self.add_credit_course()
with self.assertRaises(InvalidCreditRequirements):
api.set_credit_requirements(self.course_key, requirements)
def test_set_credit_requirements_invalid_course(self):
# Test that 'InvalidCreditCourse' exception is raise if we try to
# set credit requirements for a non credit course.
requirements = [
{
"namespace": "grade",
"name": "grade",
"display_name": "Grade",
"criteria": {},
}
]
with self.assertRaises(InvalidCreditCourse):
api.set_credit_requirements(self.course_key, requirements)
self.add_credit_course(enabled=False)
with self.assertRaises(InvalidCreditCourse):
api.set_credit_requirements(self.course_key, requirements)
def test_set_get_credit_requirements(self):
# Test that if same requirement is added multiple times
self.add_credit_course()
requirements = [
{
"namespace": "grade",
"name": "grade",
"display_name": "Grade",
"criteria": {
"min_grade": 0.8
},
},
{
"namespace": "grade",
"name": "grade",
"display_name": "Grade",
"criteria": {
"min_grade": 0.9
},
}
]
api.set_credit_requirements(self.course_key, requirements)
self.assertEqual(len(api.get_credit_requirements(self.course_key)), 1)
def test_disable_existing_requirement(self):
self.add_credit_course()
# Set initial requirements
requirements = [
{
"namespace": "grade",
"name": "midterm",
"display_name": "Midterm",
"criteria": {},
},
{
"namespace": "grade",
"name": "grade",
"display_name": "Grade",
"criteria": {
"min_grade": 0.8
},
}
]
api.set_credit_requirements(self.course_key, requirements)
# Update the requirements, removing an existing requirement
api.set_credit_requirements(self.course_key, requirements[1:])
# Expect that now only the grade requirement is returned
visible_reqs = api.get_credit_requirements(self.course_key)
self.assertEqual(len(visible_reqs), 1)
self.assertEqual(visible_reqs[0]["namespace"], "grade")
def test_disable_credit_requirements(self):
self.add_credit_course()
requirements = [
{
"namespace": "grade",
"name": "grade",
"display_name": "Grade",
"criteria": {
"min_grade": 0.8
},
}
]
api.set_credit_requirements(self.course_key, requirements)
self.assertEqual(len(api.get_credit_requirements(self.course_key)), 1)
requirements = [
{
"namespace": "grade",
"name": "other_grade",
"display_name": "Assessment 1",
"criteria": {},
}
]
api.set_credit_requirements(self.course_key, requirements)
self.assertEqual(len(api.get_credit_requirements(self.course_key)), 1)
grade_req = CreditRequirement.objects.filter(namespace="grade", name="grade")
self.assertEqual(len(grade_req), 1)
self.assertEqual(grade_req[0].active, False)
def test_is_user_eligible_for_credit(self):
credit_course = self.add_credit_course()
CreditEligibility.objects.create(
course=credit_course, username=self.user.username
)
is_eligible = api.is_user_eligible_for_credit(self.user.username, credit_course.course_key)
self.assertTrue(is_eligible)
is_eligible = api.is_user_eligible_for_credit('abc', credit_course.course_key)
self.assertFalse(is_eligible)
@ddt.data(
CourseMode.AUDIT,
CourseMode.HONOR,
CourseMode.CREDIT_MODE
)
def test_user_eligibility_with_non_verified_enrollment(self, mode):
"""
Tests that user do not become credit eligible even after meeting the credit requirements.
User can not become credit eligible if he does not has credit eligible enrollment in the course.
"""
self.add_credit_course()
# Enroll user and verify his enrollment.
self.enroll(self.user, self.course_key, mode)
self.assertTrue(CourseEnrollment.is_enrolled(self.user, self.course_key))
self.assertTrue(CourseEnrollment.enrollment_mode_for_user(self.user, self.course_key), (mode, True))
requirements = [
{
"namespace": "grade",
"name": "grade",
"display_name": "Grade",
"criteria": {
"min_grade": 0.6
},
}
]
# Set & verify course credit requirements.
api.set_credit_requirements(self.course_key, requirements)
requirements = api.get_credit_requirements(self.course_key)
self.assertEqual(len(requirements), 1)
# Set the requirement to "satisfied" and check that they are not set for non-credit eligible enrollment.
api.set_credit_requirement_status(self.user, self.course_key, "grade", "grade", status='satisfied')
self.assert_grade_requirement_status(None, 0)
# Verify user is not eligible for credit.
self.assertFalse(api.is_user_eligible_for_credit(self.user.username, self.course_key))
def test_eligibility_expired(self):
# Configure a credit eligibility that expired yesterday
credit_course = self.add_credit_course()
CreditEligibility.objects.create(
course=credit_course,
username="staff",
deadline=datetime.datetime.now(pytz.UTC) - datetime.timedelta(days=1)
)
# The user should NOT be eligible for credit
is_eligible = api.is_user_eligible_for_credit("staff", credit_course.course_key)
self.assertFalse(is_eligible)
# The eligibility should NOT show up in the user's list of eligibilities
eligibilities = api.get_eligibilities_for_user("staff")
self.assertEqual(eligibilities, [])
def test_eligibility_disabled_course(self):
# Configure a credit eligibility for a disabled course
credit_course = self.add_credit_course()
credit_course.enabled = False
credit_course.save()
CreditEligibility.objects.create(
course=credit_course,
username="staff",
)
# The user should NOT be eligible for credit
is_eligible = api.is_user_eligible_for_credit("staff", credit_course.course_key)
self.assertFalse(is_eligible)
# The eligibility should NOT show up in the user's list of eligibilities
eligibilities = api.get_eligibilities_for_user("staff")
self.assertEqual(eligibilities, [])
def assert_grade_requirement_status(self, expected_status, expected_sort_value):
""" Assert the status and order of the grade requirement. """
req_status = api.get_credit_requirement_status(self.course_key, self.user, namespace="grade", name="grade")
self.assertEqual(req_status[0]["status"], expected_status)
self.assertEqual(req_status[0]["order"], expected_sort_value)
return req_status
def _set_credit_course_requirements(self):
"""
Sets requirements for the credit course.
Returns:
dict: Course requirements
"""
requirements = [
{
"namespace": "grade",
"name": "grade",
"display_name": "Grade",
"criteria": {
"min_grade": 0.8
},
},
{
"namespace": "grade",
"name": "other_grade",
"display_name": "Assessment 1",
"criteria": {},
}
]
api.set_credit_requirements(self.course_key, requirements)
course_requirements = api.get_credit_requirements(self.course_key)
self.assertEqual(len(course_requirements), 2)
@ddt.data(
*CourseMode.CREDIT_ELIGIBLE_MODES
)
def test_set_credit_requirement_status(self, mode):
"""
Test set/update credit requirement status
"""
username = self.user.username
credit_course = self.add_credit_course()
# Enroll user and verify his enrollment.
self.enroll(self.user, self.course_key, mode)
self.assertTrue(CourseEnrollment.is_enrolled(self.user, self.course_key))
self.assertTrue(CourseEnrollment.enrollment_mode_for_user(self.user, self.course_key), (mode, True))
self._set_credit_course_requirements()
# Initially, the status should be None
self.assert_grade_requirement_status(None, 0)
# Requirement statuses cannot be changed if a CreditRequest exists
credit_request = CreditRequest.objects.create(
course=credit_course,
provider=CreditProvider.objects.first(),
username=username,
)
api.set_credit_requirement_status(self.user, self.course_key, "grade", "grade")
self.assert_grade_requirement_status(None, 0)
credit_request.delete()
# order of below two assertions matter as:
# `failed` to `satisfied` is allowed
# `satisfied` to `failed` is not allowed
# 1. Set the requirement to "failed" and check that it's actually set
api.set_credit_requirement_status(self.user, self.course_key, "grade", "grade", status="failed")
self.assert_grade_requirement_status('failed', 0)
# 2. Set the requirement to "satisfied" and check that it's actually set
api.set_credit_requirement_status(self.user, self.course_key, "grade", "grade")
self.assert_grade_requirement_status('satisfied', 0)
req_status = api.get_credit_requirement_status(self.course_key, username)
self.assertEqual(req_status[0]["status"], "satisfied")
self.assertEqual(req_status[0]["order"], 0)
# make sure the 'order' on the 2nd requirement is set correctly (aka 1)
self.assertEqual(req_status[1]["status"], None)
self.assertEqual(req_status[1]["order"], 1)
# Set the requirement to "declined" and check that it's actually set
api.set_credit_requirement_status(
self.user, self.course_key,
"grade",
"other_grade",
status="declined"
)
req_status = api.get_credit_requirement_status(
self.course_key,
username,
namespace="grade",
name="other_grade"
)
self.assertEqual(req_status[0]["status"], "declined")
@ddt.data(
*CourseMode.CREDIT_ELIGIBLE_MODES
)
def test_set_credit_requirement_status_satisfied_to_failed(self, mode):
"""
Test that if credit requirment status is set to `satisfied`, it
can not not be changed to `failed`
"""
self.add_credit_course()
# Enroll user and verify enrollment.
self.enroll(self.user, self.course_key, mode)
self.assertTrue(CourseEnrollment.is_enrolled(self.user, self.course_key))
self.assertTrue(CourseEnrollment.enrollment_mode_for_user(self.user, self.course_key), (mode, True))
self._set_credit_course_requirements()
api.set_credit_requirement_status(self.user, self.course_key, "grade", "grade", status="satisfied")
self.assert_grade_requirement_status('satisfied', 0)
# try to set status to `failed`
api.set_credit_requirement_status(self.user, self.course_key, "grade", "grade", status="failed")
# status should not be changed to `failed`, rather should maintain already set status `satisfied`
self.assert_grade_requirement_status('satisfied', 0)
@ddt.data(
*CourseMode.CREDIT_ELIGIBLE_MODES
)
def test_remove_credit_requirement_status(self, mode):
self.add_credit_course()
self.enroll(self.user, self.course_key, mode)
username = self.user.username
requirements = [
{
"namespace": "grade",
"name": "grade",
"display_name": "Grade",
"criteria": {
"min_grade": 0.8
},
},
{
"namespace": "grade",
"name": "other_grade",
"display_name": "Assessment 1",
"criteria": {},
}
]
api.set_credit_requirements(self.course_key, requirements)
course_requirements = api.get_credit_requirements(self.course_key)
self.assertEqual(len(course_requirements), 2)
# before setting credit_requirement_status
api.remove_credit_requirement_status(username, self.course_key, "grade", "grade")
req_status = api.get_credit_requirement_status(self.course_key, username, namespace="grade", name="grade")
self.assertIsNone(req_status[0]["status"])
self.assertIsNone(req_status[0]["status_date"])
self.assertIsNone(req_status[0]["reason"])
# Set the requirement to "satisfied" and check that it's actually set
api.set_credit_requirement_status(self.user, self.course_key, "grade", "grade")
req_status = api.get_credit_requirement_status(self.course_key, username, namespace="grade", name="grade")
self.assertEqual(len(req_status), 1)
self.assertEqual(req_status[0]["status"], "satisfied")
# remove the credit requirement status and check that it's actually removed
api.remove_credit_requirement_status(self.user.username, self.course_key, "grade", "grade")
req_status = api.get_credit_requirement_status(self.course_key, username, namespace="grade", name="grade")
self.assertIsNone(req_status[0]["status"])
self.assertIsNone(req_status[0]["status_date"])
self.assertIsNone(req_status[0]["reason"])
def test_remove_credit_requirement_status_req_not_configured(self):
# Configure a credit course with no requirements
self.add_credit_course()
# A user satisfies a requirement. This could potentially
# happen if there's a lag when the requirements are removed
# after the course is published.
api.remove_credit_requirement_status("bob", self.course_key, "grade", "grade")
# Since the requirement hasn't been published yet, it won't show
# up in the list of requirements.
req_status = api.get_credit_requirement_status(self.course_key, "bob", namespace="grade", name="grade")
self.assertEqual(len(req_status), 0)
@httpretty.activate
@override_settings(
ECOMMERCE_API_URL=TEST_API_URL,
ECOMMERCE_SERVICE_WORKER_USERNAME=TEST_ECOMMERCE_WORKER
)
def test_satisfy_all_requirements(self):
""" Test the credit requirements, eligibility notification, email
content caching for a credit course.
"""
self._mock_ecommerce_courses_api(self.course_key, self.COURSE_API_RESPONSE)
worker_user = User.objects.create_user(username=TEST_ECOMMERCE_WORKER)
self.assertFalse(hasattr(worker_user, 'profile'))
# Configure a course with two credit requirements
self.add_credit_course()
user = self.create_and_enroll_user(username=self.USER_INFO['username'], password=self.USER_INFO['password'])
requirements = [
{
"namespace": "grade",
"name": "grade",
"display_name": "Grade",
"criteria": {
"min_grade": 0.8
},
},
{
"namespace": "grade",
"name": "other_grade",
"display_name": "Assessment 1",
"criteria": {},
}
]
api.set_credit_requirements(self.course_key, requirements)
# Satisfy one of the requirements, but not the other
with self.assertNumQueries(11):
api.set_credit_requirement_status(
user,
self.course_key,
requirements[0]["namespace"],
requirements[0]["name"]
)
# The user should not be eligible (because only one requirement is satisfied)
self.assertFalse(api.is_user_eligible_for_credit(user.username, self.course_key))
# Satisfy the other requirement
with self.assertNumQueries(22):
api.set_credit_requirement_status(
user,
self.course_key,
requirements[1]["namespace"],
requirements[1]["name"]
)
# Now the user should be eligible
self.assertTrue(api.is_user_eligible_for_credit(user.username, self.course_key))
# Credit eligibility email should be sent
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(
mail.outbox[0].subject,
'You are eligible for credit from Hogwarts School of Witchcraft and Wizardry'
)
# Now verify them email content
email_payload_first = mail.outbox[0].attachments[0]._payload # pylint: disable=protected-access
# Test that email has two payloads [multipart (plain text and html
# content), attached image]
self.assertEqual(len(email_payload_first), 2)
# pylint: disable=protected-access
self.assertIn('text/plain', email_payload_first[0]._payload[0]['Content-Type'])
# pylint: disable=protected-access
self.assertIn('text/html', email_payload_first[0]._payload[1]['Content-Type'])
self.assertIn('image/png', email_payload_first[1]['Content-Type'])
# Now check that html email content has same logo image 'Content-ID'
# as the attached logo image 'Content-ID'
email_image = email_payload_first[1]
html_content_first = email_payload_first[0]._payload[1]._payload # pylint: disable=protected-access
# strip enclosing angle brackets from 'logo_image' cache 'Content-ID'
image_id = email_image.get('Content-ID', '')[1:-1]
self.assertIsNotNone(image_id)
self.assertIn(image_id, html_content_first)
self.assertIn(
'credit from Hogwarts School of Witchcraft and Wizardry for',
html_content_first
)
# test text email contents
text_content_first = email_payload_first[0]._payload[0]._payload
self.assertIn(
'credit from Hogwarts School of Witchcraft and Wizardry for',
text_content_first
)
# Delete the eligibility entries and satisfy the user's eligibility
# requirement again to trigger eligibility notification
CreditEligibility.objects.all().delete()
with self.assertNumQueries(15):
api.set_credit_requirement_status(
user,
self.course_key,
requirements[1]["namespace"],
requirements[1]["name"]
)
# Credit eligibility email should be sent
self.assertEqual(len(mail.outbox), 2)
# Now check that on sending eligibility notification again cached
# logo image is used
email_payload_second = mail.outbox[1].attachments[0]._payload # pylint: disable=protected-access
html_content_second = email_payload_second[0]._payload[1]._payload # pylint: disable=protected-access
self.assertIn(image_id, html_content_second)
# The user should remain eligible even if the requirement status is later changed
api.set_credit_requirement_status(
user,
self.course_key,
requirements[0]["namespace"],
requirements[0]["name"],
status="failed"
)
self.assertTrue(api.is_user_eligible_for_credit(user.username, self.course_key))
def test_set_credit_requirement_status_req_not_configured(self):
# Configure a credit course with no requirements
username = self.user.username
self.add_credit_course()
# A user satisfies a requirement. This could potentially
# happen if there's a lag when the requirements are updated
# after the course is published.
api.set_credit_requirement_status(self.user, self.course_key, "grade", "grade")
# Since the requirement hasn't been published yet, it won't show
# up in the list of requirements.
req_status = api.get_credit_requirement_status(self.course_key, username, namespace="grade", name="grade")
self.assertEqual(req_status, [])
# Now add the requirements, simulating what happens when a course is published.
requirements = [
{
"namespace": "grade",
"name": "grade",
"display_name": "Grade",
"criteria": {
"min_grade": 0.8
},
},
{
"namespace": "grade",
"name": "other_grade",
"display_name": "Assessment 1",
"criteria": {},
}
]
api.set_credit_requirements(self.course_key, requirements)
# The user should not have satisfied the requirements, since they weren't
# in effect when the user completed the requirement
req_status = api.get_credit_requirement_status(self.course_key, username)
self.assertEqual(len(req_status), 2)
self.assertEqual(req_status[0]["status"], None)
self.assertEqual(req_status[0]["status"], None)
# The user should *not* have satisfied the reverification requirement
req_status = api.get_credit_requirement_status(
self.course_key,
username,
namespace=requirements[1]["namespace"],
name=requirements[1]["name"]
)
self.assertEqual(len(req_status), 1)
self.assertEqual(req_status[0]["status"], None)
@ddt.data(
(
[u'Arizona State University'],
'credit from Arizona State University for',
'You are eligible for credit from Arizona State University'),
(
[u'Arizona State University', u'Hogwarts School of Witchcraft and Wizardry'],
'credit from Arizona State University and Hogwarts School of Witchcraft and Wizardry for',
'You are eligible for credit from Arizona State University and Hogwarts School of Witchcraft and Wizardry'
),
(
[u'Arizona State University', u'Hogwarts School of Witchcraft and Wizardry', u'Charter Oak'],
'credit from Arizona State University, Hogwarts School of Witchcraft and Wizardry, and Charter Oak for',
'You are eligible for credit from Arizona State University, Hogwarts School'
' of Witchcraft and Wizardry, and Charter Oak'
),
([], 'credit for', 'Course Credit Eligibility'),
(None, 'credit for', 'Course Credit Eligibility')
)
@ddt.unpack
def test_eligibility_email_with_providers(self, providers_list, providers_email_message, expected_subject):
""" Test the credit requirements, eligibility notification, email
for different providers combinations.
"""
# Configure a course with two credit requirements
self.add_credit_course()
user = self.create_and_enroll_user(username=self.USER_INFO['username'], password=self.USER_INFO['password'])
requirements = [
{
"namespace": "grade",
"name": "grade",
"display_name": "Grade",
"criteria": {
"min_grade": 0.8
},
},
{
"namespace": "grade",
"name": "other_grade",
"display_name": "Assessment 1",
"criteria": {},
}
]
api.set_credit_requirements(self.course_key, requirements)
# Satisfy one of the requirements, but not the other
api.set_credit_requirement_status(
user,
self.course_key,
requirements[0]["namespace"],
requirements[0]["name"]
)
# Satisfy the other requirement. And mocked the api to return different kind of data.
with mock.patch(
'openedx.core.djangoapps.credit.email_utils.get_credit_provider_attribute_values'
) as mock_method:
mock_method.return_value = providers_list
api.set_credit_requirement_status(
user,
self.course_key,
requirements[1]["namespace"],
requirements[1]["name"]
)
# Now the user should be eligible
self.assertTrue(api.is_user_eligible_for_credit(user.username, self.course_key))
# Credit eligibility email should be sent
self.assertEqual(len(mail.outbox), 1)
# Verify the email subject
self.assertEqual(mail.outbox[0].subject, expected_subject)
# Now verify them email content
email_payload_first = mail.outbox[0].attachments[0]._payload # pylint: disable=protected-access
html_content_first = email_payload_first[0]._payload[1]._payload # pylint: disable=protected-access
self.assertIn(providers_email_message, html_content_first)
# test text email
text_content_first = email_payload_first[0]._payload[0]._payload # pylint: disable=protected-access
self.assertIn(providers_email_message, text_content_first)
@ddt.ddt
class CreditProviderIntegrationApiTests(CreditApiTestBase):
"""
Test Python API for credit provider integration.
"""
USER_INFO = {
"username": "bob",
"email": "bob@example.com",
"full_name": "Bob",
"mailing_address": "123 Fake Street, Cambridge MA",
"country": "US",
}
FINAL_GRADE = 0.95
def setUp(self):
super(CreditProviderIntegrationApiTests, self).setUp()
self.user = UserFactory(
username=self.USER_INFO['username'],
email=self.USER_INFO['email'],
)
self.user.profile.name = self.USER_INFO['full_name']
self.user.profile.mailing_address = self.USER_INFO['mailing_address']
self.user.profile.country = self.USER_INFO['country']
self.user.profile.save()
# By default, configure the database so that there is a single
# credit requirement that the user has satisfied (minimum grade)
self._configure_credit()
def test_get_credit_providers(self):
# The provider should show up in the list
result = api.get_credit_providers()
self.assertEqual(result, [
{
"id": self.PROVIDER_ID,
"display_name": self.PROVIDER_NAME,
"url": self.PROVIDER_URL,
"status_url": self.PROVIDER_STATUS_URL,
"description": self.PROVIDER_DESCRIPTION,
"enable_integration": self.ENABLE_INTEGRATION,
"fulfillment_instructions": self.FULFILLMENT_INSTRUCTIONS,
"thumbnail_url": self.THUMBNAIL_URL
}
])
# Disable the provider; it should be hidden from the list
provider = CreditProvider.objects.get()
provider.active = False
provider.save()
result = api.get_credit_providers()
self.assertEqual(result, [])
def test_get_credit_providers_details(self):
"""Test that credit api method 'test_get_credit_provider_details'
returns dictionary data related to provided credit provider.
"""
expected_result = [{
"id": self.PROVIDER_ID,
"display_name": self.PROVIDER_NAME,
"url": self.PROVIDER_URL,
"status_url": self.PROVIDER_STATUS_URL,
"description": self.PROVIDER_DESCRIPTION,
"enable_integration": self.ENABLE_INTEGRATION,
"fulfillment_instructions": self.FULFILLMENT_INSTRUCTIONS,
"thumbnail_url": self.THUMBNAIL_URL
}]
result = api.get_credit_providers([self.PROVIDER_ID])
self.assertEqual(result, expected_result)
# now test that user gets empty dict for non existent credit provider
result = api.get_credit_providers(['fake_provider_id'])
self.assertEqual(result, [])
def test_credit_request(self):
# Initiate a credit request
request = api.create_credit_request(self.course_key, self.PROVIDER_ID, self.USER_INFO['username'])
# Validate the URL and method
self.assertIn('url', request)
self.assertEqual(request['url'], self.PROVIDER_URL)
self.assertIn('method', request)
self.assertEqual(request['method'], "POST")
self.assertIn('parameters', request)
parameters = request['parameters']
# Validate the UUID
self.assertIn('request_uuid', parameters)
self.assertEqual(len(parameters['request_uuid']), 32)
# Validate the timestamp
self.assertIn('timestamp', parameters)
parsed_date = from_timestamp(parameters['timestamp'])
self.assertLess(parsed_date, datetime.datetime.now(pytz.UTC))
# Validate course information
self.assertEqual(parameters['course_org'], self.course_key.org)
self.assertEqual(parameters['course_num'], self.course_key.course)
self.assertEqual(parameters['course_run'], self.course_key.run)
self.assertEqual(parameters['final_grade'], six.text_type(self.FINAL_GRADE))
# Validate user information
for key in self.USER_INFO.keys():
param_key = 'user_{key}'.format(key=key)
self.assertIn(param_key, parameters)
expected = '' if key == 'mailing_address' else self.USER_INFO[key]
self.assertEqual(parameters[param_key], expected)
def test_create_credit_request_grade_length(self):
""" Verify the length of the final grade is limited to seven (7) characters total.
This is a hack for ASU.
"""
# Update the user's grade
status = CreditRequirementStatus.objects.get(username=self.USER_INFO["username"])
status.status = "satisfied"
status.reason = {"final_grade": 1.0 / 3.0}
status.save()
# Initiate a credit request
request = api.create_credit_request(self.course_key, self.PROVIDER_ID, self.USER_INFO['username'])
self.assertEqual(request['parameters']['final_grade'], u'0.33333')
def test_create_credit_request_address_empty(self):
""" Verify the mailing address is always empty. """
request = api.create_credit_request(self.course_key, self.PROVIDER_ID, self.user.username)
self.assertEqual(request['parameters']['user_mailing_address'], '')
def test_credit_request_disable_integration(self):
CreditProvider.objects.all().update(enable_integration=False)
# Initiate a request with automatic integration disabled
request = api.create_credit_request(self.course_key, self.PROVIDER_ID, self.USER_INFO['username'])
# We get a URL and a GET method, so we can provide students
# with a link to the credit provider, where they can request
# credit directly.
self.assertIn("url", request)
self.assertEqual(request["url"], self.PROVIDER_URL)
self.assertIn("method", request)
self.assertEqual(request["method"], "GET")
@ddt.data("approved", "rejected")
def test_credit_request_status(self, status):
request = api.create_credit_request(self.course_key, self.PROVIDER_ID, self.USER_INFO["username"])
# Initial status should be "pending"
self._assert_credit_status("pending")
credit_request_status = api.get_credit_request_status(self.USER_INFO['username'], self.course_key)
self.assertEqual(credit_request_status["status"], "pending")
# Update the status
api.update_credit_request_status(request["parameters"]["request_uuid"], self.PROVIDER_ID, status)
self._assert_credit_status(status)
credit_request_status = api.get_credit_request_status(self.USER_INFO['username'], self.course_key)
self.assertEqual(credit_request_status["status"], status)
def test_query_counts(self):
# Yes, this is a lot of queries, but this API call is also doing a lot of work :)
# - 1 query: Check the user's eligibility and retrieve the credit course
# - 1 Get the provider of the credit course.
# - 2 queries: Get-or-create the credit request.
# - 1 query: Retrieve user account and profile information from the user API.
# - 1 query: Look up the user's final grade from the credit requirements table.
# - 1 query: Look up the user's enrollment date in the course.
# - 2 query: Look up the user's completion date in the course.
# - 1 query: Update the request.
# - 4 Django savepoints
with self.assertNumQueries(14):
request = api.create_credit_request(self.course_key, self.PROVIDER_ID, self.USER_INFO['username'])
# - 2 queries: Retrieve and update the request
uuid = request["parameters"]["request_uuid"]
with self.assertNumQueries(2):
api.update_credit_request_status(uuid, self.PROVIDER_ID, "approved")
with self.assertNumQueries(1):
api.get_credit_requests_for_user(self.USER_INFO["username"])
def test_reuse_credit_request(self):
# Create the first request
first_request = api.create_credit_request(self.course_key, self.PROVIDER_ID, self.USER_INFO["username"])
# Update the user's profile information, then attempt a second request
self.user.profile.name = "Bobby"
self.user.profile.save()
second_request = api.create_credit_request(self.course_key, self.PROVIDER_ID, self.USER_INFO["username"])
# Request UUID should be the same
self.assertEqual(
first_request["parameters"]["request_uuid"],
second_request["parameters"]["request_uuid"]
)
# Request should use the updated information
self.assertEqual(second_request["parameters"]["user_full_name"], "Bobby")
@ddt.data("approved", "rejected")
def test_cannot_make_credit_request_after_response(self, status):
# Create the first request
request = api.create_credit_request(self.course_key, self.PROVIDER_ID, self.USER_INFO["username"])
# Provider updates the status
api.update_credit_request_status(request["parameters"]["request_uuid"], self.PROVIDER_ID, status)
# Attempting a second request raises an exception
with self.assertRaises(RequestAlreadyCompleted):
api.create_credit_request(self.course_key, self.PROVIDER_ID, self.USER_INFO['username'])
@ddt.data("pending", "failed")
def test_user_is_not_eligible(self, requirement_status):
# Simulate a user who is not eligible for credit
CreditEligibility.objects.all().delete()
status = CreditRequirementStatus.objects.get(username=self.USER_INFO['username'])
status.status = requirement_status
status.reason = {}
status.save()
with self.assertRaises(UserIsNotEligible):
api.create_credit_request(self.course_key, self.PROVIDER_ID, self.USER_INFO['username'])
def test_create_credit_request_for_second_course(self):
# Create the first request
first_request = api.create_credit_request(self.course_key, self.PROVIDER_ID, self.USER_INFO["username"])
# Create a request for a second course
other_course_key = CourseKey.from_string("edX/other/2015")
self._configure_credit(course_key=other_course_key)
second_request = api.create_credit_request(other_course_key, self.PROVIDER_ID, self.USER_INFO["username"])
# Check that the requests have the correct course number
self.assertEqual(first_request["parameters"]["course_num"], self.course_key.course)
self.assertEqual(second_request["parameters"]["course_num"], other_course_key.course)
def test_create_request_null_mailing_address(self):
# User did not specify a mailing address
self.user.profile.mailing_address = None
self.user.profile.save()
# Request should include an empty mailing address field
request = api.create_credit_request(self.course_key, self.PROVIDER_ID, self.USER_INFO["username"])
self.assertEqual(request["parameters"]["user_mailing_address"], "")
def test_create_request_null_country(self):
# Simulate users who registered accounts before the country field was introduced.
# We need to manipulate the database directly because the country Django field
# coerces None values to empty strings.
query = u"UPDATE auth_userprofile SET country = NULL WHERE id = %s"
connection.cursor().execute(query, [str(self.user.profile.id)])
# Request should include an empty country field
request = api.create_credit_request(self.course_key, self.PROVIDER_ID, self.USER_INFO["username"])
self.assertEqual(request["parameters"]["user_country"], "")
def test_user_has_no_final_grade(self):
# Simulate an error condition that should never happen:
# a user is eligible for credit, but doesn't have a final
# grade recorded in the eligibility requirement.
grade_status = CreditRequirementStatus.objects.get(
username=self.USER_INFO['username'],
requirement__namespace="grade",
requirement__name="grade"
)
grade_status.reason = {}
grade_status.save()
with self.assertRaises(UserIsNotEligible):
api.create_credit_request(self.course_key, self.PROVIDER_ID, self.USER_INFO["username"])
def test_update_invalid_credit_status(self):
# The request status must be either "approved" or "rejected"
request = api.create_credit_request(self.course_key, self.PROVIDER_ID, self.USER_INFO["username"])
with self.assertRaises(InvalidCreditStatus):
api.update_credit_request_status(request["parameters"]["request_uuid"], self.PROVIDER_ID, "invalid")
def test_update_credit_request_not_found(self):
# The request UUID must exist
with self.assertRaises(CreditRequestNotFound):
api.update_credit_request_status("invalid_uuid", self.PROVIDER_ID, "approved")
def test_get_credit_requests_no_requests(self):
requests = api.get_credit_requests_for_user(self.USER_INFO["username"])
self.assertEqual(requests, [])
def _configure_credit(self, course_key=None):
"""
Configure a credit course and its requirements.
By default, add a single requirement (minimum grade)
that the user has satisfied.
"""
course_key = course_key or self.course_key
credit_course = self.add_credit_course(course_key=course_key)
requirement = CreditRequirement.objects.create(
course=credit_course,
namespace="grade",
name="grade",
active=True
)
status = CreditRequirementStatus.objects.create(
username=self.USER_INFO["username"],
requirement=requirement,
)
status.status = "satisfied"
status.reason = {"final_grade": self.FINAL_GRADE}
status.save()
CreditEligibility.objects.create(
username=self.USER_INFO['username'],
course=CreditCourse.objects.get(course_key=course_key)
)
def _assert_credit_status(self, expected_status):
"""Check the user's credit status. """
statuses = api.get_credit_requests_for_user(self.USER_INFO["username"])
self.assertEqual(statuses[0]["status"], expected_status)
@skip_unless_lms
@override_settings(
ECOMMERCE_API_URL=TEST_API_URL,
ECOMMERCE_SERVICE_WORKER_USERNAME=TEST_ECOMMERCE_WORKER
)
@ddt.ddt
class CourseApiTests(CreditApiTestBase):
"""Test Python API for course product information."""
def setUp(self):
super(CourseApiTests, self).setUp()
self.worker_user = User.objects.create_user(username=TEST_ECOMMERCE_WORKER)
self.add_credit_course(self.course_key)
self.credit_config = CreditConfig(cache_ttl=100, enabled=True)
self.credit_config.save()
# Add another provider.
CreditProvider.objects.get_or_create(
provider_id='ASU',
display_name='Arizona State University',
provider_url=self.PROVIDER_URL,
provider_status_url=self.PROVIDER_STATUS_URL,
provider_description=self.PROVIDER_DESCRIPTION,
enable_integration=self.ENABLE_INTEGRATION,
fulfillment_instructions=self.FULFILLMENT_INSTRUCTIONS,
thumbnail_url=self.THUMBNAIL_URL
)
self.assertFalse(hasattr(self.worker_user, 'profile'))
@httpretty.activate
def test_get_credit_provider_display_names_method(self):
"""Verify that parsed providers list is returns after getting course production information."""
self._mock_ecommerce_courses_api(self.course_key, self.COURSE_API_RESPONSE)
response_providers = get_credit_provider_attribute_values(self.course_key, 'display_name')
self.assertListEqual(self.PROVIDERS_LIST, response_providers)
@httpretty.activate
@mock.patch('edx_rest_api_client.client.EdxRestApiClient.__init__')
def test_get_credit_provider_display_names_method_with_exception(self, mock_init):
"""Verify that in case of any exception it logs the error and return."""
mock_init.side_effect = Exception
response = get_credit_provider_attribute_values(self.course_key, 'display_name')
self.assertTrue(mock_init.called)
self.assertEqual(response, None)
@httpretty.activate
def test_get_credit_provider_display_names_caching(self):
"""Verify that providers list is cached."""
self.assertTrue(self.credit_config.is_cache_enabled)
self._mock_ecommerce_courses_api(self.course_key, self.COURSE_API_RESPONSE)
# Warm up the cache.
response_providers = get_credit_provider_attribute_values(self.course_key, 'display_name')
self.assertListEqual(self.PROVIDERS_LIST, response_providers)
# Hit the cache.
response_providers = get_credit_provider_attribute_values(self.course_key, 'display_name')
self.assertListEqual(self.PROVIDERS_LIST, response_providers)
# Verify only one request was made.
self.assertEqual(len(httpretty.httpretty.latest_requests), 1)
@httpretty.activate
def test_get_credit_provider_display_names_without_caching(self):
"""Verify that providers list is not cached."""
self.credit_config.cache_ttl = 0
self.credit_config.save()
self.assertFalse(self.credit_config.is_cache_enabled)
self._mock_ecommerce_courses_api(self.course_key, self.COURSE_API_RESPONSE)
response_providers = get_credit_provider_attribute_values(self.course_key, 'display_name')
self.assertListEqual(self.PROVIDERS_LIST, response_providers)
response_providers = get_credit_provider_attribute_values(self.course_key, 'display_name')
self.assertListEqual(self.PROVIDERS_LIST, response_providers)
self.assertEqual(len(httpretty.httpretty.latest_requests), 2)
@httpretty.activate
@ddt.data(
(None, None),
({'products': []}, []),
(
{
'products': [{'expires': '', 'attribute_values': [{'name': 'credit_provider', 'value': 'ASU'}]}]
}, ['Arizona State University']
),
(
{
'products': [{'expires': '', 'attribute_values': [{'name': 'namespace', 'value': 'grade'}]}]
}, []
),
(
{
'products': [
{
'expires': '', 'attribute_values':
[
{'name': 'credit_provider', 'value': 'ASU'},
{'name': 'credit_provider', 'value': 'hogwarts'},
{'name': 'course_type', 'value': 'credit'}
]
}
]
}, ['Hogwarts School of Witchcraft and Wizardry', 'Arizona State University']
)
)
@ddt.unpack
def test_get_provider_api_with_multiple_data(self, data, expected_data):
self._mock_ecommerce_courses_api(self.course_key, data)
response_providers = get_credit_provider_attribute_values(self.course_key, 'display_name')
self.assertEqual(expected_data, response_providers)
@httpretty.activate
def test_get_credit_provider_display_names_without_providers(self):
"""Verify that if all providers are in-active than method return empty list."""
self._mock_ecommerce_courses_api(self.course_key, self.COURSE_API_RESPONSE)
CreditProvider.objects.all().update(active=False)
self.assertEqual(get_credit_provider_attribute_values(self.course_key, 'display_name'), [])
@ddt.data(None, ['asu'], ['asu', 'co'], ['asu', 'co', 'mit'])
def test_make_providers_strings(self, providers):
""" Verify that method returns given provider list as comma separated string. """
provider_string = make_providers_strings(providers)
if not providers:
self.assertEqual(provider_string, None)
elif len(providers) == 1:
self.assertEqual(provider_string, providers[0])
elif len(providers) == 2:
self.assertEqual(provider_string, 'asu and co')
else:
self.assertEqual(provider_string, 'asu, co, and mit')
|
cpennington/edx-platform
|
openedx/core/djangoapps/credit/tests/test_api.py
|
Python
|
agpl-3.0
| 54,612
|
"""
Discussion API serializers
"""
from urllib import urlencode
from urlparse import urlunparse
from django.contrib.auth.models import User as DjangoUser
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from rest_framework import serializers
from discussion_api.permissions import (
NON_UPDATABLE_COMMENT_FIELDS,
NON_UPDATABLE_THREAD_FIELDS,
get_editable_fields,
)
from discussion_api.render import render_body
from django_comment_client.utils import is_comment_too_deep
from django_comment_common.models import (
FORUM_ROLE_ADMINISTRATOR,
FORUM_ROLE_COMMUNITY_TA,
FORUM_ROLE_MODERATOR,
Role,
)
from lms.lib.comment_client.comment import Comment
from lms.lib.comment_client.thread import Thread
from lms.lib.comment_client.user import User as CommentClientUser
from lms.lib.comment_client.utils import CommentClientRequestError
from openedx.core.djangoapps.course_groups.cohorts import get_cohort_names
def get_context(course, request, thread=None):
"""
Returns a context appropriate for use with ThreadSerializer or
(if thread is provided) CommentSerializer.
"""
# TODO: cache staff_user_ids and ta_user_ids if we need to improve perf
staff_user_ids = {
user.id
for role in Role.objects.filter(
name__in=[FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR],
course_id=course.id
)
for user in role.users.all()
}
ta_user_ids = {
user.id
for role in Role.objects.filter(name=FORUM_ROLE_COMMUNITY_TA, course_id=course.id)
for user in role.users.all()
}
requester = request.user
cc_requester = CommentClientUser.from_django_user(requester).retrieve()
cc_requester["course_id"] = course.id
return {
"course": course,
"request": request,
"thread": thread,
# For now, the only groups are cohorts
"group_ids_to_names": get_cohort_names(course),
"is_requester_privileged": requester.id in staff_user_ids or requester.id in ta_user_ids,
"staff_user_ids": staff_user_ids,
"ta_user_ids": ta_user_ids,
"cc_requester": cc_requester,
}
def validate_not_blank(value):
"""
Validate that a value is not an empty string or whitespace.
Raises: ValidationError
"""
if not value.strip():
raise ValidationError("This field may not be blank.")
class _ContentSerializer(serializers.Serializer):
"""A base class for thread and comment serializers."""
id = serializers.CharField(read_only=True) # pylint: disable=invalid-name
author = serializers.SerializerMethodField()
author_label = serializers.SerializerMethodField()
created_at = serializers.CharField(read_only=True)
updated_at = serializers.CharField(read_only=True)
raw_body = serializers.CharField(source="body", validators=[validate_not_blank])
rendered_body = serializers.SerializerMethodField()
abuse_flagged = serializers.SerializerMethodField()
voted = serializers.SerializerMethodField()
vote_count = serializers.SerializerMethodField()
editable_fields = serializers.SerializerMethodField()
non_updatable_fields = set()
def __init__(self, *args, **kwargs):
super(_ContentSerializer, self).__init__(*args, **kwargs)
for field in self.non_updatable_fields:
setattr(self, "validate_{}".format(field), self._validate_non_updatable)
def _validate_non_updatable(self, value):
"""Ensure that a field is not edited in an update operation."""
if self.instance:
raise ValidationError("This field is not allowed in an update.")
return value
def _is_user_privileged(self, user_id):
"""
Returns a boolean indicating whether the given user_id identifies a
privileged user.
"""
return user_id in self.context["staff_user_ids"] or user_id in self.context["ta_user_ids"]
def _is_anonymous(self, obj):
"""
Returns a boolean indicating whether the content should be anonymous to
the requester.
"""
return (
obj["anonymous"] or
obj["anonymous_to_peers"] and not self.context["is_requester_privileged"]
)
def get_author(self, obj):
"""Returns the author's username, or None if the content is anonymous."""
return None if self._is_anonymous(obj) else obj["username"]
def _get_user_label(self, user_id):
"""
Returns the role label (i.e. "Staff" or "Community TA") for the user
with the given id.
"""
return (
"Staff" if user_id in self.context["staff_user_ids"] else
"Community TA" if user_id in self.context["ta_user_ids"] else
None
)
def get_author_label(self, obj):
"""Returns the role label for the content author."""
if self._is_anonymous(obj) or obj["user_id"] is None:
return None
else:
user_id = int(obj["user_id"])
return self._get_user_label(user_id)
def get_rendered_body(self, obj):
"""Returns the rendered body content."""
return render_body(obj["body"])
def get_abuse_flagged(self, obj):
"""
Returns a boolean indicating whether the requester has flagged the
content as abusive.
"""
return self.context["cc_requester"]["id"] in obj.get("abuse_flaggers", [])
def get_voted(self, obj):
"""
Returns a boolean indicating whether the requester has voted for the
content.
"""
return obj["id"] in self.context["cc_requester"]["upvoted_ids"]
def get_vote_count(self, obj):
"""Returns the number of votes for the content."""
return obj.get("votes", {}).get("up_count", 0)
def get_editable_fields(self, obj):
"""Return the list of the fields the requester can edit"""
return sorted(get_editable_fields(obj, self.context))
class ThreadSerializer(_ContentSerializer):
"""
A serializer for thread data.
N.B. This should not be used with a comment_client Thread object that has
not had retrieve() called, because of the interaction between DRF's attempts
at introspection and Thread's __getattr__.
"""
course_id = serializers.CharField()
topic_id = serializers.CharField(source="commentable_id", validators=[validate_not_blank])
group_id = serializers.IntegerField(required=False, allow_null=True)
group_name = serializers.SerializerMethodField()
type = serializers.ChoiceField(
source="thread_type",
choices=[(val, val) for val in ["discussion", "question"]]
)
title = serializers.CharField(validators=[validate_not_blank])
pinned = serializers.SerializerMethodField(read_only=True)
closed = serializers.BooleanField(read_only=True)
following = serializers.SerializerMethodField()
comment_count = serializers.IntegerField(source="comments_count", read_only=True)
unread_comment_count = serializers.IntegerField(source="unread_comments_count", read_only=True)
comment_list_url = serializers.SerializerMethodField()
endorsed_comment_list_url = serializers.SerializerMethodField()
non_endorsed_comment_list_url = serializers.SerializerMethodField()
read = serializers.BooleanField(read_only=True)
has_endorsed = serializers.BooleanField(read_only=True, source="endorsed")
response_count = serializers.IntegerField(source="resp_total", read_only=True)
non_updatable_fields = NON_UPDATABLE_THREAD_FIELDS
# TODO: https://openedx.atlassian.net/browse/MA-1359
def __init__(self, *args, **kwargs):
remove_fields = kwargs.pop('remove_fields', None)
super(ThreadSerializer, self).__init__(*args, **kwargs)
# Compensate for the fact that some threads in the comments service do
# not have the pinned field set
if self.instance and self.instance.get("pinned") is None:
self.instance["pinned"] = False
if self.instance and self.instance.get("resp_total") is None:
self.instance["resp_total"] = None
if remove_fields:
# for multiple fields in a list
for field_name in remove_fields:
self.fields.pop(field_name)
def get_pinned(self, obj):
"""
Compensate for the fact that some threads in the comments service do
not have the pinned field set.
"""
return bool(obj["pinned"])
def get_group_name(self, obj):
"""Returns the name of the group identified by the thread's group_id."""
return self.context["group_ids_to_names"].get(obj["group_id"])
def get_following(self, obj):
"""
Returns a boolean indicating whether the requester is following the
thread.
"""
return obj["id"] in self.context["cc_requester"]["subscribed_thread_ids"]
def get_comment_list_url(self, obj, endorsed=None):
"""
Returns the URL to retrieve the thread's comments, optionally including
the endorsed query parameter.
"""
if (
(obj["thread_type"] == "question" and endorsed is None) or
(obj["thread_type"] == "discussion" and endorsed is not None)
):
return None
path = reverse("comment-list")
query_dict = {"thread_id": obj["id"]}
if endorsed is not None:
query_dict["endorsed"] = endorsed
return self.context["request"].build_absolute_uri(
urlunparse(("", "", path, "", urlencode(query_dict), ""))
)
def get_endorsed_comment_list_url(self, obj):
"""Returns the URL to retrieve the thread's endorsed comments."""
return self.get_comment_list_url(obj, endorsed=True)
def get_non_endorsed_comment_list_url(self, obj):
"""Returns the URL to retrieve the thread's non-endorsed comments."""
return self.get_comment_list_url(obj, endorsed=False)
def create(self, validated_data):
thread = Thread(user_id=self.context["cc_requester"]["id"], **validated_data)
thread.save()
return thread
def update(self, instance, validated_data):
for key, val in validated_data.items():
instance[key] = val
instance.save()
return instance
class CommentSerializer(_ContentSerializer):
"""
A serializer for comment data.
N.B. This should not be used with a comment_client Comment object that has
not had retrieve() called, because of the interaction between DRF's attempts
at introspection and Comment's __getattr__.
"""
thread_id = serializers.CharField()
parent_id = serializers.CharField(required=False, allow_null=True)
endorsed = serializers.BooleanField(required=False)
endorsed_by = serializers.SerializerMethodField()
endorsed_by_label = serializers.SerializerMethodField()
endorsed_at = serializers.SerializerMethodField()
children = serializers.SerializerMethodField()
non_updatable_fields = NON_UPDATABLE_COMMENT_FIELDS
def get_endorsed_by(self, obj):
"""
Returns the username of the endorsing user, if the information is
available and would not identify the author of an anonymous thread.
"""
endorsement = obj.get("endorsement")
if endorsement:
endorser_id = int(endorsement["user_id"])
# Avoid revealing the identity of an anonymous non-staff question
# author who has endorsed a comment in the thread
if not (
self._is_anonymous(self.context["thread"]) and
not self._is_user_privileged(endorser_id)
):
return DjangoUser.objects.get(id=endorser_id).username
return None
def get_endorsed_by_label(self, obj):
"""
Returns the role label (i.e. "Staff" or "Community TA") for the
endorsing user
"""
endorsement = obj.get("endorsement")
if endorsement:
return self._get_user_label(int(endorsement["user_id"]))
else:
return None
def get_endorsed_at(self, obj):
"""Returns the timestamp for the endorsement, if available."""
endorsement = obj.get("endorsement")
return endorsement["time"] if endorsement else None
def get_children(self, obj):
return [
CommentSerializer(child, context=self.context).data
for child in obj.get("children", [])
]
def to_representation(self, data):
data = super(CommentSerializer, self).to_representation(data)
# Django Rest Framework v3 no longer includes None values
# in the representation. To maintain the previous behavior,
# we do this manually instead.
if 'parent_id' not in data:
data["parent_id"] = None
return data
def validate(self, attrs):
"""
Ensure that parent_id identifies a comment that is actually in the
thread identified by thread_id and does not violate the configured
maximum depth.
"""
parent = None
parent_id = attrs.get("parent_id")
if parent_id:
try:
parent = Comment(id=parent_id).retrieve()
except CommentClientRequestError:
pass
if not (parent and parent["thread_id"] == attrs["thread_id"]):
raise ValidationError(
"parent_id does not identify a comment in the thread identified by thread_id."
)
if is_comment_too_deep(parent):
raise ValidationError({"parent_id": ["Comment level is too deep."]})
return attrs
def create(self, validated_data):
comment = Comment(
course_id=self.context["thread"]["course_id"],
user_id=self.context["cc_requester"]["id"],
**validated_data
)
comment.save()
return comment
def update(self, instance, validated_data):
for key, val in validated_data.items():
instance[key] = val
# TODO: The comments service doesn't populate the endorsement
# field on comment creation, so we only provide
# endorsement_user_id on update
if key == "endorsed":
instance["endorsement_user_id"] = self.context["cc_requester"]["id"]
instance.save()
return instance
|
jamiefolsom/edx-platform
|
lms/djangoapps/discussion_api/serializers.py
|
Python
|
agpl-3.0
| 14,571
|
"""Tests for the lms module itself."""
import logging
import mimetypes
from django.conf import settings
from django.test import TestCase
from edxmako import LOOKUP, add_lookup
log = logging.getLogger(__name__)
class LmsModuleTests(TestCase):
"""
Tests for lms module itself.
"""
def test_new_mimetypes(self):
extensions = ['eot', 'otf', 'ttf', 'woff']
for extension in extensions:
mimetype, _ = mimetypes.guess_type('test.' + extension)
self.assertIsNotNone(mimetype)
def test_api_docs(self):
"""
Tests that requests to the `/api-docs/` endpoint do not raise an exception.
"""
response = self.client.get('/api-docs/')
self.assertEqual(200, response.status_code)
|
cpennington/edx-platform
|
lms/tests.py
|
Python
|
agpl-3.0
| 771
|
"""Implements basics of Capa, including class CapaModule."""
import json
import logging
import sys
import re
from lxml import etree
from pkg_resources import resource_string
import dogstats_wrapper as dog_stats_api
from .capa_base import CapaMixin, CapaFields, ComplexEncoder
from capa import responsetypes
from .progress import Progress
from xmodule.util.misc import escape_html_characters
from xmodule.x_module import XModule, module_attr, DEPRECATION_VSCOMPAT_EVENT
from xmodule.raw_module import RawDescriptor
from xmodule.exceptions import NotFoundError, ProcessingError
log = logging.getLogger("edx.courseware")
class CapaModule(CapaMixin, XModule):
"""
An XModule implementing LonCapa format problems, implemented by way of
capa.capa_problem.LoncapaProblem
CapaModule.__init__ takes the same arguments as xmodule.x_module:XModule.__init__
"""
icon_class = 'problem'
js = {
'coffee': [
resource_string(__name__, 'js/src/capa/display.coffee'),
resource_string(__name__, 'js/src/javascript_loader.coffee'),
],
'js': [
resource_string(__name__, 'js/src/collapsible.js'),
resource_string(__name__, 'js/src/capa/imageinput.js'),
resource_string(__name__, 'js/src/capa/schematic.js'),
]
}
js_module_name = "Problem"
css = {'scss': [resource_string(__name__, 'css/capa/display.scss')]}
def __init__(self, *args, **kwargs):
"""
Accepts the same arguments as xmodule.x_module:XModule.__init__
"""
super(CapaModule, self).__init__(*args, **kwargs)
def handle_ajax(self, dispatch, data):
"""
This is called by courseware.module_render, to handle an AJAX call.
`data` is request.POST.
Returns a json dictionary:
{ 'progress_changed' : True/False,
'progress' : 'none'/'in_progress'/'done',
<other request-specific values here > }
"""
handlers = {
'hint_button': self.hint_button,
'problem_get': self.get_problem,
'problem_check': self.check_problem,
'problem_reset': self.reset_problem,
'problem_save': self.save_problem,
'problem_show': self.get_answer,
'score_update': self.update_score,
'input_ajax': self.handle_input_ajax,
'ungraded_response': self.handle_ungraded_response
}
_ = self.runtime.service(self, "i18n").ugettext
generic_error_message = _(
"We're sorry, there was an error with processing your request. "
"Please try reloading your page and trying again."
)
not_found_error_message = _(
"The state of this problem has changed since you loaded this page. "
"Please refresh your page."
)
if dispatch not in handlers:
return 'Error: {} is not a known capa action'.format(dispatch)
before = self.get_progress()
try:
result = handlers[dispatch](data)
except NotFoundError as err:
log.exception(
"Unable to find data when dispatching %s to %s for user %s",
dispatch,
self.scope_ids.usage_id,
self.scope_ids.user_id
)
_, _, traceback_obj = sys.exc_info() # pylint: disable=redefined-outer-name
raise ProcessingError(not_found_error_message), None, traceback_obj
except Exception as err:
log.exception(
"Unknown error when dispatching %s to %s for user %s",
dispatch,
self.scope_ids.usage_id,
self.scope_ids.user_id
)
_, _, traceback_obj = sys.exc_info() # pylint: disable=redefined-outer-name
raise ProcessingError(generic_error_message), None, traceback_obj
after = self.get_progress()
result.update({
'progress_changed': after != before,
'progress_status': Progress.to_js_status_str(after),
'progress_detail': Progress.to_js_detail_str(after),
})
return json.dumps(result, cls=ComplexEncoder)
class CapaDescriptor(CapaFields, RawDescriptor):
"""
Module implementing problems in the LON-CAPA format,
as implemented by capa.capa_problem
"""
INDEX_CONTENT_TYPE = 'CAPA'
module_class = CapaModule
has_score = True
show_in_read_only_mode = True
template_dir_name = 'problem'
mako_template = "widgets/problem-edit.html"
js = {'coffee': [resource_string(__name__, 'js/src/problem/edit.coffee')]}
js_module_name = "MarkdownEditingDescriptor"
css = {
'scss': [
resource_string(__name__, 'css/editor/edit.scss'),
resource_string(__name__, 'css/problem/edit.scss')
]
}
# The capa format specifies that what we call max_attempts in the code
# is the attribute `attempts`. This will do that conversion
metadata_translations = dict(RawDescriptor.metadata_translations)
metadata_translations['attempts'] = 'max_attempts'
@classmethod
def filter_templates(cls, template, course):
"""
Filter template that contains 'latex' from templates.
Show them only if use_latex_compiler is set to True in
course settings.
"""
return 'latex' not in template['template_id'] or course.use_latex_compiler
def get_context(self):
_context = RawDescriptor.get_context(self)
_context.update({
'markdown': self.markdown,
'enable_markdown': self.markdown is not None,
'enable_latex_compiler': self.use_latex_compiler,
})
return _context
# VS[compat]
# TODO (cpennington): Delete this method once all fall 2012 course are being
# edited in the cms
@classmethod
def backcompat_paths(cls, path):
dog_stats_api.increment(
DEPRECATION_VSCOMPAT_EVENT,
tags=["location:capa_descriptor_backcompat_paths"]
)
return [
'problems/' + path[8:],
path[8:],
]
@property
def non_editable_metadata_fields(self):
non_editable_fields = super(CapaDescriptor, self).non_editable_metadata_fields
non_editable_fields.extend([
CapaDescriptor.due,
CapaDescriptor.graceperiod,
CapaDescriptor.force_save_button,
CapaDescriptor.markdown,
CapaDescriptor.text_customization,
CapaDescriptor.use_latex_compiler,
])
return non_editable_fields
@property
def problem_types(self):
""" Low-level problem type introspection for content libraries filtering by problem type """
tree = etree.XML(self.data)
registered_tags = responsetypes.registry.registered_tags()
return set([node.tag for node in tree.iter() if node.tag in registered_tags])
def index_dictionary(self):
"""
Return dictionary prepared with module content and type for indexing.
"""
xblock_body = super(CapaDescriptor, self).index_dictionary()
# Removing solutions and hints, as well as script and style
capa_content = re.sub(
re.compile(
r"""
<solution>.*?</solution> |
<script>.*?</script> |
<style>.*?</style> |
<[a-z]*hint.*?>.*?</[a-z]*hint>
""",
re.DOTALL |
re.VERBOSE),
"",
self.data
)
capa_content = escape_html_characters(capa_content)
capa_body = {
"capa_content": capa_content,
"display_name": self.display_name,
}
if "content" in xblock_body:
xblock_body["content"].update(capa_body)
else:
xblock_body["content"] = capa_body
xblock_body["content_type"] = self.INDEX_CONTENT_TYPE
xblock_body["problem_types"] = list(self.problem_types)
return xblock_body
def has_support(self, view, functionality):
"""
Override the XBlock.has_support method to return appropriate
value for the multi-device functionality.
Returns whether the given view has support for the given functionality.
"""
if functionality == "multi_device":
return all(
responsetypes.registry.get_class_for_tag(tag).multi_device_support
for tag in self.problem_types
)
return False
# Proxy to CapaModule for access to any of its attributes
answer_available = module_attr('answer_available')
check_button_name = module_attr('check_button_name')
check_button_checking_name = module_attr('check_button_checking_name')
check_problem = module_attr('check_problem')
choose_new_seed = module_attr('choose_new_seed')
closed = module_attr('closed')
get_answer = module_attr('get_answer')
get_problem = module_attr('get_problem')
get_problem_html = module_attr('get_problem_html')
get_state_for_lcp = module_attr('get_state_for_lcp')
handle_input_ajax = module_attr('handle_input_ajax')
hint_button = module_attr('hint_button')
handle_problem_html_error = module_attr('handle_problem_html_error')
handle_ungraded_response = module_attr('handle_ungraded_response')
is_attempted = module_attr('is_attempted')
is_correct = module_attr('is_correct')
is_past_due = module_attr('is_past_due')
is_submitted = module_attr('is_submitted')
lcp = module_attr('lcp')
make_dict_of_responses = module_attr('make_dict_of_responses')
new_lcp = module_attr('new_lcp')
publish_grade = module_attr('publish_grade')
rescore_problem = module_attr('rescore_problem')
reset_problem = module_attr('reset_problem')
save_problem = module_attr('save_problem')
set_state_from_lcp = module_attr('set_state_from_lcp')
should_show_check_button = module_attr('should_show_check_button')
should_show_reset_button = module_attr('should_show_reset_button')
should_show_save_button = module_attr('should_show_save_button')
update_score = module_attr('update_score')
|
solashirai/edx-platform
|
common/lib/xmodule/xmodule/capa_module.py
|
Python
|
agpl-3.0
| 10,313
|
"""
Signal handler for setting default course mode expiration dates
"""
import logging
from crum import get_current_user
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.signals import post_save
from django.dispatch.dispatcher import receiver
from xmodule.modulestore.django import SignalHandler, modulestore
from xmodule.modulestore.exceptions import ItemNotFoundError
from xmodule.partitions.partitions import ENROLLMENT_TRACK_PARTITION_ID
from .models import CourseMode, CourseModeExpirationConfig
log = logging.getLogger(__name__)
@receiver(SignalHandler.course_published)
def _listen_for_course_publish(sender, course_key, **kwargs): # pylint: disable=unused-argument
"""
Catches the signal that a course has been published in Studio and
sets the verified mode dates to defaults.
"""
try:
verified_mode = CourseMode.objects.get(course_id=course_key, mode_slug=CourseMode.VERIFIED)
if _should_update_date(verified_mode):
course = modulestore().get_course(course_key)
if not course:
return None
verification_window = CourseModeExpirationConfig.current().verification_window
new_expiration_datetime = course.end - verification_window
if verified_mode.expiration_datetime != new_expiration_datetime:
# Set the expiration_datetime without triggering the explicit flag
verified_mode._expiration_datetime = new_expiration_datetime # pylint: disable=protected-access
verified_mode.save()
except ObjectDoesNotExist:
pass
def _should_update_date(verified_mode):
""" Returns whether or not the verified mode should be updated. """
return not(verified_mode is None or verified_mode.expiration_datetime_is_explicit)
@receiver(post_save, sender=CourseMode)
def update_masters_access_course(sender, instance, **kwargs): # pylint: disable=unused-argument
"""
Update all blocks in the verified content group to include the master's content group
"""
if instance.mode_slug != CourseMode.MASTERS:
return
masters_id = getattr(settings, 'COURSE_ENROLLMENT_MODES', {}).get('masters', {}).get('id', None)
verified_id = getattr(settings, 'COURSE_ENROLLMENT_MODES', {}).get('verified', {}).get('id', None)
if not (masters_id and verified_id):
log.error("Missing settings.COURSE_ENROLLMENT_MODES -> verified:%s masters:%s", verified_id, masters_id)
return
course_id = instance.course_id
user = get_current_user()
user_id = user.id if user else None
store = modulestore()
with store.bulk_operations(course_id):
try:
items = store.get_items(course_id, settings={'group_access': {'$exists': True}}, include_orphans=False)
except ItemNotFoundError:
return
for item in items:
group_access = item.group_access
enrollment_groups = group_access.get(ENROLLMENT_TRACK_PARTITION_ID, None)
if enrollment_groups is not None:
if verified_id in enrollment_groups and masters_id not in enrollment_groups:
enrollment_groups.append(masters_id)
item.group_access = group_access
log.info("Publishing %s with Master's group access", item.location)
store.update_item(item, user_id)
store.publish(item.location, user_id)
|
eduNEXT/edunext-platform
|
common/djangoapps/course_modes/signals.py
|
Python
|
agpl-3.0
| 3,507
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 Smile (<http://www.smile.fr>). All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from subprocess import os
def zipdir(path, zip):
for root, dirs, files in os.walk(path):
for file in files:
zip.write(os.path.join(root, file))
|
tiexinliu/odoo_addons
|
smile_module_repository/tools/osutil.py
|
Python
|
agpl-3.0
| 1,146
|
import dbus
bus = dbus.SystemBus()
# This adds a signal match so that the client gets signals sent by Blivet1's
# ObjectManager. These signals are used to notify clients of changes to the
# managed objects (for blivet, this will be devices, formats, and actions).
bus.add_match_string("type='signal',sender='com.redhat.Blivet1',path_namespace='/com/redhat/Blivet1'")
blivet = bus.get_object('com.redhat.Blivet1', '/com/redhat/Blivet1/Blivet')
blivet.Reset()
object_manager = bus.get_object('com.redhat.Blivet1', '/com/redhat/Blivet1')
objects = object_manager.GetManagedObjects()
for object_path in blivet.ListDevices():
device = objects[object_path]['com.redhat.Blivet1.Device']
fmt = objects[device['Format']]['com.redhat.Blivet1.Format']
print(device['Name'], device['Type'], device['Size'], fmt['Type'])
|
AdamWill/blivet
|
examples/dbus_client.py
|
Python
|
lgpl-2.1
| 825
|
# Copyright 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.
"""Full Correlation Matrix Analysis (FCMA)
Correlation related high performance routines
"""
# Authors: Yida Wang
# (Intel Labs), 2017
import numpy as np
from . import cython_blas as blas # type: ignore
from scipy.stats.mstats import zscore
import math
__all__ = [
"compute_correlation",
]
def _normalize_for_correlation(data, axis, return_nans=False):
"""normalize the data before computing correlation
The data will be z-scored and divided by sqrt(n)
along the assigned axis
Parameters
----------
data: 2D array
axis: int
specify which dimension of the data should be normalized
return_nans: bool, default:False
If False, return zeros for NaNs; if True, return NaNs
Returns
-------
data: 2D array
the normalized data
"""
shape = data.shape
data = zscore(data, axis=axis, ddof=0)
# if zscore fails (standard deviation is zero),
# optionally set all values to be zero
if not return_nans:
data = np.nan_to_num(data)
data = data / math.sqrt(shape[axis])
return data
def compute_correlation(matrix1, matrix2, return_nans=False):
"""compute correlation between two sets of variables
Correlate the rows of matrix1 with the rows of matrix2.
If matrix1 == matrix2, it is auto-correlation computation
resulting in a symmetric correlation matrix.
The number of columns MUST agree between set1 and set2.
The correlation being computed here is
the Pearson's correlation coefficient, which can be expressed as
.. math:: corr(X, Y) = \\frac{cov(X, Y)}{\\sigma_X\\sigma_Y}
where cov(X, Y) is the covariance of variable X and Y, and
.. math:: \\sigma_X
is the standard deviation of variable X
Reducing the correlation computation to matrix multiplication
and using BLAS GEMM API wrapped by Scipy can speedup the numpy built-in
correlation computation (numpy.corrcoef) by one order of magnitude
.. math::
corr(X, Y)
&= \\frac{\\sum\\limits_{i=1}^n (x_i-\\bar{x})(y_i-\\bar{y})}{(n-1)
\\sqrt{\\frac{\\sum\\limits_{j=1}^n x_j^2-n\\bar{x}}{n-1}}
\\sqrt{\\frac{\\sum\\limits_{j=1}^{n} y_j^2-n\\bar{y}}{n-1}}}\\\\
&= \\sum\\limits_{i=1}^n(\\frac{(x_i-\\bar{x})}
{\\sqrt{\\sum\\limits_{j=1}^n x_j^2-n\\bar{x}}}
\\frac{(y_i-\\bar{y})}{\\sqrt{\\sum\\limits_{j=1}^n y_j^2-n\\bar{y}}})
By default (return_nans=False), returns zeros for vectors with NaNs.
If return_nans=True, convert zeros to NaNs (np.nan) in output.
Parameters
----------
matrix1: 2D array in shape [r1, c]
MUST be continuous and row-major
matrix2: 2D array in shape [r2, c]
MUST be continuous and row-major
return_nans: bool, default:False
If False, return zeros for NaNs; if True, return NaNs
Returns
-------
corr_data: 2D array in shape [r1, r2]
continuous and row-major in np.float32
"""
matrix1 = matrix1.astype(np.float32)
matrix2 = matrix2.astype(np.float32)
[r1, d1] = matrix1.shape
[r2, d2] = matrix2.shape
if d1 != d2:
raise ValueError('Dimension discrepancy')
# preprocess two components
matrix1 = _normalize_for_correlation(matrix1, 1,
return_nans=return_nans)
matrix2 = _normalize_for_correlation(matrix2, 1,
return_nans=return_nans)
corr_data = np.empty((r1, r2), dtype=np.float32, order='C')
# blas routine is column-major
blas.compute_single_matrix_multiplication('T', 'N',
r2, r1, d1,
1.0,
matrix2, d2,
matrix1, d1,
0.0,
corr_data,
r2)
return corr_data
|
brainiak/brainiak
|
brainiak/fcma/util.py
|
Python
|
apache-2.0
| 4,594
|
import mock
import pytest
from urlparse import urlparse
from addons.wiki.tests.factories import NodeWikiFactory
from api.base.settings.defaults import API_BASE
from api.base.settings import osf_settings
from api_tests import utils as test_utils
from framework.auth import core
from osf.models import Guid
from osf_tests.factories import (
ProjectFactory,
AuthUserFactory,
CommentFactory,
RegistrationFactory,
PrivateLinkFactory,
)
from rest_framework import exceptions
@pytest.mark.django_db
class CommentDetailMixin(object):
@pytest.fixture()
def user(self):
return AuthUserFactory()
@pytest.fixture()
def contributor(self):
return AuthUserFactory()
@pytest.fixture()
def non_contrib(self):
return AuthUserFactory()
# check if all necessary fixtures are setup by subclass
@pytest.fixture()
def private_project(self):
raise NotImplementedError
@pytest.fixture()
def comment(self):
raise NotImplementedError
@pytest.fixture()
def private_url(self):
raise NotImplementedError
@pytest.fixture()
def payload(self):
raise NotImplementedError
# public_project_with_comments
@pytest.fixture()
def public_project(self):
raise NotImplementedError
@pytest.fixture()
def public_comment(self):
raise NotImplementedError
@pytest.fixture()
def public_comment_reply(self):
raise NotImplementedError
@pytest.fixture()
def public_url(self):
raise NotImplementedError
@pytest.fixture()
def public_comment_payload(self):
raise NotImplementedError
# registration_with_comments
@pytest.fixture()
def registration(self):
raise NotImplementedError
@pytest.fixture()
def registration_url(self):
raise NotImplementedError
@pytest.fixture()
def registration_comment(self):
raise NotImplementedError
@pytest.fixture()
def comment_url(self):
raise NotImplementedError
@pytest.fixture()
def registration_comment_reply(self):
raise NotImplementedError
@pytest.fixture()
def replies_url(self):
raise NotImplementedError
@pytest.fixture()
def set_up_payload(self):
def payload(target_id, content='test', has_content=True):
payload = {
'data': {
'id': target_id,
'type': 'comments',
'attributes': {
'content': 'Updating this comment',
'deleted': False
}
}
}
if has_content:
payload['data']['attributes']['content'] = content
return payload
return payload
def test_private_node_comments_related_auth(self, app, user, contributor, non_contrib, comment, private_url):
# test_private_node_logged_in_contributor_can_view_comment
res = app.get(private_url, auth=user.auth)
assert res.status_code == 200
assert comment._id == res.json['data']['id']
assert comment.content == res.json['data']['attributes']['content']
# def test_private_node_logged_in_non_contrib_cannot_view_comment
res = app.get(private_url, auth=non_contrib.auth, expect_errors=True)
assert res.status_code == 403
assert res.json['errors'][0]['detail'] == exceptions.PermissionDenied.default_detail
# def test_private_node_logged_out_user_cannot_view_comment
res = app.get(private_url, expect_errors=True)
assert res.status_code == 401
assert res.json['errors'][0]['detail'] == exceptions.NotAuthenticated.default_detail
def test_private_node_user_with_private_and_anonymous_link_misc(self, app, private_project, comment):
# def test_private_node_user_with_private_link_can_see_comment
private_link = PrivateLinkFactory(anonymous=False)
private_link.nodes.add(private_project)
private_link.save()
res = app.get('/{}comments/{}/'.format(API_BASE, comment._id), {'view_only': private_link.key}, expect_errors=True)
assert res.status_code == 200
assert comment._id == res.json['data']['id']
assert comment.content == res.json['data']['attributes']['content']
# test_private_node_user_with_anonymous_link_cannot_see_commenter_info
private_link = PrivateLinkFactory(anonymous=True)
private_link.nodes.add(private_project)
private_link.save()
res = app.get('/{}comments/{}/'.format(API_BASE, comment._id), {'view_only': private_link.key})
assert res.status_code == 200
assert comment._id == res.json['data']['id']
assert comment.content == res.json['data']['attributes']['content']
assert 'user' not in res.json['data']['relationships']
# test_private_node_user_with_anonymous_link_cannot_see_mention_info
comment.content = 'test with [@username](userlink) and @mention'
comment.save()
res = app.get('/{}comments/{}/'.format(API_BASE, comment._id), {'view_only': private_link.key})
assert res.status_code == 200
assert comment._id == res.json['data']['id']
assert 'test with @A User and @mention' == res.json['data']['attributes']['content']
def test_public_node_comment_auth_misc(self, app, user, non_contrib, public_project, public_url, public_comment, registration_comment, comment_url):
# test_public_node_logged_in_contributor_can_view_comment
res = app.get(public_url, auth=user.auth)
assert res.status_code == 200
assert public_comment._id == res.json['data']['id']
assert public_comment.content == res.json['data']['attributes']['content']
# test_public_node_logged_in_non_contrib_can_view_comment
res = app.get(public_url, auth=non_contrib.auth)
assert res.status_code == 200
assert public_comment._id == res.json['data']['id']
assert public_comment.content == res.json['data']['attributes']['content']
# test_public_node_logged_out_user_can_view_comment
res = app.get(public_url)
assert res.status_code == 200
assert public_comment._id == res.json['data']['id']
assert public_comment.content == res.json['data']['attributes']['content']
# test_registration_logged_in_contributor_can_view_comment
res = app.get(comment_url, auth=user.auth)
assert res.status_code == 200
assert registration_comment._id == res.json['data']['id']
assert registration_comment.content == res.json['data']['attributes']['content']
# test_public_node_user_with_private_link_can_view_comment
private_link = PrivateLinkFactory(anonymous=False)
private_link.nodes.add(public_project)
private_link.save()
res = app.get('/{}comments/{}/'.format(API_BASE, public_comment._id), {'view_only': private_link.key}, expect_errors=True)
assert public_comment._id == res.json['data']['id']
assert public_comment.content == res.json['data']['attributes']['content']
def test_comment_has_multiple_links(self, app, user, public_url, public_project, public_comment, public_comment_reply, comment_url, registration):
res = app.get(public_url)
assert res.status_code == 200
# test_comment_has_user_link
url_user = res.json['data']['relationships']['user']['links']['related']['href']
expected_url = '/{}users/{}/'.format(API_BASE, user._id)
assert urlparse(url_user).path == expected_url
# test_comment_has_node_link
url_node = res.json['data']['relationships']['node']['links']['related']['href']
expected_url = '/{}nodes/{}/'.format(API_BASE, public_project._id)
assert urlparse(url_node).path == expected_url
# test_comment_has_replies_link
url_replies = res.json['data']['relationships']['replies']['links']['related']['href']
uri = test_utils.urlparse_drop_netloc(url_replies)
res_uri = app.get(uri)
assert res_uri.status_code == 200
assert res_uri.json['data'][0]['type'] == 'comments'
# test_comment_has_reports_link
url_reports = res.json['data']['relationships']['reports']['links']['related']['href']
expected_url = '/{}comments/{}/reports/'.format(API_BASE, public_comment._id)
assert urlparse(url_reports).path == expected_url
# test_registration_comment_has_node_link
res = app.get(comment_url, auth=user.auth)
url = res.json['data']['relationships']['node']['links']['related']['href']
expected_url = '/{}registrations/{}/'.format(API_BASE, registration._id)
assert res.status_code == 200
assert urlparse(url).path == expected_url
def test_private_node_comment_auth_misc(self, app, user, non_contrib, private_url, payload):
# test_private_node_only_logged_in_contributor_commenter_can_update_comment
res = app.put_json_api(private_url, payload, auth=user.auth)
assert res.status_code == 200
assert payload['data']['attributes']['content'] == res.json['data']['attributes']['content']
# test_private_node_logged_in_non_contrib_cannot_update_comment
res = app.put_json_api(private_url, payload, auth=non_contrib.auth, expect_errors=True)
assert res.status_code == 403
assert res.json['errors'][0]['detail'] == exceptions.PermissionDenied.default_detail
# test_private_node_logged_out_user_cannot_update_comment
res = app.put_json_api(private_url, payload, expect_errors=True)
assert res.status_code == 401
assert res.json['errors'][0]['detail'] == exceptions.NotAuthenticated.default_detail
def test_public_node_comment_auth_misc(self, app, user, contributor, non_contrib, public_url, public_comment, public_comment_payload):
# test_public_node_only_contributor_commenter_can_update_comment
res = app.put_json_api(public_url, public_comment_payload, auth=user.auth)
assert res.status_code == 200
assert public_comment_payload['data']['attributes']['content'] == res.json['data']['attributes']['content']
# test_public_node_contributor_cannot_update_other_users_comment
res = app.put_json_api(public_url, public_comment_payload, auth=contributor.auth, expect_errors=True)
assert res.status_code == 403
assert res.json['errors'][0]['detail'] == exceptions.PermissionDenied.default_detail
# test_public_node_non_contrib_cannot_update_other_users_comment
res = app.put_json_api(public_url, public_comment_payload, auth=non_contrib.auth, expect_errors=True)
assert res.status_code == 403
assert res.json['errors'][0]['detail'] == exceptions.PermissionDenied.default_detail
# test_public_node_logged_out_user_cannot_update_comment
res = app.put_json_api(public_url, public_comment_payload, expect_errors=True)
assert res.status_code == 401
assert res.json['errors'][0]['detail'] == exceptions.NotAuthenticated.default_detail
def test_update_comment_misc(self, app, user, private_url, comment, set_up_payload):
# test_update_comment_cannot_exceed_max_length
content = ('c' * (osf_settings.COMMENT_MAXLENGTH + 3))
payload = set_up_payload(comment._id, content=content)
res = app.put_json_api(private_url, payload, auth=user.auth, expect_errors=True)
assert res.status_code == 400
assert (res.json['errors'][0]['detail'] ==
'Ensure this field has no more than {} characters.'.format(str(osf_settings.COMMENT_MAXLENGTH)))
# test_update_comment_cannot_be_empty
payload = set_up_payload(comment._id, content='')
res = app.put_json_api(private_url, payload, auth=user.auth, expect_errors=True)
assert res.status_code == 400
assert res.json['errors'][0]['detail'] == 'This field may not be blank.'
def test_private_node_only_logged_in_contributor_commenter_can_delete_comment(self, app, user, private_url):
res = app.delete_json_api(private_url, auth=user.auth)
assert res.status_code == 204
def test_private_node_only_logged_in_contributor_commenter_can_delete_own_reply(self, app, user, private_project, comment):
reply_target = Guid.load(comment._id)
reply = CommentFactory(node=private_project, target=reply_target, user=user)
reply_url = '/{}comments/{}/'.format(API_BASE, reply._id)
res = app.delete_json_api(reply_url, auth=user.auth)
assert res.status_code == 204
def test_private_node_only_logged_in_contributor_commenter_can_undelete_own_reply(self, app, user, private_project, comment, set_up_payload):
reply_target = Guid.load(comment._id)
reply = CommentFactory(node=private_project, target=reply_target, user=user)
reply_url = '/{}comments/{}/'.format(API_BASE, reply._id)
reply.is_deleted = True
reply.save()
payload = set_up_payload(reply._id, has_content=False)
res = app.patch_json_api(reply_url, payload, auth=user.auth)
assert res.status_code == 200
assert not res.json['data']['attributes']['deleted']
assert res.json['data']['attributes']['content'] == reply.content
def test_private_node_cannot_delete_comment_situation(self, app, user, contributor, non_contrib, private_url, comment):
# def test_private_node_contributor_cannot_delete_other_users_comment(self):
res = app.delete_json_api(private_url, auth=contributor.auth, expect_errors=True)
assert res.status_code == 403
assert res.json['errors'][0]['detail'] == exceptions.PermissionDenied.default_detail
# def test_private_node_non_contrib_cannot_delete_comment(self):
res = app.delete_json_api(private_url, auth=non_contrib.auth, expect_errors=True)
assert res.status_code == 403
assert res.json['errors'][0]['detail'] == exceptions.PermissionDenied.default_detail
# def test_private_node_logged_out_user_cannot_delete_comment(self):
res = app.delete_json_api(private_url, expect_errors=True)
assert res.status_code == 401
# def test_private_node_user_cannot_delete_already_deleted_comment(self):
comment.is_deleted = True
comment.save()
res = app.delete_json_api(private_url, auth=user.auth, expect_errors=True)
assert res.status_code == 400
assert res.json['errors'][0]['detail'] == 'Comment already deleted.'
def test_private_node_only_logged_in_contributor_commenter_can_undelete_comment(self, app, user, comment, set_up_payload):
comment.is_deleted = True
comment.save()
url = '/{}comments/{}/'.format(API_BASE, comment._id)
payload = set_up_payload(comment._id, has_content=False)
res = app.patch_json_api(url, payload, auth=user.auth)
assert res.status_code == 200
assert not res.json['data']['attributes']['deleted']
assert res.json['data']['attributes']['content'] == comment.content
def test_private_node_cannot_undelete_comment_situation(self, app, user, contributor, non_contrib, comment, set_up_payload):
comment.is_deleted = True
comment.save()
url = '/{}comments/{}/'.format(API_BASE, comment._id)
payload = set_up_payload(comment._id, has_content=False)
# test_private_node_contributor_cannot_undelete_other_users_comment
res = app.patch_json_api(url, payload, auth=contributor.auth, expect_errors=True)
assert res.status_code == 403
# test_private_node_non_contrib_cannot_undelete_comment
res = app.patch_json_api(url, payload, auth=non_contrib.auth, expect_errors=True)
assert res.status_code == 403
# test_private_node_logged_out_user_cannot_undelete_comment
res = app.patch_json_api(url, payload, expect_errors=True)
assert res.status_code == 401
def test_public_node_only_logged_in_contributor_commenter_can_delete_comment(self, app, user, public_url):
res = app.delete_json_api(public_url, auth=user.auth)
assert res.status_code == 204
def test_public_node_cannot_delete_comment_situations(self, app, user, contributor, non_contrib, public_url, public_comment):
# test_public_node_contributor_cannot_delete_other_users_comment
res = app.delete_json_api(public_url, auth=contributor.auth, expect_errors=True)
assert res.status_code == 403
assert res.json['errors'][0]['detail'] == exceptions.PermissionDenied.default_detail
# test_public_node_non_contrib_cannot_delete_other_users_comment
res = app.delete_json_api(public_url, auth=non_contrib.auth, expect_errors=True)
assert res.status_code == 403
assert res.json['errors'][0]['detail'] == exceptions.PermissionDenied.default_detail
# test_public_node_logged_out_user_cannot_delete_comment
res = app.delete_json_api(public_url, expect_errors=True)
assert res.status_code == 401
assert res.json['errors'][0]['detail'] == exceptions.NotAuthenticated.default_detail
# test_public_node_user_cannot_delete_already_deleted_comment
public_comment.is_deleted = True
public_comment.save()
res = app.delete_json_api(public_url, auth=user.auth, expect_errors=True)
assert res.status_code == 400
assert res.json['errors'][0]['detail'] == 'Comment already deleted.'
def test_private_node_deleted_comment_auth_misc(self, app, user, contributor, comment, private_project):
comment.is_deleted = True
comment.save()
# test_private_node_only_logged_in_commenter_can_view_deleted_comment
url = '/{}comments/{}/'.format(API_BASE, comment._id)
res = app.get(url, auth=user.auth)
assert res.status_code == 200
assert res.json['data']['attributes']['content'] == comment.content
# test_private_node_contributor_cannot_see_other_users_deleted_comment
url = '/{}comments/{}/'.format(API_BASE, comment._id)
res = app.get(url, auth=contributor.auth)
assert res.status_code == 200
assert res.json['data']['attributes']['content'] is None
# test_private_node_logged_out_user_cannot_see_deleted_comment
url = '/{}comments/{}/'.format(API_BASE, comment._id)
res = app.get(url, expect_errors=True)
assert res.status_code == 401
assert res.json['errors'][0]['detail'] == exceptions.NotAuthenticated.default_detail
# test_private_node_view_only_link_user_cannot_see_deleted_comment
private_link = PrivateLinkFactory(anonymous=False)
private_link.nodes.add(private_project)
private_link.save()
res = app.get('/{}comments/{}/'.format(API_BASE, comment._id), {'view_only': private_link.key}, expect_errors=True)
assert res.status_code == 200
assert res.json['data']['attributes']['content'] is None
# test_private_node_anonymous_view_only_link_user_cannot_see_deleted_comment
anonymous_link = PrivateLinkFactory(anonymous=True)
anonymous_link.nodes.add(private_project)
anonymous_link.save()
res = app.get('/{}comments/{}/'.format(API_BASE, comment._id), {'view_only': anonymous_link.key}, expect_errors=True)
assert res.status_code == 200
assert res.json['data']['attributes']['content'] is None
def test_public_node_deleted_comments_auth_misc(self, app, user, contributor, non_contrib, public_project, public_comment):
public_comment.is_deleted = True
public_comment.save()
url = '/{}comments/{}/'.format(API_BASE, public_comment._id)
# test_public_node_only_logged_in_commenter_can_view_deleted_comment
res = app.get(url, auth=user.auth)
assert res.status_code == 200
assert res.json['data']['attributes']['content'] == public_comment.content
# test_public_node_contributor_cannot_view_other_users_deleted_comment
res = app.get(url, auth=contributor.auth)
assert res.status_code == 200
assert res.json['data']['attributes']['content'] is None
# test_public_node_non_contrib_cannot_view_other_users_deleted_comment
res = app.get(url, auth=non_contrib.auth)
assert res.status_code == 200
assert res.json['data']['attributes']['content'] is None
# test_public_node_logged_out_user_cannot_view_deleted_comments
res = app.get(url)
assert res.status_code == 200
assert res.json['data']['attributes']['content'] is None
# test_public_node_view_only_link_user_cannot_see_deleted_comment
private_link = PrivateLinkFactory(anonymous=False)
private_link.nodes.add(public_project)
private_link.save()
res = app.get('/{}comments/{}/'.format(API_BASE, public_comment._id), {'view_only': private_link.key}, expect_errors=True)
assert res.status_code == 200
assert res.json['data']['attributes']['content'] is None
class TestCommentDetailView(CommentDetailMixin):
# private_project_with_comments
@pytest.fixture()
def private_project(self, user, contributor):
private_project = ProjectFactory.create(is_public=False, creator=user)
private_project.add_contributor(contributor, save=True)
return private_project
@pytest.fixture()
def comment(self, user, private_project):
return CommentFactory(node=private_project, user=user)
@pytest.fixture()
def private_url(self, comment):
return '/{}comments/{}/'.format(API_BASE, comment._id)
@pytest.fixture()
def payload(self, comment, set_up_payload):
return set_up_payload(comment._id)
# public_project_with_comments
@pytest.fixture()
def public_project(self, user, contributor):
public_project = ProjectFactory.create(is_public=True, creator=user)
public_project.add_contributor(contributor, save=True)
return public_project
@pytest.fixture()
def public_comment(self, user, public_project):
return CommentFactory(node=public_project, user=user)
@pytest.fixture()
def public_comment_reply(self, user, public_comment, public_project):
reply_target = Guid.load(public_comment._id)
return CommentFactory(node=public_project, target=reply_target, user=user)
@pytest.fixture()
def public_url(self, public_comment):
return '/{}comments/{}/'.format(API_BASE, public_comment._id)
@pytest.fixture()
def public_comment_payload(self, public_comment, set_up_payload):
return set_up_payload(public_comment._id)
# registration_with_comments
@pytest.fixture()
def registration(self, user):
return RegistrationFactory(creator=user)
@pytest.fixture()
def registration_url(self, registration):
return '/{}registrations/{}/'.format(API_BASE, registration._id)
@pytest.fixture()
def registration_comment(self, user, registration):
return CommentFactory(node=registration, user=user)
@pytest.fixture()
def comment_url(self, registration_comment):
return '/{}comments/{}/'.format(API_BASE, registration_comment._id)
@pytest.fixture()
def registration_comment_reply(self, user, registration, registration_comment):
reply_target = Guid.load(registration_comment._id)
return CommentFactory(node=registration, target=reply_target, user=user)
@pytest.fixture()
def replies_url(self, registration, registration_comment):
return '/{}registrations/{}/comments/?filter[target]={}'.format(API_BASE, registration._id, registration_comment._id)
def test_comment_has_target_link_with_correct_type(self, app, public_url, public_project):
res = app.get(public_url)
url = res.json['data']['relationships']['target']['links']['related']['href']
expected_url = '/{}nodes/{}/'.format(API_BASE, public_project._id)
target_type = res.json['data']['relationships']['target']['links']['related']['meta']['type']
expected_type = 'nodes'
assert res.status_code == 200
assert urlparse(url).path == expected_url
assert target_type == expected_type
def test_public_node_non_contrib_commenter_can_update_comment(self, app, non_contrib, set_up_payload):
project = ProjectFactory(is_public=True, comment_level='public')
comment = CommentFactory(node=project, user=non_contrib)
url = '/{}comments/{}/'.format(API_BASE, comment._id)
payload = set_up_payload(comment._id)
res = app.put_json_api(url, payload, auth=non_contrib.auth)
assert res.status_code == 200
assert payload['data']['attributes']['content'] == res.json['data']['attributes']['content']
def test_public_node_non_contrib_commenter_cannot_update_own_comment_if_comment_level_private(self, app, non_contrib, set_up_payload):
project = ProjectFactory(is_public=True, comment_level='public')
comment = CommentFactory(node=project, user=non_contrib)
project.comment_level = 'private'
project.save()
url = '/{}comments/{}/'.format(API_BASE, comment._id)
payload = set_up_payload(comment._id)
res = app.put_json_api(url, payload, auth=non_contrib.auth, expect_errors=True)
assert res.status_code == 403
assert res.json['errors'][0]['detail'] == exceptions.PermissionDenied.default_detail
def test_public_node_non_contrib_commenter_can_delete_comment(self, app, non_contrib):
project = ProjectFactory(is_public=True)
comment = CommentFactory(node=project, user=non_contrib)
url = '/{}comments/{}/'.format(API_BASE, comment._id)
res = app.delete_json_api(url, auth=non_contrib.auth)
assert res.status_code == 204
def test_registration_comment_has_usable_replies_relationship_link(self, app, user, registration_url, registration_comment_reply):
res = app.get(registration_url, auth=user.auth)
assert res.status_code == 200
comments_url = res.json['data']['relationships']['comments']['links']['related']['href']
comments_uri = test_utils.urlparse_drop_netloc(comments_url)
comments_res = app.get(comments_uri, auth=user.auth)
assert comments_res.status_code == 200
replies_url = comments_res.json['data'][0]['relationships']['replies']['links']['related']['href']
replies_uri = test_utils.urlparse_drop_netloc(replies_url)
replies_res = app.get(replies_uri, auth=user.auth)
node_url = comments_res.json['data'][0]['relationships']['node']['links']['related']['href']
node_uri = test_utils.urlparse_drop_netloc(node_url)
assert node_uri == registration_url
def test_registration_comment_has_usable_node_relationship_link(self, app, user, registration, registration_url, registration_comment_reply):
res = app.get(registration_url, auth=user.auth)
assert res.status_code == 200
comments_url = res.json['data']['relationships']['comments']['links']['related']['href']
comments_uri = test_utils.urlparse_drop_netloc(comments_url)
comments_res = app.get(comments_uri, auth=user.auth)
assert comments_res.status_code == 200
node_url = comments_res.json['data'][0]['relationships']['node']['links']['related']['href']
node_uri = test_utils.urlparse_drop_netloc(node_url)
node_res = app.get(node_uri, auth=user.auth)
assert registration._id in node_res.json['data']['id']
class TestFileCommentDetailView(CommentDetailMixin):
# private_project_with_comments
@pytest.fixture()
def private_project(self, user, contributor):
private_project = ProjectFactory.create(is_public=False, creator=user)
private_project.add_contributor(contributor, save=True)
return private_project
@pytest.fixture()
def file(self, user, private_project):
return test_utils.create_test_file(private_project, user)
@pytest.fixture()
def comment(self, user, private_project, file):
return CommentFactory(node=private_project, target=file.get_guid(), user=user)
@pytest.fixture()
def private_url(self, comment):
return '/{}comments/{}/'.format(API_BASE, comment._id)
@pytest.fixture()
def payload(self, comment, set_up_payload):
return set_up_payload(comment._id)
# public_project_with_comments
@pytest.fixture()
def public_project(self, user, contributor):
public_project = ProjectFactory.create(is_public=True, creator=user, comment_level='private')
public_project.add_contributor(contributor, save=True)
return public_project
@pytest.fixture()
def public_file(self, user, public_project):
return test_utils.create_test_file(public_project, user)
@pytest.fixture()
def public_comment(self, user, public_project, public_file):
return CommentFactory(node=public_project, target=public_file.get_guid(), user=user)
@pytest.fixture()
def public_comment_reply(self, user, public_comment, public_project):
reply_target = Guid.load(public_comment._id)
return CommentFactory(node=public_project, target=reply_target, user=user)
@pytest.fixture()
def public_url(self, public_comment):
return '/{}comments/{}/'.format(API_BASE, public_comment._id)
@pytest.fixture()
def public_comment_payload(self, public_comment, set_up_payload):
return set_up_payload(public_comment._id)
# registration_with_comments
@pytest.fixture()
def registration(self, user):
return RegistrationFactory(creator=user, comment_level='private')
@pytest.fixture()
def registration_file(self, user, registration):
return test_utils.create_test_file(registration, user)
@pytest.fixture()
def registration_comment(self, user, registration, registration_file):
return CommentFactory(node=registration, target=registration_file.get_guid(), user=user)
@pytest.fixture()
def comment_url(self, registration_comment):
return '/{}comments/{}/'.format(API_BASE, registration_comment._id)
@pytest.fixture()
def registration_comment_reply(self, user, registration, registration_comment):
reply_target = Guid.load(registration_comment._id)
return CommentFactory(node=registration, target=reply_target, user=user)
def test_file_comment_has_target_link_with_correct_type(self, app, public_url, public_file):
res = app.get(public_url)
url = res.json['data']['relationships']['target']['links']['related']['href']
expected_url = '/{}files/{}/'.format(API_BASE, public_file._id)
target_type = res.json['data']['relationships']['target']['links']['related']['meta']['type']
expected_type = 'files'
assert res.status_code == 200
assert urlparse(url).path == expected_url
assert target_type == expected_type
def test_public_node_non_contrib_commenter_can_update_file_comment(self, app, non_contrib, set_up_payload):
project = ProjectFactory(is_public=True)
test_file = test_utils.create_test_file(project, project.creator)
comment = CommentFactory(node=project, target=test_file.get_guid(), user=non_contrib)
url = '/{}comments/{}/'.format(API_BASE, comment._id)
payload = set_up_payload(comment._id)
res = app.put_json_api(url, payload, auth=non_contrib.auth)
assert res.status_code == 200
assert payload['data']['attributes']['content'] == res.json['data']['attributes']['content']
def test_public_node_non_contrib_commenter_cannot_update_own_file_comment_if_comment_level_private(self, app, non_contrib, set_up_payload):
project = ProjectFactory(is_public=True)
test_file = test_utils.create_test_file(project, project.creator)
comment = CommentFactory(node=project, target=test_file.get_guid(), user=non_contrib)
project.comment_level = 'private'
project.save()
url = '/{}comments/{}/'.format(API_BASE, comment._id)
payload = set_up_payload(comment._id)
res = app.put_json_api(url, payload, auth=non_contrib.auth, expect_errors=True)
assert res.status_code == 403
assert res.json['errors'][0]['detail'] == exceptions.PermissionDenied.default_detail
def test_public_node_non_contrib_commenter_can_delete_file_comment(self, app, non_contrib):
project = ProjectFactory(is_public=True, comment_level='public')
test_file = test_utils.create_test_file(project, project.creator)
comment = CommentFactory(node=project, target=test_file.get_guid(), user=non_contrib)
url = '/{}comments/{}/'.format(API_BASE, comment._id)
res = app.delete_json_api(url, auth=non_contrib.auth)
assert res.status_code == 204
def test_comment_detail_for_deleted_file_is_not_returned(self, app, user, private_project, file, private_url):
# Delete commented file
osfstorage = private_project.get_addon('osfstorage')
root_node = osfstorage.get_root()
file.delete()
res = app.get(private_url, auth=user.auth, expect_errors=True)
assert res.status_code == 404
class TestWikiCommentDetailView(CommentDetailMixin):
# private_project_with_comments
@pytest.fixture()
def private_project(self, user, contributor):
private_project = ProjectFactory.create(is_public=False, creator=user, comment_level='private')
private_project.add_contributor(contributor, save=True)
return private_project
@pytest.fixture()
def wiki(self, user, private_project):
with mock.patch('osf.models.AbstractNode.update_search'):
return NodeWikiFactory(node=private_project, user=user)
@pytest.fixture()
def comment(self, user, private_project, wiki):
return CommentFactory(node=private_project, target=Guid.load(wiki._id), user=user)
@pytest.fixture()
def private_url(self, comment):
return '/{}comments/{}/'.format(API_BASE, comment._id)
@pytest.fixture()
def payload(self, comment, set_up_payload):
return set_up_payload(comment._id)
# public_project_with_comments
@pytest.fixture()
def public_project(self, user, contributor):
public_project = ProjectFactory.create(is_public=True, creator=user, comment_level='private')
public_project.add_contributor(contributor, save=True)
return public_project
@pytest.fixture()
def public_wiki(self, user, public_project):
with mock.patch('osf.models.AbstractNode.update_search'):
return NodeWikiFactory(node=public_project, user=user)
@pytest.fixture()
def public_comment(self, user, public_project, public_wiki):
return CommentFactory(node=public_project, target=Guid.load(public_wiki._id), user=user)
@pytest.fixture()
def public_comment_reply(self, user, public_comment, public_project):
reply_target = Guid.load(public_comment._id)
return CommentFactory(node=public_project, target=reply_target, user=user)
@pytest.fixture()
def public_url(self, public_comment):
return '/{}comments/{}/'.format(API_BASE, public_comment._id)
@pytest.fixture()
def public_comment_payload(self, public_comment, set_up_payload):
return set_up_payload(public_comment._id)
# registration_with_comments
@pytest.fixture()
def registration(self, user):
return RegistrationFactory(creator=user, comment_level='private')
@pytest.fixture()
def registration_wiki(self, registration, user):
with mock.patch('osf.models.AbstractNode.update_search'):
return NodeWikiFactory(node=registration, user=user)
@pytest.fixture()
def registration_comment(self, user, registration, registration_wiki):
return CommentFactory(node=registration, target=Guid.load(registration_wiki._id), user=user)
@pytest.fixture()
def comment_url(self, registration_comment):
return '/{}comments/{}/'.format(API_BASE, registration_comment._id)
@pytest.fixture()
def registration_comment_reply(self, user, registration, registration_comment):
reply_target = Guid.load(registration_comment._id)
return CommentFactory(node=registration, target=reply_target, user=user)
def test_wiki_comment_has_target_link_with_correct_type(self, app, public_url, public_wiki):
res = app.get(public_url)
url = res.json['data']['relationships']['target']['links']['related']['href']
expected_url = public_wiki.get_absolute_url()
target_type = res.json['data']['relationships']['target']['links']['related']['meta']['type']
expected_type = 'wiki'
assert res.status_code == 200
assert url == expected_url
assert target_type == expected_type
def test_public_node_non_contrib_commenter_can_update_wiki_comment(self, app, user, non_contrib, set_up_payload):
project = ProjectFactory(is_public=True)
test_wiki = NodeWikiFactory(node=project, user=user)
comment = CommentFactory(node=project, target=Guid.load(test_wiki._id), user=non_contrib)
url = '/{}comments/{}/'.format(API_BASE, comment._id)
payload = set_up_payload(comment._id)
res = app.put_json_api(url, payload, auth=non_contrib.auth)
assert res.status_code == 200
assert payload['data']['attributes']['content'] == res.json['data']['attributes']['content']
def test_public_node_non_contrib_commenter_cannot_update_own_wiki_comment_if_comment_level_private(self, app, user, non_contrib, set_up_payload):
project = ProjectFactory(is_public=True)
test_wiki = NodeWikiFactory(node=project, user=user)
comment = CommentFactory(node=project, target=Guid.load(test_wiki._id), user=non_contrib)
project.comment_level = 'private'
project.save()
url = '/{}comments/{}/'.format(API_BASE, comment._id)
payload = set_up_payload(comment._id)
res = app.put_json_api(url, payload, auth=non_contrib.auth, expect_errors=True)
assert res.status_code == 403
assert res.json['errors'][0]['detail'] == exceptions.PermissionDenied.default_detail
def test_public_node_non_contrib_commenter_can_delete_wiki_comment(self, app, user, non_contrib):
project = ProjectFactory(is_public=True, comment_level='public')
test_wiki = NodeWikiFactory(node=project, user=user)
comment = CommentFactory(node=project, target=Guid.load(test_wiki._id), user=non_contrib)
url = '/{}comments/{}/'.format(API_BASE, comment._id)
res = app.delete_json_api(url, auth=non_contrib.auth)
assert res.status_code == 204
def test_comment_detail_for_deleted_wiki_is_not_returned(self, app, user, wiki, private_url, private_project):
# Delete commented wiki page
private_project.delete_node_wiki(wiki.page_name, core.Auth(user))
res = app.get(private_url, auth=user.auth, expect_errors=True)
assert res.status_code == 404
|
aaxelb/osf.io
|
api_tests/comments/views/test_comment_detail.py
|
Python
|
apache-2.0
| 39,369
|
from pymongo import MongoClient
import sys
import requests
import time
import dblayer
# client = MongoClient("mongodb://localhost:27017")
#
# db = client.TestUSGS
#vals = []
def doGetData():
sess = requests.Session()
dbobj = dblayer.classDBLayer()
#### TME: Get start time
start_time = time.time()
url = "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&minlatitude=-60.522&minlongitude=-166.992&maxlatitude=72.006&maxlongitude=-25.664&starttime=2015-01-01&endtime=2017-01-01&minmagnitude=4"
resp = None
resp_text=""
try:
r = requests.get(url)
resp = r.json()
except requests.exceptions.Timeout:
# Maybe set up for a retry, or continue in a retry loop
resp_text = "Timed out"
sys.exit(1)
except requests.exceptions.TooManyRedirects:
# Tell the user their URL was bad and try a different one
resp_text = "Too many redirects"
sys.exit(1)
except requests.exceptions.RequestException as e:
# catastrophic error. bail.
resp_text = str(e)
#print (e)
sys.exit(1)
dbobj.dropdb()
# db.usgsdata.drop()
if resp is not None:
dbobj.insertdata(resp["features"])
#db.usgsdata.insert_many(resp["features"])
#print ("Total " + str(db.usgsdata.count()) + " records downloaded." )
resp_text = "Total " + str(dbobj.count()) + " records downloaded."
#### TME: Elapsed time taken to download USGS data
elapsed = time.time() - start_time
line = "="*60
print (line)
print(str(elapsed) + " secs required to download " + str(dbobj.count()) + " records from USGS.")
print (line)
dbobj.closedb()
sess.close()
return resp_text
#sess = requests.Session()
#### TME: Get start time
#start_time = time.time()
#doGetData()
#### TME: Elapsed time taken to download USGS data
# elapsed = time.time() - start_time
# line = "="*60
# print (line)
# print(str(elapsed) + " secs required to download " + str(db.usgsdata.count()) + " records from USGS.")
# print (line)
#client.close()
|
Anveling/sp17-i524
|
project/S17-IO-3017/code/projectearth/getusgsdata.py
|
Python
|
apache-2.0
| 2,091
|
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from AlgorithmImports import *
#
# This is a demonstration algorithm. It trades UVXY.
# Dual Thrust alpha model is used to produce insights.
# Those input parameters have been chosen that gave acceptable results on a series
# of random backtests run for the period from Oct, 2016 till Feb, 2019.
#
class VIXDualThrustAlpha(QCAlgorithm):
def Initialize(self):
# -- STRATEGY INPUT PARAMETERS --
self.k1 = 0.63
self.k2 = 0.63
self.rangePeriod = 20
self.consolidatorBars = 30
# Settings
self.SetStartDate(2018, 10, 1)
self.SetSecurityInitializer(lambda security: security.SetFeeModel(ConstantFeeModel(0)))
self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin)
# Universe Selection
self.UniverseSettings.Resolution = Resolution.Minute # it's minute by default, but lets leave this param here
symbols = [Symbol.Create("SPY", SecurityType.Equity, Market.USA)]
self.SetUniverseSelection(ManualUniverseSelectionModel(symbols))
# Warming up
resolutionInTimeSpan = Extensions.ToTimeSpan(self.UniverseSettings.Resolution)
warmUpTimeSpan = Time.Multiply(resolutionInTimeSpan, self.consolidatorBars)
self.SetWarmUp(warmUpTimeSpan)
# Alpha Model
self.SetAlpha(DualThrustAlphaModel(self.k1, self.k2, self.rangePeriod, self.UniverseSettings.Resolution, self.consolidatorBars))
## Portfolio Construction
self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel())
## Execution
self.SetExecution(ImmediateExecutionModel())
## Risk Management
self.SetRiskManagement(MaximumDrawdownPercentPerSecurity(0.03))
class DualThrustAlphaModel(AlphaModel):
'''Alpha model that uses dual-thrust strategy to create insights
https://medium.com/@FMZ_Quant/dual-thrust-trading-strategy-2cc74101a626
or here:
https://www.quantconnect.com/tutorials/strategy-library/dual-thrust-trading-algorithm'''
def __init__(self,
k1,
k2,
rangePeriod,
resolution = Resolution.Daily,
barsToConsolidate = 1):
'''Initializes a new instance of the class
Args:
k1: Coefficient for upper band
k2: Coefficient for lower band
rangePeriod: Amount of last bars to calculate the range
resolution: The resolution of data sent into the EMA indicators
barsToConsolidate: If we want alpha to work on trade bars whose length is different
from the standard resolution - 1m 1h etc. - we need to pass this parameters along
with proper data resolution'''
# coefficient that used to determinte upper and lower borders of a breakout channel
self.k1 = k1
self.k2 = k2
# period the range is calculated over
self.rangePeriod = rangePeriod
# initialize with empty dict.
self.symbolDataBySymbol = dict()
# time for bars we make the calculations on
resolutionInTimeSpan = Extensions.ToTimeSpan(resolution)
self.consolidatorTimeSpan = Time.Multiply(resolutionInTimeSpan, barsToConsolidate)
# in 5 days after emission an insight is to be considered expired
self.period = timedelta(5)
def Update(self, algorithm, data):
insights = []
for symbol, symbolData in self.symbolDataBySymbol.items():
if not symbolData.IsReady:
continue
holding = algorithm.Portfolio[symbol]
price = algorithm.Securities[symbol].Price
# buying condition
# - (1) price is above upper line
# - (2) and we are not long. this is a first time we crossed the line lately
if price > symbolData.UpperLine and not holding.IsLong:
insightCloseTimeUtc = algorithm.UtcTime + self.period
insights.append(Insight.Price(symbol, insightCloseTimeUtc, InsightDirection.Up))
# selling condition
# - (1) price is lower that lower line
# - (2) and we are not short. this is a first time we crossed the line lately
if price < symbolData.LowerLine and not holding.IsShort:
insightCloseTimeUtc = algorithm.UtcTime + self.period
insights.append(Insight.Price(symbol, insightCloseTimeUtc, InsightDirection.Down))
return insights
def OnSecuritiesChanged(self, algorithm, changes):
# added
for symbol in [x.Symbol for x in changes.AddedSecurities]:
if symbol not in self.symbolDataBySymbol:
# add symbol/symbolData pair to collection
symbolData = self.SymbolData(symbol, self.k1, self.k2, self.rangePeriod, self.consolidatorTimeSpan)
self.symbolDataBySymbol[symbol] = symbolData
# register consolidator
algorithm.SubscriptionManager.AddConsolidator(symbol, symbolData.GetConsolidator())
# removed
for symbol in [x.Symbol for x in changes.RemovedSecurities]:
symbolData = self.symbolDataBySymbol.pop(symbol, None)
if symbolData is None:
algorithm.Error("Unable to remove data from collection: DualThrustAlphaModel")
else:
# unsubscribe consolidator from data updates
algorithm.SubscriptionManager.RemoveConsolidator(symbol, symbolData.GetConsolidator())
class SymbolData:
'''Contains data specific to a symbol required by this model'''
def __init__(self, symbol, k1, k2, rangePeriod, consolidatorResolution):
self.Symbol = symbol
self.rangeWindow = RollingWindow[TradeBar](rangePeriod)
self.consolidator = TradeBarConsolidator(consolidatorResolution)
def onDataConsolidated(sender, consolidated):
# add new tradebar to
self.rangeWindow.Add(consolidated)
if self.rangeWindow.IsReady:
hh = max([x.High for x in self.rangeWindow])
hc = max([x.Close for x in self.rangeWindow])
lc = min([x.Close for x in self.rangeWindow])
ll = min([x.Low for x in self.rangeWindow])
range = max([hh - lc, hc - ll])
self.UpperLine = consolidated.Close + k1 * range
self.LowerLine = consolidated.Close - k2 * range
# event fired at new consolidated trade bar
self.consolidator.DataConsolidated += onDataConsolidated
# Returns the interior consolidator
def GetConsolidator(self):
return self.consolidator
@property
def IsReady(self):
return self.rangeWindow.IsReady
|
StefanoRaggi/Lean
|
Algorithm.Python/Alphas/VIXDualThrustAlpha.py
|
Python
|
apache-2.0
| 7,584
|
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
"""Add audit tables
Revision ID: 53c3b75c86ed
Revises: 53ef72c8a867
Create Date: 2013-09-11 19:34:08.020226
"""
# revision identifiers, used by Alembic.
revision = '53c3b75c86ed'
down_revision = '53ef72c8a867'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('audits',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(length=250), nullable=False),
sa.Column('slug', sa.String(length=250), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('url', sa.String(length=250), nullable=True),
sa.Column('start_date', sa.DateTime(), nullable=True),
sa.Column('end_date', sa.DateTime(), nullable=True),
sa.Column('report_start_date', sa.Date(), nullable=True),
sa.Column('report_end_date', sa.Date(), nullable=True),
sa.Column('owner_id', sa.Integer(), nullable=True),
sa.Column('audit_firm', sa.String(length=250), nullable=True),
sa.Column('status', sa.Enum(u'Planned', u'In Progress', u'Manager Review', u'Ready for External Review', u'Completed'), nullable=False),
sa.Column('gdrive_evidence_folder', sa.String(length=250), nullable=True),
sa.Column('program_id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('modified_by_id', sa.Integer(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('context_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['context_id'], ['contexts.id'], ),
sa.ForeignKeyConstraint(['owner_id'], ['people.id'], ),
sa.ForeignKeyConstraint(['program_id'], ['programs.id'], ),
sa.PrimaryKeyConstraint('id')
)
def downgrade():
op.drop_table('audits')
|
prasannav7/ggrc-core
|
src/ggrc/migrations/versions/20130911193408_53c3b75c86ed_add_audit_tables.py
|
Python
|
apache-2.0
| 1,991
|
#!/usr/bin/env python
#
# Copyright (c) Greenplum Inc 2012. All Rights Reserved.
#
import unittest
from mock import patch
from gppylib.operations.filespace import is_filespace_configured, MoveTransFilespaceLocally
import os
import tempfile
import shutil
import hashlib
class FileSpaceTestCase(unittest.TestCase):
def setUp(self):
self.subject = MoveTransFilespaceLocally(None, None, None, None, None)
self.one_dir = tempfile.mkdtemp()
self.one_file = tempfile.mkstemp(dir=self.one_dir)
def tearDown(self):
if self.one_dir and os.path.exists(self.one_dir):
shutil.rmtree(self.one_dir)
@patch('os.path.exists', return_value=True)
def test00_is_filespace_configured(self, mock_obj):
self.assertEqual(is_filespace_configured(), True)
@patch('os.path.exists', return_value=False)
def test02_is_filespace_configured(self, mock_obj):
self.assertEqual(is_filespace_configured(), False)
def test_move_trans_filespace_locally(self):
with open(self.one_file[1], 'w') as f:
f.write("some text goes here")
m = hashlib.sha256()
m.update("some text goes here")
local_digest = m.hexdigest()
test_digest = self.subject.get_sha256(self.one_dir)
self.assertEquals(test_digest, local_digest)
|
edespino/gpdb
|
gpMgmt/bin/gppylib/operations/test/unit/test_unit_filespace.py
|
Python
|
apache-2.0
| 1,326
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import unittest
from unittest import mock
from parameterized import parameterized
from airflow.exceptions import AirflowException
from airflow.providers.amazon.aws.hooks.batch_client import BatchClientHook
from airflow.providers.amazon.aws.sensors.batch import BatchSensor
TASK_ID = 'batch_job_sensor'
JOB_ID = '8222a1c2-b246-4e19-b1b8-0039bb4407c0'
class TestBatchSensor(unittest.TestCase):
def setUp(self):
self.batch_sensor = BatchSensor(
task_id='batch_job_sensor',
job_id=JOB_ID,
)
@mock.patch.object(BatchClientHook, 'get_job_description')
def test_poke_on_success_state(self, mock_get_job_description):
mock_get_job_description.return_value = {'status': 'SUCCEEDED'}
self.assertTrue(self.batch_sensor.poke({}))
mock_get_job_description.assert_called_once_with(JOB_ID)
@mock.patch.object(BatchClientHook, 'get_job_description')
def test_poke_on_failure_state(self, mock_get_job_description):
mock_get_job_description.return_value = {'status': 'FAILED'}
with self.assertRaises(AirflowException) as e:
self.batch_sensor.poke({})
self.assertEqual('Batch sensor failed. AWS Batch job status: FAILED', str(e.exception))
mock_get_job_description.assert_called_once_with(JOB_ID)
@mock.patch.object(BatchClientHook, 'get_job_description')
def test_poke_on_invalid_state(self, mock_get_job_description):
mock_get_job_description.return_value = {'status': 'INVALID'}
with self.assertRaises(AirflowException) as e:
self.batch_sensor.poke({})
self.assertEqual('Batch sensor failed. Unknown AWS Batch job status: INVALID', str(e.exception))
mock_get_job_description.assert_called_once_with(JOB_ID)
@parameterized.expand(
[
('SUBMITTED',),
('PENDING',),
('RUNNABLE',),
('STARTING',),
('RUNNING',),
]
)
@mock.patch.object(BatchClientHook, 'get_job_description')
def test_poke_on_intermediate_state(self, job_status, mock_get_job_description):
mock_get_job_description.return_value = {'status': job_status}
self.assertFalse(self.batch_sensor.poke({}))
mock_get_job_description.assert_called_once_with(JOB_ID)
|
Acehaidrey/incubator-airflow
|
tests/providers/amazon/aws/sensors/test_batch.py
|
Python
|
apache-2.0
| 3,092
|
# -*- coding: utf-8 -*-
""" Print accepted talks not scheduled and not accepted talks which have been
scheduled.
"""
from collections import defaultdict
from optparse import make_option
import operator
import simplejson as json
from django.core.management.base import BaseCommand, CommandError
from django.core import urlresolvers
from conference import models
from conference import utils
from conference.models import TALK_TYPE, TALK_ADMIN_TYPE
from ...utils import (talk_schedule,
talk_type,
group_talks_by_type,
talk_track_title)
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--all_scheduled',
action='store_true',
dest='all_scheduled',
default=False,
help='Show a list of accepted talks which have not been scheduled',
),
make_option('--all_accepted',
action='store_true',
dest='all_accepted',
default=False,
help='Show a list of scheduled talks which have not been accepted',
),
)
def handle(self, *args, **options):
try:
conference = args[0]
except IndexError:
raise CommandError('conference not specified')
if not options['all_scheduled'] and not options['all_accepted']:
print('Please use either --all_scheduled or --all_accepted option.')
if options['all_scheduled']:
print('Checking that all accepted talks have been scheduled.')
talks = (models.Talk.objects.filter(conference=conference,
status='accepted'))
type_talks = group_talks_by_type(talks)
for type in type_talks:
for talk in type_talks[type]:
schedules = list(talk_schedule(talk))
if not schedules:
print('ERROR: {} (id: {}) "{}" is not '
'scheduled'.format(talk_type(talk), talk.id, talk))
elif len(schedules) > 1:
print('ERROR: {} (id: {}) "{}" is '
'scheduled {} times: {} in {}.'.format(talk_type(talk),
talk.id,
talk,
len(schedules),
schedules,
talk_track_title(talk)))
if options['all_accepted']:
print('Checking that all scheduled talks are accepted.')
talks = (models.Talk.objects.filter(conference=conference))
type_talks = group_talks_by_type(talks)
for type in type_talks:
for talk in type_talks[type]:
schedules = list(talk_schedule(talk))
if talk.status != 'accepted' and schedules:
print('ERROR: {} (id: {}) "{}" is scheduled but '
'not accepted.'.format(talk_type(talk),
talk.id,
talk))
|
artcz/epcon
|
p3/management/commands/check_schedule.py
|
Python
|
bsd-2-clause
| 3,428
|
from cassandra.cqlengine import connection
from stream_framework import settings
def setup_connection():
connection.setup(
hosts=settings.STREAM_CASSANDRA_HOSTS,
consistency=settings.STREAM_CASSANDRA_CONSISTENCY_LEVEL,
default_keyspace=settings.STREAM_DEFAULT_KEYSPACE,
**settings.CASSANDRA_DRIVER_KWARGS
)
|
smuser90/Stream-Framework
|
stream_framework/storage/cassandra/connection.py
|
Python
|
bsd-3-clause
| 349
|
# -*- coding: utf-8 -*-
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Custom importer to handle module load times. Wraps gsutil."""
from __future__ import absolute_import
import six
if six.PY3:
import builtins as builtin
else:
import __builtin__ as builtin
import atexit
from collections import OrderedDict
from operator import itemgetter
import os
import sys
import timeit
# This file will function in an identical manner to 'gsutil'. Instead of calling
# 'gsutil some_command' run 'gsutil_measure_imports some_command' from this test
# directory. When used, this file will change the MEASURING_TIME_ACTIVE variable
# in the gsutil.py file to True, signaling that the we are measuring import
# times. In all other cases, this variable will be set to False. This behavior
# will allow gsutil developers to analyze which modules are taking the most time
# to initialize. This is especially important because not all of those modules
# will be used. Therefore it is important to speed up the ones which are not
# used and take a significant amount of time to initialize (e.g. 100ms).
INITIALIZATION_TIMES = {}
real_importer = builtin.__import__
def get_sorted_initialization_times(items=10):
"""Returns a sorted OrderedDict.
The keys are module names and the values are the corresponding times taken to
import.
Args:
items: The number of items to return in the list.
Returns:
An OrderedDict object, sorting initialization times in increasing order.
"""
return OrderedDict(
sorted(INITIALIZATION_TIMES.items(), key=itemgetter(1),
reverse=True)[:items])
def print_sorted_initialization_times():
"""Prints the most expensive imports in descending order."""
print('\n***Most expensive imports***')
for item in get_sorted_initialization_times().iteritems():
print(item)
def timed_importer(name, *args, **kwargs):
"""Wrapper for the default Python import function.
Args:
name: The name of the module.
*args: A list of arguments passed to import.
**kwargs: A dictionary of arguments to pass to import.
Returns:
The value provided by the default import function.
"""
# TODO: Build an import tree to better understand which areas need more
# attention.
import_start_time = timeit.default_timer()
import_value = real_importer(name, *args, **kwargs)
import_end_time = timeit.default_timer()
INITIALIZATION_TIMES[name] = import_end_time - import_start_time
return import_value
builtin.__import__ = timed_importer
def initialize():
"""Initializes gsutil."""
sys.path.insert(0, os.path.abspath(os.path.join(sys.path[0], '..')))
import gsutil # pylint: disable=g-import-not-at-top
atexit.register(print_sorted_initialization_times)
gsutil.MEASURING_TIME_ACTIVE = True
gsutil.RunMain()
|
catapult-project/catapult
|
third_party/gsutil/test/gsutil_measure_imports.py
|
Python
|
bsd-3-clause
| 3,347
|
from osm import OSM, Node, Way
osm = OSM( "map.osm" )
fp = open("nodes.csv", "w")
for nodeid in osm.nodes.keys():
fp.write( "%s\n"%nodeid )
fp.close()
fp = open("map.csv", "w")
for wayid, way in osm.ways.iteritems():
if 'highway' in way.tags:
fp.write("%s,%s,%s,%f\n"%(wayid, way.fromv, way.tov, way.length(osm.nodes)))
fp.close()
|
brendannee/Bikesy-Backend
|
pygs/graphserver/ext/osm/simplify_osm.py
|
Python
|
bsd-3-clause
| 359
|
from django.core.management.base import BaseCommand
from django.db import models
from wagtail.wagtailcore.models import PageRevision, get_page_types
def replace_in_model(model, from_text, to_text):
text_field_names = [field.name for field in model._meta.fields if isinstance(field, models.TextField) or isinstance(field, models.CharField)]
updated_fields = []
for field in text_field_names:
field_value = getattr(model, field)
if field_value and (from_text in field_value):
updated_fields.append(field)
setattr(model, field, field_value.replace(from_text, to_text))
if updated_fields:
model.save(update_fields=updated_fields)
class Command(BaseCommand):
def handle(self, from_text, to_text, **options):
for revision in PageRevision.objects.filter(content_json__contains=from_text):
revision.content_json = revision.content_json.replace(from_text, to_text)
revision.save(update_fields=['content_json'])
for content_type in get_page_types():
print "scanning %s" % content_type.name
page_class = content_type.model_class()
try:
child_relation_names = [rel.get_accessor_name() for rel in page_class._meta.child_relations]
except AttributeError:
child_relation_names = []
for page in page_class.objects.all():
replace_in_model(page, from_text, to_text)
for child_rel in child_relation_names:
for child in getattr(page, child_rel).all():
replace_in_model(child, from_text, to_text)
|
suziesparkle/wagtail
|
wagtail/wagtailcore/management/commands/replace_text.py
|
Python
|
bsd-3-clause
| 1,661
|
# django imports
from django.contrib import admin
# lfs imports
from lfs.tax.models import Tax
admin.site.register(Tax)
|
leadbrick/django-lfs
|
lfs/tax/admin.py
|
Python
|
bsd-3-clause
| 122
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.six import StringIO
import sys
from django.apps import apps
from django.conf import settings
from django.core import checks
from django.core.checks import Error, Warning
from django.core.checks.model_checks import check_all_models
from django.core.checks.registry import CheckRegistry
from django.core.checks.compatibility.django_1_6_0 import check_1_6_compatibility
from django.core.checks.compatibility.django_1_7_0 import check_1_7_compatibility
from django.core.management.base import CommandError
from django.core.management import call_command
from django.db import models
from django.db.models.fields import NOT_PROVIDED
from django.test import TestCase
from django.test.utils import override_settings, override_system_checks
from django.utils.encoding import force_text
from .models import SimpleModel, Book
class DummyObj(object):
def __repr__(self):
return "obj"
class SystemCheckFrameworkTests(TestCase):
def test_register_and_run_checks(self):
calls = [0]
registry = CheckRegistry()
@registry.register()
def f(**kwargs):
calls[0] += 1
return [1, 2, 3]
errors = registry.run_checks()
self.assertEqual(errors, [1, 2, 3])
self.assertEqual(calls[0], 1)
class MessageTests(TestCase):
def test_printing(self):
e = Error("Message", hint="Hint", obj=DummyObj())
expected = "obj: Message\n\tHINT: Hint"
self.assertEqual(force_text(e), expected)
def test_printing_no_hint(self):
e = Error("Message", hint=None, obj=DummyObj())
expected = "obj: Message"
self.assertEqual(force_text(e), expected)
def test_printing_no_object(self):
e = Error("Message", hint="Hint", obj=None)
expected = "?: Message\n\tHINT: Hint"
self.assertEqual(force_text(e), expected)
def test_printing_with_given_id(self):
e = Error("Message", hint="Hint", obj=DummyObj(), id="ID")
expected = "obj: (ID) Message\n\tHINT: Hint"
self.assertEqual(force_text(e), expected)
def test_printing_field_error(self):
field = SimpleModel._meta.get_field('field')
e = Error("Error", hint=None, obj=field)
expected = "check_framework.SimpleModel.field: Error"
self.assertEqual(force_text(e), expected)
def test_printing_model_error(self):
e = Error("Error", hint=None, obj=SimpleModel)
expected = "check_framework.SimpleModel: Error"
self.assertEqual(force_text(e), expected)
def test_printing_manager_error(self):
manager = SimpleModel.manager
e = Error("Error", hint=None, obj=manager)
expected = "check_framework.SimpleModel.manager: Error"
self.assertEqual(force_text(e), expected)
class Django_1_6_0_CompatibilityChecks(TestCase):
@override_settings(TEST_RUNNER='myapp.test.CustomRunner')
def test_boolean_field_default_value(self):
# We patch the field's default value to trigger the warning
boolean_field = Book._meta.get_field('is_published')
old_default = boolean_field.default
try:
boolean_field.default = NOT_PROVIDED
errors = check_1_6_compatibility()
expected = [
checks.Warning(
'BooleanField does not have a default value.',
hint=('Django 1.6 changed the default value of BooleanField from False to None. '
'See https://docs.djangoproject.com/en/1.6/ref/models/fields/#booleanfield '
'for more information.'),
obj=boolean_field,
id='1_6.W002',
)
]
self.assertEqual(errors, expected)
finally:
# Restore the ``default``
boolean_field.default = old_default
class Django_1_7_0_CompatibilityChecks(TestCase):
@override_settings(MIDDLEWARE_CLASSES=('django.contrib.sessions.middleware.SessionMiddleware',))
def test_middleware_classes_overridden(self):
errors = check_1_7_compatibility()
self.assertEqual(errors, [])
def test_middleware_classes_not_set_explicitly(self):
# If MIDDLEWARE_CLASSES was set explicitly, temporarily pretend it wasn't
middleware_classes_overridden = False
if 'MIDDLEWARE_CLASSES' in settings._wrapped._explicit_settings:
middleware_classes_overridden = True
settings._wrapped._explicit_settings.remove('MIDDLEWARE_CLASSES')
try:
errors = check_1_7_compatibility()
expected = [
checks.Warning(
"MIDDLEWARE_CLASSES is not set.",
hint=("Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. "
"django.contrib.sessions.middleware.SessionMiddleware, "
"django.contrib.auth.middleware.AuthenticationMiddleware, and "
"django.contrib.messages.middleware.MessageMiddleware were removed from the defaults. "
"If your project needs these middleware then you should configure this setting."),
obj=None,
id='1_7.W001',
)
]
self.assertEqual(errors, expected)
finally:
# Restore settings value
if middleware_classes_overridden:
settings._wrapped._explicit_settings.add('MIDDLEWARE_CLASSES')
def simple_system_check(**kwargs):
simple_system_check.kwargs = kwargs
return []
def tagged_system_check(**kwargs):
tagged_system_check.kwargs = kwargs
return []
tagged_system_check.tags = ['simpletag']
def deployment_system_check(**kwargs):
deployment_system_check.kwargs = kwargs
return [checks.Warning('Deployment Check')]
deployment_system_check.tags = ['deploymenttag']
class CheckCommandTests(TestCase):
def setUp(self):
simple_system_check.kwargs = None
tagged_system_check.kwargs = None
self.old_stdout, self.old_stderr = sys.stdout, sys.stderr
sys.stdout, sys.stderr = StringIO(), StringIO()
def tearDown(self):
sys.stdout, sys.stderr = self.old_stdout, self.old_stderr
@override_system_checks([simple_system_check, tagged_system_check])
def test_simple_call(self):
call_command('check')
self.assertEqual(simple_system_check.kwargs, {'app_configs': None})
self.assertEqual(tagged_system_check.kwargs, {'app_configs': None})
@override_system_checks([simple_system_check, tagged_system_check])
def test_given_app(self):
call_command('check', 'auth', 'admin')
auth_config = apps.get_app_config('auth')
admin_config = apps.get_app_config('admin')
self.assertEqual(simple_system_check.kwargs, {'app_configs': [auth_config, admin_config]})
self.assertEqual(tagged_system_check.kwargs, {'app_configs': [auth_config, admin_config]})
@override_system_checks([simple_system_check, tagged_system_check])
def test_given_tag(self):
call_command('check', tags=['simpletag'])
self.assertEqual(simple_system_check.kwargs, None)
self.assertEqual(tagged_system_check.kwargs, {'app_configs': None})
@override_system_checks([simple_system_check, tagged_system_check])
def test_invalid_tag(self):
self.assertRaises(CommandError, call_command, 'check', tags=['missingtag'])
@override_system_checks([simple_system_check])
def test_list_tags_empty(self):
call_command('check', list_tags=True)
self.assertEqual('\n', sys.stdout.getvalue())
@override_system_checks([tagged_system_check])
def test_list_tags(self):
call_command('check', list_tags=True)
self.assertEqual('simpletag\n', sys.stdout.getvalue())
@override_system_checks([tagged_system_check], deployment_checks=[deployment_system_check])
def test_list_deployment_check_omitted(self):
call_command('check', list_tags=True)
self.assertEqual('simpletag\n', sys.stdout.getvalue())
@override_system_checks([tagged_system_check], deployment_checks=[deployment_system_check])
def test_list_deployment_check_included(self):
call_command('check', deploy=True, list_tags=True)
self.assertEqual('deploymenttag\nsimpletag\n', sys.stdout.getvalue())
@override_system_checks([tagged_system_check], deployment_checks=[deployment_system_check])
def test_tags_deployment_check_omitted(self):
msg = 'There is no system check with the "deploymenttag" tag.'
with self.assertRaisesMessage(CommandError, msg):
call_command('check', tags=['deploymenttag'])
@override_system_checks([tagged_system_check], deployment_checks=[deployment_system_check])
def test_tags_deployment_check_included(self):
call_command('check', deploy=True, tags=['deploymenttag'])
self.assertIn('Deployment Check', sys.stderr.getvalue())
def custom_error_system_check(app_configs, **kwargs):
return [
Error(
'Error',
hint=None,
id='myerrorcheck.E001',
)
]
def custom_warning_system_check(app_configs, **kwargs):
return [
Warning(
'Warning',
hint=None,
id='mywarningcheck.E001',
)
]
class SilencingCheckTests(TestCase):
def setUp(self):
self.old_stdout, self.old_stderr = sys.stdout, sys.stderr
self.stdout, self.stderr = StringIO(), StringIO()
sys.stdout, sys.stderr = self.stdout, self.stderr
def tearDown(self):
sys.stdout, sys.stderr = self.old_stdout, self.old_stderr
@override_settings(SILENCED_SYSTEM_CHECKS=['myerrorcheck.E001'])
@override_system_checks([custom_error_system_check])
def test_silenced_error(self):
out = StringIO()
err = StringIO()
try:
call_command('check', stdout=out, stderr=err)
except CommandError:
self.fail("The mycheck.E001 check should be silenced.")
self.assertEqual(out.getvalue(), '')
self.assertEqual(
err.getvalue(),
'System check identified some issues:\n\n'
'ERRORS:\n'
'?: (myerrorcheck.E001) Error\n\n'
'System check identified 1 issue (0 silenced).\n'
)
@override_settings(SILENCED_SYSTEM_CHECKS=['mywarningcheck.E001'])
@override_system_checks([custom_warning_system_check])
def test_silenced_warning(self):
out = StringIO()
err = StringIO()
try:
call_command('check', stdout=out, stderr=err)
except CommandError:
self.fail("The mycheck.E001 check should be silenced.")
self.assertEqual(out.getvalue(), 'System check identified no issues (1 silenced).\n')
self.assertEqual(err.getvalue(), '')
class CheckFrameworkReservedNamesTests(TestCase):
def setUp(self):
self.current_models = apps.all_models[__package__]
self.saved_models = set(self.current_models)
def tearDown(self):
for model in (set(self.current_models) - self.saved_models):
del self.current_models[model]
apps.clear_cache()
@override_settings(SILENCED_SYSTEM_CHECKS=['models.E020'])
def test_model_check_method_not_shadowed(self):
class ModelWithAttributeCalledCheck(models.Model):
check = 42
class ModelWithFieldCalledCheck(models.Model):
check = models.IntegerField()
class ModelWithRelatedManagerCalledCheck(models.Model):
pass
class ModelWithDescriptorCalledCheck(models.Model):
check = models.ForeignKey(ModelWithRelatedManagerCalledCheck)
article = models.ForeignKey(ModelWithRelatedManagerCalledCheck, related_name='check')
expected = [
Error(
"The 'ModelWithAttributeCalledCheck.check()' class method is "
"currently overridden by 42.",
hint=None,
obj=ModelWithAttributeCalledCheck,
id='models.E020'
),
Error(
"The 'ModelWithRelatedManagerCalledCheck.check()' class method is "
"currently overridden by %r." % ModelWithRelatedManagerCalledCheck.check,
hint=None,
obj=ModelWithRelatedManagerCalledCheck,
id='models.E020'
),
Error(
"The 'ModelWithDescriptorCalledCheck.check()' class method is "
"currently overridden by %r." % ModelWithDescriptorCalledCheck.check,
hint=None,
obj=ModelWithDescriptorCalledCheck,
id='models.E020'
),
]
self.assertEqual(check_all_models(), expected)
|
benjaminrigaud/django
|
tests/check_framework/tests.py
|
Python
|
bsd-3-clause
| 12,962
|
##########################################################################
#
# Copyright (c) 2019, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import unittest
import imath
import IECore
import Gaffer
import GafferTest
class NameValuePlugTest( GafferTest.TestCase ) :
def assertPlugSerialises( self, plug ):
s = Gaffer.ScriptNode()
s["n"] = Gaffer.Node()
s["n"]["p"] = plug
s2 = Gaffer.ScriptNode()
s2.execute( s.serialise() )
self.assertEqual( s2["n"]["p"].getName(), plug.getName() )
self.assertEqual( s2["n"]["p"].direction(), plug.direction() )
self.assertEqual( s2["n"]["p"].getFlags(), plug.getFlags() )
self.assertEqual( s2["n"]["p"].keys(), plug.keys() )
self.assertEqual( s2["n"]["p"]["value"].getValue(), plug["value"].getValue() )
self.assertEqual( s2["n"]["p"]["value"].defaultValue(), plug["value"].defaultValue() )
self.assertEqual( s2["n"]["p"]["name"].getValue(), plug["name"].getValue() )
self.assertEqual( s2["n"]["p"]["name"].defaultValue(), plug["name"].defaultValue() )
if "enable" in plug.keys():
self.assertEqual( s2["n"]["p"]["enable"].getValue(), plug["enable"].getValue() )
self.assertEqual( s2["n"]["p"]["enable"].defaultValue(), plug["enable"].defaultValue() )
if isinstance( plug, Gaffer.IntPlug ):
self.assertEqual( s2["n"]["p"]["value"].minValue(), plug.minValue() )
self.assertEqual( s2["n"]["p"]["value"].maxValue(), plug.maxValue() )
def assertCounterpart( self, plug ):
p2 = plug.createCounterpart( "testName", Gaffer.Plug.Direction.Out )
self.assertEqual( p2.getName(), "testName" )
self.assertEqual( p2.direction(), Gaffer.Plug.Direction.Out )
self.assertEqual( p2.getFlags(), plug.getFlags() )
self.assertEqual( p2.keys(), plug.keys() )
if "value" in plug.keys():
self.assertEqual( p2["value"].getValue(), plug["value"].getValue() )
self.assertEqual( p2["value"].defaultValue(), plug["value"].defaultValue() )
if "name" in plug.keys():
self.assertEqual( p2["name"].getValue(), plug["name"].getValue() )
self.assertEqual( p2["name"].defaultValue(), plug["name"].defaultValue() )
if "enable" in plug.keys():
self.assertEqual( p2["enable"].getValue(), plug["enable"].getValue() )
self.assertEqual( p2["enable"].defaultValue(), plug["enable"].defaultValue() )
if isinstance( plug, Gaffer.IntPlug ):
self.assertEqual( p2.minValue(), plug.minValue() )
self.assertEqual( p2.maxValue(), plug.maxValue() )
def test( self ) :
constructed = {}
constructed["defaults"] = {}
constructed["specified"] = {}
constructed["defaults"]["empty"] = Gaffer.NameValuePlug()
constructed["defaults"]["partialEmpty"] = Gaffer.NameValuePlug()
constructed["defaults"]["partialEmpty"].addChild( Gaffer.StringPlug( "name", defaultValue = "key") )
# Note that if we specify the direction and flags without specifying argument names, this is ambiguous
# with the later forms of the constructor. I guess this is OK since the old serialised forms
# of MemberPlug do include the argument names, and we want to deprecate this form anyway
constructed["specified"]["empty"] = Gaffer.NameValuePlug( "foo", direction = Gaffer.Plug.Direction.Out, flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
constructed["specified"]["partialEmpty"] = Gaffer.NameValuePlug( "foo", direction = Gaffer.Plug.Direction.Out, flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
constructed["specified"]["partialEmpty"].addChild( Gaffer.StringPlug( "name", direction = Gaffer.Plug.Direction.Out, flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic, defaultValue = "key" ) )
constructed["defaults"]["fromData"] = Gaffer.NameValuePlug( "key", IECore.IntData(42) )
constructed["specified"]["fromData"] = Gaffer.NameValuePlug( "key", IECore.IntData(42), "foo", Gaffer.Plug.Direction.Out, Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
constructed["defaults"]["fromPlug"] = Gaffer.NameValuePlug( "key", Gaffer.IntPlug( minValue = -3, maxValue = 5) )
constructed["specified"]["fromPlug"] = Gaffer.NameValuePlug( "key", Gaffer.IntPlug( direction = Gaffer.Plug.Direction.Out, flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic ), "foo" )
constructed["defaults"]["fromDataEnable"] = Gaffer.NameValuePlug( "key", IECore.IntData(42), True )
constructed["specified"]["fromDataEnable"] = Gaffer.NameValuePlug( "key", IECore.IntData(42), True, "foo", Gaffer.Plug.Direction.Out, Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
constructed["defaults"]["fromPlugEnable"] = Gaffer.NameValuePlug( "key", Gaffer.IntPlug(), True )
constructed["specified"]["fromPlugEnable"] = Gaffer.NameValuePlug( "key", Gaffer.IntPlug( minValue = -7, maxValue = 15, direction = Gaffer.Plug.Direction.Out, flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic ) , True, "foo" )
for k in [ "empty", "fromData", "fromPlug", "fromDataEnable", "fromPlugEnable" ]:
defa = constructed["defaults"][k]
spec = constructed["specified"][k]
numChildren = 3 if "Enable" in k else 2
if k == "empty":
numChildren = 0
self.assertEqual( len( spec.children() ), numChildren )
self.assertEqual( len( defa.children() ), numChildren )
self.assertEqual( defa.getName(), "NameValuePlug" )
self.assertEqual( spec.getName(), "foo" )
self.assertEqual( defa.direction(), Gaffer.Plug.Direction.In )
self.assertEqual( spec.direction(), Gaffer.Plug.Direction.Out )
self.assertEqual( defa.getFlags(), Gaffer.Plug.Flags.Default )
self.assertEqual( spec.getFlags(), Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
if k == "empty":
self.assertNotIn( "name", defa )
self.assertNotIn( "name", spec )
self.assertNotIn( "value", defa )
self.assertNotIn( "value", spec )
elif k == "partialEmpty":
self.assertEqual( defa["name"].getValue(), "key" )
self.assertEqual( spec["name"].getValue(), "key" )
self.assertNotIn( "value", defa )
self.assertNotIn( "value", spec )
else:
self.assertEqual( defa["name"].getValue(), "key" )
self.assertEqual( spec["name"].getValue(), "key" )
if "fromPlug" in k:
self.assertEqual( defa["value"].getValue(), 0 )
self.assertEqual( spec["value"].getValue(), 0 )
else:
self.assertEqual( defa["value"].getValue(), 42 )
self.assertEqual( spec["value"].getValue(), 42 )
if k == "empty":
# A completely empty NameValuePlug is invalid, but we have to partially
# support it because old serialisation code will create these before
# the addChild's run to create name and value
self.assertCounterpart( defa )
self.assertCounterpart( spec )
# We shouldn't ever serialise invalid plugs though - if the children
# haven't been created by the time we try to serialise, that's a bug
self.assertRaises( RuntimeError, self.assertPlugSerialises, spec )
elif k == "partialEmpty":
# A NameValuePlug with a name but no value, on the other hand, is just
# broken
self.assertRaises( RuntimeError, self.assertPlugSerialises, spec )
self.assertRaises( RuntimeError, self.assertCounterpart, defa )
self.assertRaises( RuntimeError, self.assertCounterpart, spec )
else:
self.assertPlugSerialises( spec )
self.assertCounterpart( defa )
self.assertCounterpart( spec )
def testBasicRepr( self ) :
p = Gaffer.NameValuePlug( "key", IECore.StringData( "value" ) )
self.assertEqual(
repr( p ),
'Gaffer.NameValuePlug( "key", Gaffer.StringPlug( "value", defaultValue = \'value\', ), "NameValuePlug", Gaffer.Plug.Flags.Default )'
)
def testEmptyPlugRepr( self ) :
# Use the deprecated constructor to create a NameValuePlug without name or value
p = Gaffer.NameValuePlug( "mm", direction = Gaffer.Plug.Direction.Out, flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
self.assertRaises( RuntimeError, repr, p )
def testValueTypes( self ) :
for v in [
IECore.FloatVectorData( [ 1, 2, 3 ] ),
IECore.IntVectorData( [ 1, 2, 3 ] ),
IECore.StringVectorData( [ "1", "2", "3" ] ),
IECore.V3fVectorData( [ imath.V3f( x ) for x in range( 1, 5 ) ] ),
IECore.Color3fVectorData( [ imath.Color3f( x ) for x in range( 1, 5 ) ] ),
IECore.M44fVectorData( [ imath.M44f() * x for x in range( 1, 5 ) ] ),
IECore.M33fVectorData( [ imath.M33f() * x for x in range( 1, 5 ) ] ),
IECore.V2iVectorData( [ imath.V2i( x ) for x in range( 1, 5 ) ] ),
IECore.V3fData( imath.V3f( 1, 2, 3 ) ),
IECore.V2fData( imath.V2f( 1, 2 ) ),
IECore.M44fData( imath.M44f( *range(16) ) ),
IECore.Box2fData( imath.Box2f( imath.V2f( 0, 1 ), imath.V2f( 1, 2 ) ) ),
IECore.Box2iData( imath.Box2i( imath.V2i( -1, 10 ), imath.V2i( 11, 20 ) ) ),
IECore.Box3fData( imath.Box3f( imath.V3f( 0, 1, 2 ), imath.V3f( 3, 4, 5 ) ) ),
IECore.Box3iData( imath.Box3i( imath.V3i( 0, 1, 2 ), imath.V3i( 3, 4, 5 ) ) ),
IECore.InternedStringVectorData( [ "a", "b" ] )
]:
if 'value' in dir( v ):
expected = v.value
else:
expected = v
self.assertEqual( expected, Gaffer.NameValuePlug( "test", v )["value"].getValue() )
def testTransformPlug( self ) :
p = Gaffer.NameValuePlug( "a", Gaffer.TransformPlug() )
self.assertEqual( p["value"].matrix(), imath.M44f() )
def testAdditionalChildrenRejected( self ) :
m = Gaffer.NameValuePlug( "a", IECore.IntData( 10 ) )
self.assertRaises( RuntimeError, m.addChild, Gaffer.IntPlug() )
self.assertRaises( RuntimeError, m.addChild, Gaffer.StringPlug( "name" ) )
self.assertRaises( RuntimeError, m.addChild, Gaffer.IntPlug( "name" ) )
self.assertRaises( RuntimeError, m.addChild, Gaffer.IntPlug( "value" ) )
def testDefaultValues( self ) :
m = Gaffer.NameValuePlug( "a", IECore.IntData( 10 ) )
self.assertTrue( m["value"].defaultValue(), 10 )
self.assertTrue( m["value"].getValue(), 10 )
self.assertTrue( m["name"].defaultValue(), "a" )
self.assertTrue( m["name"].getValue(), "a" )
m = Gaffer.NameValuePlug( "b", IECore.FloatData( 20 ) )
self.assertTrue( m["value"].defaultValue(), 20 )
self.assertTrue( m["value"].getValue(), 20 )
self.assertTrue( m["name"].defaultValue(), "b" )
self.assertTrue( m["name"].getValue(), "b" )
m = Gaffer.NameValuePlug( "c", IECore.StringData( "abc" ) )
self.assertTrue( m["value"].defaultValue(), "abc" )
self.assertTrue( m["value"].getValue(), "abc" )
self.assertTrue( m["name"].defaultValue(), "c" )
self.assertTrue( m["name"].getValue(), "c" )
def testNonValuePlugs( self ) :
p1 = Gaffer.NameValuePlug( "name", Gaffer.Plug(), name = "p1", defaultEnabled = False )
p2 = p1.createCounterpart( "p2", Gaffer.Plug.Direction.In )
self.assertTrue( p1.settable() )
self.assertTrue( p2.settable() )
p2.setInput( p1 )
self.assertEqual( p2["name"].getInput(), p1["name"] )
self.assertEqual( p2["value"].getInput(), p1["value"] )
self.assertTrue( p1.settable() )
self.assertFalse( p2.settable() )
p2.setInput( None )
self.assertTrue( p2.settable() )
self.assertTrue( p1.isSetToDefault() )
p1["name"].setValue( "nonDefault" )
self.assertFalse( p1.isSetToDefault() )
p1.setToDefault()
self.assertTrue( p1.isSetToDefault() )
p1["name"].setValue( "nonDefault" )
p1["enabled"].setValue( True )
p2.setFrom( p1 )
self.assertEqual( p2["name"].getValue(), p1["name"].getValue() )
self.assertEqual( p2["enabled"].getValue(), p1["enabled"].getValue() )
self.assertEqual( p1.hash(), p2.hash() )
p2["enabled"].setValue( False )
self.assertNotEqual( p1.hash(), p2.hash() )
def testDynamicFlags( self ) :
def assertFlags( script ) :
self.assertEqual( script["n"]["user"]["p1"].getFlags(), Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
self.assertEqual( script["n"]["user"]["p1"]["name"].getFlags(), Gaffer.Plug.Flags.Default )
self.assertEqual( script["n"]["user"]["p1"]["value"].getFlags(), Gaffer.Plug.Flags.Default )
c = script["n"]["user"]["p1"].createCounterpart( "c", Gaffer.Plug.Direction.In )
self.assertEqual( c.getFlags(), script["n"]["user"]["p1"].getFlags() )
self.assertEqual( script["n"]["user"]["p2"].getFlags(), Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
self.assertEqual( script["n"]["user"]["p2"]["name"].getFlags(), Gaffer.Plug.Flags.Default )
self.assertEqual( script["n"]["user"]["p2"]["value"].getFlags(), Gaffer.Plug.Flags.Default )
self.assertEqual( script["n"]["user"]["p2"]["enabled"].getFlags(), Gaffer.Plug.Flags.Default )
c = script["n"]["user"]["p2"].createCounterpart( "c", Gaffer.Plug.Direction.In )
self.assertEqual( c.getFlags(), script["n"]["user"]["p2"].getFlags() )
s = Gaffer.ScriptNode()
s["n"] = Gaffer.Node()
s["n"]["user"]["p1"] = Gaffer.NameValuePlug( "name1", Gaffer.IntPlug( defaultValue = 1 ), flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
s["n"]["user"]["p2"] = Gaffer.NameValuePlug( "name2", Gaffer.IntPlug( defaultValue = 1 ), defaultEnabled = False, flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
assertFlags( s )
s2 = Gaffer.ScriptNode()
s2.execute( s.serialise() )
assertFlags( s2 )
s3 = Gaffer.ScriptNode()
s3.execute( s2.serialise() )
assertFlags( s3 )
if __name__ == "__main__":
unittest.main()
|
hradec/gaffer
|
python/GafferTest/NameValuePlugTest.py
|
Python
|
bsd-3-clause
| 14,881
|
# Authors: Lars Buitinck
# Dan Blanchard <dblanchard@ets.org>
# License: BSD 3 clause
from random import Random
import numpy as np
import scipy.sparse as sp
from numpy.testing import assert_array_equal
from numpy.testing import assert_allclose
import pytest
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_selection import SelectKBest, chi2
@pytest.mark.parametrize("sparse", (True, False))
@pytest.mark.parametrize("dtype", (int, np.float32, np.int16))
@pytest.mark.parametrize("sort", (True, False))
@pytest.mark.parametrize("iterable", (True, False))
def test_dictvectorizer(sparse, dtype, sort, iterable):
D = [{"foo": 1, "bar": 3}, {"bar": 4, "baz": 2}, {"bar": 1, "quux": 1, "quuux": 2}]
v = DictVectorizer(sparse=sparse, dtype=dtype, sort=sort)
X = v.fit_transform(iter(D) if iterable else D)
assert sp.issparse(X) == sparse
assert X.shape == (3, 5)
assert X.sum() == 14
assert v.inverse_transform(X) == D
if sparse:
# CSR matrices can't be compared for equality
assert_array_equal(X.A, v.transform(iter(D) if iterable else D).A)
else:
assert_array_equal(X, v.transform(iter(D) if iterable else D))
if sort:
assert v.feature_names_ == sorted(v.feature_names_)
# TODO: Remove in 1.2 when get_feature_names is removed.
@pytest.mark.filterwarnings("ignore::FutureWarning:sklearn")
@pytest.mark.parametrize("get_names", ["get_feature_names", "get_feature_names_out"])
def test_feature_selection(get_names):
# make two feature dicts with two useful features and a bunch of useless
# ones, in terms of chi2
d1 = dict([("useless%d" % i, 10) for i in range(20)], useful1=1, useful2=20)
d2 = dict([("useless%d" % i, 10) for i in range(20)], useful1=20, useful2=1)
for indices in (True, False):
v = DictVectorizer().fit([d1, d2])
X = v.transform([d1, d2])
sel = SelectKBest(chi2, k=2).fit(X, [0, 1])
v.restrict(sel.get_support(indices=indices), indices=indices)
assert_array_equal(getattr(v, get_names)(), ["useful1", "useful2"])
# TODO: Remove in 1.2 when get_feature_names is removed.
@pytest.mark.filterwarnings("ignore::FutureWarning:sklearn")
@pytest.mark.parametrize("get_names", ["get_feature_names", "get_feature_names_out"])
def test_one_of_k(get_names):
D_in = [
{"version": "1", "ham": 2},
{"version": "2", "spam": 0.3},
{"version=3": True, "spam": -1},
]
v = DictVectorizer()
X = v.fit_transform(D_in)
assert X.shape == (3, 5)
D_out = v.inverse_transform(X)
assert D_out[0] == {"version=1": 1, "ham": 2}
names = getattr(v, get_names)()
assert "version=2" in names
assert "version" not in names
# TODO: Remove in 1.2 when get_feature_names is removed.
@pytest.mark.filterwarnings("ignore::FutureWarning:sklearn")
@pytest.mark.parametrize("get_names", ["get_feature_names", "get_feature_names_out"])
def test_iterable_value(get_names):
D_names = ["ham", "spam", "version=1", "version=2", "version=3"]
X_expected = [
[2.0, 0.0, 2.0, 1.0, 0.0],
[0.0, 0.3, 0.0, 1.0, 0.0],
[0.0, -1.0, 0.0, 0.0, 1.0],
]
D_in = [
{"version": ["1", "2", "1"], "ham": 2},
{"version": "2", "spam": 0.3},
{"version=3": True, "spam": -1},
]
v = DictVectorizer()
X = v.fit_transform(D_in)
X = X.toarray()
assert_array_equal(X, X_expected)
D_out = v.inverse_transform(X)
assert D_out[0] == {"version=1": 2, "version=2": 1, "ham": 2}
names = getattr(v, get_names)()
assert_array_equal(names, D_names)
def test_iterable_not_string_error():
error_value = (
"Unsupported type <class 'int'> in iterable value. "
"Only iterables of string are supported."
)
D2 = [{"foo": "1", "bar": "2"}, {"foo": "3", "baz": "1"}, {"foo": [1, "three"]}]
v = DictVectorizer(sparse=False)
with pytest.raises(TypeError) as error:
v.fit(D2)
assert str(error.value) == error_value
def test_mapping_error():
error_value = (
"Unsupported value type <class 'dict'> "
"for foo: {'one': 1, 'three': 3}.\n"
"Mapping objects are not supported."
)
D2 = [
{"foo": "1", "bar": "2"},
{"foo": "3", "baz": "1"},
{"foo": {"one": 1, "three": 3}},
]
v = DictVectorizer(sparse=False)
with pytest.raises(TypeError) as error:
v.fit(D2)
assert str(error.value) == error_value
def test_unseen_or_no_features():
D = [{"camelot": 0, "spamalot": 1}]
for sparse in [True, False]:
v = DictVectorizer(sparse=sparse).fit(D)
X = v.transform({"push the pram a lot": 2})
if sparse:
X = X.toarray()
assert_array_equal(X, np.zeros((1, 2)))
X = v.transform({})
if sparse:
X = X.toarray()
assert_array_equal(X, np.zeros((1, 2)))
try:
v.transform([])
except ValueError as e:
assert "empty" in str(e)
def test_deterministic_vocabulary():
# Generate equal dictionaries with different memory layouts
items = [("%03d" % i, i) for i in range(1000)]
rng = Random(42)
d_sorted = dict(items)
rng.shuffle(items)
d_shuffled = dict(items)
# check that the memory layout does not impact the resulting vocabulary
v_1 = DictVectorizer().fit([d_sorted])
v_2 = DictVectorizer().fit([d_shuffled])
assert v_1.vocabulary_ == v_2.vocabulary_
def test_n_features_in():
# For vectorizers, n_features_in_ does not make sense and does not exist.
dv = DictVectorizer()
assert not hasattr(dv, "n_features_in_")
d = [{"foo": 1, "bar": 2}, {"foo": 3, "baz": 1}]
dv.fit(d)
assert not hasattr(dv, "n_features_in_")
# TODO: Remove in 1.2 when get_feature_names is removed
def test_feature_union_get_feature_names_deprecated():
"""Check that get_feature_names is deprecated"""
D_in = [{"version": "1", "ham": 2}, {"version": "2", "spam": 0.3}]
v = DictVectorizer().fit(D_in)
msg = "get_feature_names is deprecated in 1.0"
with pytest.warns(FutureWarning, match=msg):
v.get_feature_names()
def test_dictvectorizer_dense_sparse_equivalence():
"""Check the equivalence between between sparse and dense DictVectorizer.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/19978
"""
movie_entry_fit = [
{"category": ["thriller", "drama"], "year": 2003},
{"category": ["animation", "family"], "year": 2011},
{"year": 1974},
]
movie_entry_transform = [{"category": ["thriller"], "unseen_feature": "3"}]
dense_vectorizer = DictVectorizer(sparse=False)
sparse_vectorizer = DictVectorizer(sparse=True)
dense_vector_fit = dense_vectorizer.fit_transform(movie_entry_fit)
sparse_vector_fit = sparse_vectorizer.fit_transform(movie_entry_fit)
assert not sp.issparse(dense_vector_fit)
assert sp.issparse(sparse_vector_fit)
assert_allclose(dense_vector_fit, sparse_vector_fit.toarray())
dense_vector_transform = dense_vectorizer.transform(movie_entry_transform)
sparse_vector_transform = sparse_vectorizer.transform(movie_entry_transform)
assert not sp.issparse(dense_vector_transform)
assert sp.issparse(sparse_vector_transform)
assert_allclose(dense_vector_transform, sparse_vector_transform.toarray())
dense_inverse_transform = dense_vectorizer.inverse_transform(dense_vector_transform)
sparse_inverse_transform = sparse_vectorizer.inverse_transform(
sparse_vector_transform
)
expected_inverse = [{"category=thriller": 1.0}]
assert dense_inverse_transform == expected_inverse
assert sparse_inverse_transform == expected_inverse
def test_dict_vectorizer_unsupported_value_type():
"""Check that we raise an error when the value associated to a feature
is not supported.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/19489
"""
class A:
pass
vectorizer = DictVectorizer(sparse=True)
X = [{"foo": A()}]
err_msg = "Unsupported value Type"
with pytest.raises(TypeError, match=err_msg):
vectorizer.fit_transform(X)
def test_dict_vectorizer_get_feature_names_out():
"""Check that integer feature names are converted to strings in
feature_names_out."""
X = [{1: 2, 3: 4}, {2: 4}]
dv = DictVectorizer(sparse=False).fit(X)
feature_names = dv.get_feature_names_out()
assert isinstance(feature_names, np.ndarray)
assert feature_names.dtype == object
assert_array_equal(feature_names, ["1", "2", "3"])
|
manhhomienbienthuy/scikit-learn
|
sklearn/feature_extraction/tests/test_dict_vectorizer.py
|
Python
|
bsd-3-clause
| 8,675
|
import warnings
import os
import nibabel as nb
import numpy as np
from ...utils.misc import package_check
have_nipy = True
try:
package_check('nipy')
except Exception, e:
have_nipy = False
else:
import nipy.modalities.fmri.design_matrix as dm
import nipy.labs.glm.glm as GLM
if have_nipy:
try:
BlockParadigm = dm.BlockParadigm
except AttributeError:
from nipy.modalities.fmri.experimental_paradigm import BlockParadigm
from ..base import (BaseInterface, TraitedSpec, traits, File, OutputMultiPath,
BaseInterfaceInputSpec, isdefined)
class FitGLMInputSpec(BaseInterfaceInputSpec):
session_info = traits.List(minlen=1, maxlen=1, mandatory=True,
desc=('Session specific information generated by'
' ``modelgen.SpecifyModel``, FitGLM does '
'not support multiple runs uless they are '
'concatenated (see SpecifyModel options)'))
hrf_model = traits.Enum('Canonical', 'Canonical With Derivative', 'FIR',
desc=("that specifies the hemodynamic reponse "
"function it can be 'Canonical', 'Canonical "
"With Derivative' or 'FIR'"), usedefault=True)
drift_model = traits.Enum("Cosine", "Polynomial", "Blank",
desc = ("string that specifies the desired drift "
"model, to be chosen among 'Polynomial', "
"'Cosine', 'Blank'"), usedefault=True)
TR = traits.Float(mandatory=True)
model = traits.Enum("ar1", "spherical",
desc=("autoregressive mode is available only for the "
"kalman method"), usedefault=True)
method = traits.Enum("kalman", "ols",
desc=("method to fit the model, ols or kalma; kalman "
"is more time consuming but it supports "
"autoregressive model"), usedefault=True)
mask = traits.File(exists=True,
desc=("restrict the fitting only to the region defined "
"by this mask"))
normalize_design_matrix = traits.Bool(False,
desc=("normalize (zscore) the "
"regressors before fitting"),
usedefault=True)
save_residuals = traits.Bool(False, usedefault=True)
plot_design_matrix = traits.Bool(False, usedefault=True)
class FitGLMOutputSpec(TraitedSpec):
beta = File(exists=True)
nvbeta = traits.Any()
s2 = File(exists=True)
dof = traits.Any()
constants = traits.Any()
axis = traits.Any()
reg_names = traits.List()
residuals = traits.File()
a = File(exists=True)
class FitGLM(BaseInterface):
'''
Fit GLM model based on the specified design. Supports only single or concatenated runs.
'''
input_spec = FitGLMInputSpec
output_spec = FitGLMOutputSpec
def _run_interface(self, runtime):
session_info = self.inputs.session_info
functional_runs = self.inputs.session_info[0]['scans']
if isinstance(functional_runs, str):
functional_runs = [functional_runs]
nii = nb.load(functional_runs[0])
data = nii.get_data()
if isdefined(self.inputs.mask):
mask = nb.load(self.inputs.mask).get_data() > 0
else:
mask = np.ones(nii.shape[:3]) == 1
timeseries = data.copy()[mask,:]
del data
for functional_run in functional_runs[1:]:
nii = nb.load(functional_run)
data = nii.get_data()
npdata = data.copy()
del data
timeseries = np.concatenate((timeseries,npdata[mask,:]), axis=1)
del npdata
nscans = timeseries.shape[1]
if 'hpf' in session_info[0].keys():
hpf = session_info[0]['hpf']
drift_model=self.inputs.drift_model
else:
hpf=0
drift_model = "Blank"
reg_names = []
for reg in session_info[0]['regress']:
reg_names.append(reg['name'])
reg_vals = np.zeros((nscans,len(reg_names)))
for i in range(len(reg_names)):
reg_vals[:,i] = np.array(session_info[0]['regress'][i]['val']).reshape(1,-1)
frametimes= np.linspace(0, (nscans-1)*self.inputs.TR, nscans)
conditions = []
onsets = []
duration = []
for i,cond in enumerate(session_info[0]['cond']):
onsets += cond['onset']
conditions += [cond['name']]*len(cond['onset'])
if len(cond['duration']) == 1:
duration += cond['duration']*len(cond['onset'])
else:
duration += cond['duration']
if conditions:
paradigm = BlockParadigm(con_id=conditions, onset=onsets, duration=duration)
else:
paradigm = None
design_matrix, self._reg_names = dm.dmtx_light(frametimes, paradigm, drift_model=drift_model, hfcut=hpf,
hrf_model=self.inputs.hrf_model,
add_regs=reg_vals,
add_reg_names=reg_names
)
if self.inputs.normalize_design_matrix:
for i in range(len(self._reg_names)-1):
design_matrix[:,i] = (design_matrix[:,i]-design_matrix[:,i].mean())/design_matrix[:,i].std()
if self.inputs.plot_design_matrix:
import pylab
pylab.pcolor(design_matrix)
pylab.savefig("design_matrix.pdf")
pylab.close()
pylab.clf()
glm = GLM.glm()
glm.fit(timeseries.T, design_matrix, method=self.inputs.method, model=self.inputs.model)
self._beta_file = os.path.abspath("beta.nii")
beta = np.zeros(mask.shape + (glm.beta.shape[0],))
beta[mask,:] = glm.beta.T
nb.save(nb.Nifti1Image(beta, nii.get_affine()), self._beta_file)
self._s2_file = os.path.abspath("s2.nii")
s2 = np.zeros(mask.shape)
s2[mask] = glm.s2
nb.save(nb.Nifti1Image(s2, nii.get_affine()), self._s2_file)
if self.inputs.save_residuals:
explained = np.dot(design_matrix,glm.beta)
residuals = np.zeros(mask.shape + (nscans,))
residuals[mask,:] = timeseries - explained.T
self._residuals_file = os.path.abspath("residuals.nii")
nb.save(nb.Nifti1Image(residuals, nii.get_affine()), self._residuals_file)
self._nvbeta = glm.nvbeta
self._dof = glm.dof
self._constants = glm._constants
self._axis = glm._axis
if self.inputs.model == "ar1":
self._a_file = os.path.abspath("a.nii")
a = np.zeros(mask.shape)
a[mask] = glm.a.squeeze()
nb.save(nb.Nifti1Image(a, nii.get_affine()), self._a_file)
self._model = glm.model
self._method = glm.method
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["beta"] = self._beta_file
outputs["nvbeta"] = self._nvbeta
outputs["s2"] = self._s2_file
outputs["dof"] = self._dof
outputs["constants"] = self._constants
outputs["axis"] = self._axis
outputs["reg_names"] = self._reg_names
if self.inputs.model == "ar1":
outputs["a"] = self._a_file
if self.inputs.save_residuals:
outputs["residuals"] = self._residuals_file
return outputs
class EstimateContrastInputSpec(BaseInterfaceInputSpec):
contrasts = traits.List(
traits.Either(traits.Tuple(traits.Str,
traits.Enum('T'),
traits.List(traits.Str),
traits.List(traits.Float)),
traits.Tuple(traits.Str,
traits.Enum('T'),
traits.List(traits.Str),
traits.List(traits.Float),
traits.List(traits.Float)),
traits.Tuple(traits.Str,
traits.Enum('F'),
traits.List(traits.Either(traits.Tuple(traits.Str,
traits.Enum('T'),
traits.List(traits.Str),
traits.List(traits.Float)),
traits.Tuple(traits.Str,
traits.Enum('T'),
traits.List(traits.Str),
traits.List(traits.Float),
traits.List(traits.Float)))))),
desc="""List of contrasts with each contrast being a list of the form:
[('name', 'stat', [condition list], [weight list], [session list])]. if
session list is None or not provided, all sessions are used. For F
contrasts, the condition list should contain previously defined
T-contrasts.""", mandatory=True)
beta = File(exists=True, desc="beta coefficients of the fitted model",mandatory=True)
nvbeta = traits.Any(mandatory=True)
s2 = File(exists=True, desc="squared variance of the residuals",mandatory=True)
dof = traits.Any(desc="degrees of freedom", mandatory=True)
constants = traits.Any(mandatory=True)
axis = traits.Any(mandatory=True)
reg_names = traits.List(mandatory=True)
mask = traits.File(exists=True)
class EstimateContrastOutputSpec(TraitedSpec):
stat_maps = OutputMultiPath(File(exists=True))
z_maps = OutputMultiPath(File(exists=True))
p_maps = OutputMultiPath(File(exists=True))
class EstimateContrast(BaseInterface):
'''
Estimate contrast of a fitted model.
'''
input_spec = EstimateContrastInputSpec
output_spec = EstimateContrastOutputSpec
def _run_interface(self, runtime):
beta_nii = nb.load(self.inputs.beta)
if isdefined(self.inputs.mask):
mask = nb.load(self.inputs.mask).get_data() > 0
else:
mask = np.ones(beta_nii.shape[:3]) == 1
glm = GLM.glm()
nii = nb.load(self.inputs.beta)
glm.beta = beta_nii.get_data().copy()[mask,:].T
glm.nvbeta = self.inputs.nvbeta
glm.s2 = nb.load(self.inputs.s2).get_data().copy()[mask]
glm.dof = self.inputs.dof
glm._axis = self.inputs.axis
glm._constants = self.inputs.constants
reg_names = self.inputs.reg_names
self._stat_maps = []
self._p_maps = []
self._z_maps = []
for contrast_def in self.inputs.contrasts:
name = contrast_def[0]
_ = contrast_def[1]
contrast = np.zeros(len(reg_names))
for i, reg_name in enumerate(reg_names):
if reg_name in contrast_def[2]:
idx = contrast_def[2].index(reg_name)
contrast[i] = contrast_def[3][idx]
est_contrast = glm.contrast(contrast)
stat_map = np.zeros(mask.shape)
stat_map[mask] = est_contrast.stat().T
stat_map_file = os.path.abspath(name + "_stat_map.nii")
nb.save(nb.Nifti1Image(stat_map, nii.get_affine()), stat_map_file)
self._stat_maps.append(stat_map_file)
p_map = np.zeros(mask.shape)
p_map[mask] = est_contrast.pvalue().T
p_map_file = os.path.abspath(name + "_p_map.nii")
nb.save(nb.Nifti1Image(p_map, nii.get_affine()), p_map_file)
self._p_maps.append(p_map_file)
z_map = np.zeros(mask.shape)
z_map[mask] = est_contrast.zscore().T
z_map_file = os.path.abspath(name + "_z_map.nii")
nb.save(nb.Nifti1Image(z_map, nii.get_affine()), z_map_file)
self._z_maps.append(z_map_file)
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["stat_maps"] = self._stat_maps
outputs["p_maps"] = self._p_maps
outputs["z_maps"] = self._z_maps
return outputs
|
mick-d/nipype_source
|
nipype/interfaces/nipy/model.py
|
Python
|
bsd-3-clause
| 12,699
|
#!/usr/bin/env python
# (c) 2014, Will Thames <will@thames.id.au>
#
# 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/>.
#
import ansible.constants as C
import sys
def main():
print C.DEFAULT_MODULE_PATH
return 0
if __name__ == '__main__':
sys.exit(main())
|
bootswithdefer/ansible
|
v2/hacking/get_library.py
|
Python
|
gpl-3.0
| 872
|
#!/usr/bin/env python
# HFacer.py - regenerate the Scintilla.h and SciLexer.h files from the Scintilla.iface interface
# definition file.
# The header files are copied to a temporary file apart from the section between a /* ++Autogenerated*/
# comment and a /* --Autogenerated*/ comment which is generated by the printHFile and printLexHFile
# functions. After the temporary file is created, it is copied back to the original file name.
import sys
import os
import Face
def Contains(s,sub):
return s.find(sub) != -1
def printLexHFile(f,out):
for name in f.order:
v = f.features[name]
if v["FeatureType"] in ["val"]:
if Contains(name, "SCE_") or Contains(name, "SCLEX_"):
out.write("#define " + name + " " + v["Value"] + "\n")
def printHFile(f,out):
previousCategory = ""
for name in f.order:
v = f.features[name]
if v["Category"] != "Deprecated":
if v["Category"] == "Provisional" and previousCategory != "Provisional":
out.write("#ifndef SCI_DISABLE_PROVISIONAL\n")
previousCategory = v["Category"]
if v["FeatureType"] in ["fun", "get", "set"]:
featureDefineName = "SCI_" + name.upper()
out.write("#define " + featureDefineName + " " + v["Value"] + "\n")
elif v["FeatureType"] in ["evt"]:
featureDefineName = "SCN_" + name.upper()
out.write("#define " + featureDefineName + " " + v["Value"] + "\n")
elif v["FeatureType"] in ["val"]:
if not (Contains(name, "SCE_") or Contains(name, "SCLEX_")):
out.write("#define " + name + " " + v["Value"] + "\n")
out.write("#endif\n")
def CopyWithInsertion(input, output, genfn, definition):
copying = 1
for line in input.readlines():
if copying:
output.write(line)
if Contains(line, "/* ++Autogenerated"):
copying = 0
genfn(definition, output)
if Contains(line, "/* --Autogenerated"):
copying = 1
output.write(line)
def contents(filename):
f = open(filename)
t = f.read()
f.close()
return t
def Regenerate(filename, genfn, definition):
inText = contents(filename)
tempname = "HFacer.tmp"
out = open(tempname,"w")
hfile = open(filename)
CopyWithInsertion(hfile, out, genfn, definition)
out.close()
hfile.close()
outText = contents(tempname)
if inText == outText:
os.unlink(tempname)
else:
os.unlink(filename)
os.rename(tempname, filename)
f = Face.Face()
try:
f.ReadFromFile("Scintilla.iface")
Regenerate("Scintilla.h", printHFile, f)
Regenerate("SciLexer.h", printLexHFile, f)
print("Maximum ID is %s" % max([x for x in f.values if int(x) < 3000]))
except:
raise
|
dluschan/rdo_studio
|
thirdparty/scintilla/include/HFacer.py
|
Python
|
mit
| 2,521
|
"""Blink an LED
This script assumes:
- ``board.pins[13]`` is a ``DigitalPin``
- there is an LED attached to it
"""
import time
import pingo
board = pingo.detect.get_board()
led = board.pins[13]
led.mode = pingo.OUT
while True:
led.toggle()
print(led.state)
time.sleep(.5)
|
dyegocantu/pingo-py
|
pingo/examples/blink.py
|
Python
|
mit
| 290
|
import unittest
import bottle
from tools import api
class TestRoute(unittest.TestCase):
@api('0.12')
def test_callback_inspection(self):
def x(a, b): pass
def d(f):
def w():
return f()
return w
route = bottle.Route(None, None, None, d(x))
self.assertEqual(route.get_undecorated_callback(), x)
self.assertEqual(set(route.get_callback_args()), set(['a', 'b']))
def d2(foo):
def d(f):
def w():
return f()
return w
return d
route = bottle.Route(None, None, None, d2('foo')(x))
self.assertEqual(route.get_undecorated_callback(), x)
self.assertEqual(set(route.get_callback_args()), set(['a', 'b']))
def test_callback_inspection_multiple_args(self):
# decorator with argument, modifying kwargs
def d2(f="1"):
def d(fn):
def w(*args, **kwargs):
# modification of kwargs WITH the decorator argument
# is necessary requirement for the error
kwargs["a"] = f
return fn(*args, **kwargs)
return w
return d
@d2(f='foo')
def x(a, b):
return
route = bottle.Route(None, None, None, x)
# triggers the "TypeError: 'foo' is not a Python function"
self.assertEqual(set(route.get_callback_args()), set(['a', 'b']))
if bottle.py3k:
def test_callback_inspection_newsig(self):
env = {}
eval(compile('def foo(a, *, b=5): pass', '<foo>', 'exec'), env, env)
route = bottle.Route(None, None, None, env['foo'])
self.assertEqual(set(route.get_callback_args()), set(['a', 'b']))
|
SmithSamuelM/bottle
|
test/test_route.py
|
Python
|
mit
| 1,829
|
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.aodv', cpp_namespace='::ns3')
return root_module
def register_types(module):
root_module = module.get_root()
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacType [enumeration]
module.add_enum('WifiMacType', ['WIFI_MAC_CTL_RTS', 'WIFI_MAC_CTL_CTS', 'WIFI_MAC_CTL_ACK', 'WIFI_MAC_CTL_BACKREQ', 'WIFI_MAC_CTL_BACKRESP', 'WIFI_MAC_MGT_BEACON', 'WIFI_MAC_MGT_ASSOCIATION_REQUEST', 'WIFI_MAC_MGT_ASSOCIATION_RESPONSE', 'WIFI_MAC_MGT_DISASSOCIATION', 'WIFI_MAC_MGT_REASSOCIATION_REQUEST', 'WIFI_MAC_MGT_REASSOCIATION_RESPONSE', 'WIFI_MAC_MGT_PROBE_REQUEST', 'WIFI_MAC_MGT_PROBE_RESPONSE', 'WIFI_MAC_MGT_AUTHENTICATION', 'WIFI_MAC_MGT_DEAUTHENTICATION', 'WIFI_MAC_MGT_ACTION', 'WIFI_MAC_MGT_ACTION_NO_ACK', 'WIFI_MAC_MGT_MULTIHOP_ACTION', 'WIFI_MAC_DATA', 'WIFI_MAC_DATA_CFACK', 'WIFI_MAC_DATA_CFPOLL', 'WIFI_MAC_DATA_CFACK_CFPOLL', 'WIFI_MAC_DATA_NULL', 'WIFI_MAC_DATA_NULL_CFACK', 'WIFI_MAC_DATA_NULL_CFPOLL', 'WIFI_MAC_DATA_NULL_CFACK_CFPOLL', 'WIFI_MAC_QOSDATA', 'WIFI_MAC_QOSDATA_CFACK', 'WIFI_MAC_QOSDATA_CFPOLL', 'WIFI_MAC_QOSDATA_CFACK_CFPOLL', 'WIFI_MAC_QOSDATA_NULL', 'WIFI_MAC_QOSDATA_NULL_CFPOLL', 'WIFI_MAC_QOSDATA_NULL_CFACK_CFPOLL'], import_from_module='ns.wifi')
## 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')
## int-to-type.h (module 'core'): ns3::IntToType<0> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['0'])
## int-to-type.h (module 'core'): ns3::IntToType<0>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 0 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<1> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['1'])
## int-to-type.h (module 'core'): ns3::IntToType<1>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 1 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<2> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['2'])
## int-to-type.h (module 'core'): ns3::IntToType<2>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 2 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<3> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['3'])
## int-to-type.h (module 'core'): ns3::IntToType<3>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 3 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<4> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['4'])
## int-to-type.h (module 'core'): ns3::IntToType<4>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 4 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<5> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['5'])
## int-to-type.h (module 'core'): ns3::IntToType<5>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 5 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<6> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['6'])
## int-to-type.h (module 'core'): ns3::IntToType<6>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 6 >'], import_from_module='ns.core')
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
module.add_class('Ipv4Address', import_from_module='ns.network')
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class]
module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet')
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration]
module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet')
## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class]
module.add_class('Ipv4Mask', import_from_module='ns.network')
## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper [class]
module.add_class('Ipv4RoutingHelper', allow_subclassing=True, import_from_module='ns.internet')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
module.add_class('Ipv6Address', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress [class]
module.add_class('Ipv6InterfaceAddress', import_from_module='ns.internet')
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::State_e [enumeration]
module.add_enum('State_e', ['TENTATIVE', 'DEPRECATED', 'PREFERRED', 'PERMANENT', 'HOMEADDRESS', 'TENTATIVE_OPTIMISTIC', 'INVALID'], outer_class=root_module['ns3::Ipv6InterfaceAddress'], import_from_module='ns.internet')
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Scope_e [enumeration]
module.add_enum('Scope_e', ['HOST', 'LINKLOCAL', 'GLOBAL'], outer_class=root_module['ns3::Ipv6InterfaceAddress'], import_from_module='ns.internet')
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class]
module.add_class('Ipv6Prefix', import_from_module='ns.network')
## mac48-address.h (module 'network'): ns3::Mac48Address [class]
module.add_class('Mac48Address', import_from_module='ns.network')
## mac48-address.h (module 'network'): ns3::Mac48Address [class]
root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address'])
## node-container.h (module 'network'): ns3::NodeContainer [class]
module.add_class('NodeContainer', import_from_module='ns.network')
## object-base.h (module 'core'): ns3::ObjectBase [class]
module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core')
## object.h (module 'core'): ns3::ObjectDeleter [struct]
module.add_class('ObjectDeleter', import_from_module='ns.core')
## object-factory.h (module 'core'): ns3::ObjectFactory [class]
module.add_class('ObjectFactory', import_from_module='ns.core')
## packet-metadata.h (module 'network'): ns3::PacketMetadata [class]
module.add_class('PacketMetadata', import_from_module='ns.network')
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata'])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [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'])
## 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')
## timer.h (module 'core'): ns3::Timer [class]
module.add_class('Timer', import_from_module='ns.core')
## timer.h (module 'core'): ns3::Timer::DestroyPolicy [enumeration]
module.add_enum('DestroyPolicy', ['CANCEL_ON_DESTROY', 'REMOVE_ON_DESTROY', 'CHECK_ON_DESTROY'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core')
## timer.h (module 'core'): ns3::Timer::State [enumeration]
module.add_enum('State', ['RUNNING', 'EXPIRED', 'SUSPENDED'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core')
## timer-impl.h (module 'core'): ns3::TimerImpl [class]
module.add_class('TimerImpl', allow_subclassing=True, import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId [class]
module.add_class('TypeId', import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration]
module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct]
module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId'])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct]
module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId'])
## empty.h (module 'core'): ns3::empty [class]
module.add_class('empty', import_from_module='ns.core')
## int64x64-double.h (module 'core'): ns3::int64x64_t [class]
module.add_class('int64x64_t', import_from_module='ns.core')
## aodv-helper.h (module 'aodv'): ns3::AodvHelper [class]
module.add_class('AodvHelper', parent=root_module['ns3::Ipv4RoutingHelper'])
## 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', 'CS1', 'AF11', 'AF12', 'AF13', 'CS2', 'AF21', 'AF22', 'AF23', 'CS3', 'AF31', 'AF32', 'AF33', 'CS4', 'AF41', 'AF42', 'AF43', 'CS5', 'EF', 'CS6', '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', ['NotECT', 'ECT1', 'ECT0', 'CE'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet')
## ipv6-header.h (module 'internet'): ns3::Ipv6Header [class]
module.add_class('Ipv6Header', import_from_module='ns.internet', parent=root_module['ns3::Header'])
## ipv6-header.h (module 'internet'): ns3::Ipv6Header::NextHeader_e [enumeration]
module.add_enum('NextHeader_e', ['IPV6_EXT_HOP_BY_HOP', 'IPV6_IPV4', 'IPV6_TCP', 'IPV6_UDP', 'IPV6_IPV6', 'IPV6_EXT_ROUTING', 'IPV6_EXT_FRAGMENTATION', 'IPV6_EXT_CONFIDENTIALITY', 'IPV6_EXT_AUTHENTIFICATION', 'IPV6_ICMPV6', 'IPV6_EXT_END', 'IPV6_EXT_DESTINATION', 'IPV6_SCTP', 'IPV6_EXT_MOBILITY', 'IPV6_UDP_LITE'], outer_class=root_module['ns3::Ipv6Header'], import_from_module='ns.internet')
## object.h (module 'core'): ns3::Object [class]
module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >'])
## object.h (module 'core'): ns3::Object::AggregateIterator [class]
module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object'])
## random-variable-stream.h (module 'core'): ns3::RandomVariableStream [class]
module.add_class('RandomVariableStream', import_from_module='ns.core', parent=root_module['ns3::Object'])
## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable [class]
module.add_class('SequentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::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::SocketIpTtlTag [class]
module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class]
module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## nstime.h (module 'core'): ns3::Time [class]
module.add_class('Time', import_from_module='ns.core')
## nstime.h (module 'core'): ns3::Time::Unit [enumeration]
module.add_enum('Unit', ['S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core')
## nstime.h (module 'core'): ns3::Time [class]
root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t'])
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class]
module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
## trailer.h (module 'network'): ns3::Trailer [class]
module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk'])
## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable [class]
module.add_class('TriangularRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable [class]
module.add_class('UniformRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable [class]
module.add_class('WeibullRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader [class]
module.add_class('WifiMacHeader', import_from_module='ns.wifi', parent=root_module['ns3::Header'])
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader::QosAckPolicy [enumeration]
module.add_enum('QosAckPolicy', ['NORMAL_ACK', 'NO_ACK', 'NO_EXPLICIT_ACK', 'BLOCK_ACK'], outer_class=root_module['ns3::WifiMacHeader'], import_from_module='ns.wifi')
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader::AddressType [enumeration]
module.add_enum('AddressType', ['ADDR1', 'ADDR2', 'ADDR3', 'ADDR4'], outer_class=root_module['ns3::WifiMacHeader'], import_from_module='ns.wifi')
## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable [class]
module.add_class('ZetaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable [class]
module.add_class('ZipfRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## arp-cache.h (module 'internet'): ns3::ArpCache [class]
module.add_class('ArpCache', import_from_module='ns.internet', parent=root_module['ns3::Object'])
## arp-cache.h (module 'internet'): ns3::ArpCache::Entry [class]
module.add_class('Entry', import_from_module='ns.internet', outer_class=root_module['ns3::ArpCache'])
## attribute.h (module 'core'): ns3::AttributeAccessor [class]
module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
## attribute.h (module 'core'): ns3::AttributeChecker [class]
module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
## attribute.h (module 'core'): ns3::AttributeValue [class]
module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
## callback.h (module 'core'): ns3::CallbackChecker [class]
module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## callback.h (module 'core'): ns3::CallbackImplBase [class]
module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
## callback.h (module 'core'): ns3::CallbackValue [class]
module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable [class]
module.add_class('ConstantRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable [class]
module.add_class('DeterministicRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable [class]
module.add_class('EmpiricalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## attribute.h (module 'core'): ns3::EmptyAttributeValue [class]
module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## enum.h (module 'core'): ns3::EnumChecker [class]
module.add_class('EnumChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## enum.h (module 'core'): ns3::EnumValue [class]
module.add_class('EnumValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable [class]
module.add_class('ErlangRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## event-impl.h (module 'core'): ns3::EventImpl [class]
module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >'])
## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable [class]
module.add_class('ExponentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable [class]
module.add_class('GammaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol [class]
module.add_class('IpL4Protocol', import_from_module='ns.internet', parent=root_module['ns3::Object'])
## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus [enumeration]
module.add_enum('RxStatus', ['RX_OK', 'RX_CSUM_FAILED', 'RX_ENDPOINT_CLOSED', 'RX_ENDPOINT_UNREACH'], outer_class=root_module['ns3::IpL4Protocol'], import_from_module='ns.internet')
## ipv4.h (module 'internet'): ns3::Ipv4 [class]
module.add_class('Ipv4', import_from_module='ns.internet', parent=root_module['ns3::Object'])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class]
module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class]
module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv4-interface.h (module 'internet'): ns3::Ipv4Interface [class]
module.add_class('Ipv4Interface', import_from_module='ns.internet', parent=root_module['ns3::Object'])
## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol [class]
module.add_class('Ipv4L3Protocol', import_from_module='ns.internet', parent=root_module['ns3::Ipv4'])
## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::DropReason [enumeration]
module.add_enum('DropReason', ['DROP_TTL_EXPIRED', 'DROP_NO_ROUTE', 'DROP_BAD_CHECKSUM', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_FRAGMENT_TIMEOUT'], outer_class=root_module['ns3::Ipv4L3Protocol'], import_from_module='ns.internet')
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class]
module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class]
module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute [class]
module.add_class('Ipv4MulticastRoute', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >'])
## ipv4-route.h (module 'internet'): ns3::Ipv4Route [class]
module.add_class('Ipv4Route', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >'])
## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol [class]
module.add_class('Ipv4RoutingProtocol', import_from_module='ns.internet', parent=root_module['ns3::Object'])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class]
module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class]
module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface [class]
module.add_class('Ipv6Interface', import_from_module='ns.internet', parent=root_module['ns3::Object'])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class]
module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class]
module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable [class]
module.add_class('LogNormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class]
module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class]
module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## net-device.h (module 'network'): ns3::NetDevice [class]
module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object'])
## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration]
module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network')
## nix-vector.h (module 'network'): ns3::NixVector [class]
module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
## node.h (module 'network'): ns3::Node [class]
module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object'])
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable [class]
module.add_class('NormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class]
module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class]
module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class]
module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >'])
## packet.h (module 'network'): ns3::Packet [class]
module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class]
module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## nstime.h (module 'core'): ns3::TimeChecker [class]
module.add_class('TimeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## nstime.h (module 'core'): ns3::TimeValue [class]
module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## type-id.h (module 'core'): ns3::TypeIdChecker [class]
module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## type-id.h (module 'core'): ns3::TypeIdValue [class]
module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## address.h (module 'network'): ns3::AddressChecker [class]
module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## address.h (module 'network'): ns3::AddressValue [class]
module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
module.add_container('std::list< ns3::Ptr< ns3::Packet > >', 'ns3::Ptr< ns3::Packet >', container_type='list')
module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type='map')
## Register a nested module for the namespace FatalImpl
nested_module = module.add_cpp_namespace('FatalImpl')
register_types_ns3_FatalImpl(nested_module)
## Register a nested module for the namespace aodv
nested_module = module.add_cpp_namespace('aodv')
register_types_ns3_aodv(nested_module)
def register_types_ns3_FatalImpl(module):
root_module = module.get_root()
def register_types_ns3_aodv(module):
root_module = module.get_root()
## aodv-packet.h (module 'aodv'): ns3::aodv::MessageType [enumeration]
module.add_enum('MessageType', ['AODVTYPE_RREQ', 'AODVTYPE_RREP', 'AODVTYPE_RERR', 'AODVTYPE_RREP_ACK'])
## aodv-rtable.h (module 'aodv'): ns3::aodv::RouteFlags [enumeration]
module.add_enum('RouteFlags', ['VALID', 'INVALID', 'IN_SEARCH'])
## aodv-dpd.h (module 'aodv'): ns3::aodv::DuplicatePacketDetection [class]
module.add_class('DuplicatePacketDetection')
## aodv-id-cache.h (module 'aodv'): ns3::aodv::IdCache [class]
module.add_class('IdCache')
## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors [class]
module.add_class('Neighbors')
## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbor [struct]
module.add_class('Neighbor', outer_class=root_module['ns3::aodv::Neighbors'])
## aodv-rqueue.h (module 'aodv'): ns3::aodv::QueueEntry [class]
module.add_class('QueueEntry')
## aodv-rqueue.h (module 'aodv'): ns3::aodv::RequestQueue [class]
module.add_class('RequestQueue')
## aodv-packet.h (module 'aodv'): ns3::aodv::RerrHeader [class]
module.add_class('RerrHeader', parent=root_module['ns3::Header'])
## aodv-routing-protocol.h (module 'aodv'): ns3::aodv::RoutingProtocol [class]
module.add_class('RoutingProtocol', parent=root_module['ns3::Ipv4RoutingProtocol'])
## aodv-rtable.h (module 'aodv'): ns3::aodv::RoutingTable [class]
module.add_class('RoutingTable')
## aodv-rtable.h (module 'aodv'): ns3::aodv::RoutingTableEntry [class]
module.add_class('RoutingTableEntry')
## aodv-packet.h (module 'aodv'): ns3::aodv::RrepAckHeader [class]
module.add_class('RrepAckHeader', parent=root_module['ns3::Header'])
## aodv-packet.h (module 'aodv'): ns3::aodv::RrepHeader [class]
module.add_class('RrepHeader', parent=root_module['ns3::Header'])
## aodv-packet.h (module 'aodv'): ns3::aodv::RreqHeader [class]
module.add_class('RreqHeader', parent=root_module['ns3::Header'])
## aodv-packet.h (module 'aodv'): ns3::aodv::TypeHeader [class]
module.add_class('TypeHeader', parent=root_module['ns3::Header'])
module.add_container('std::map< ns3::Ipv4Address, unsigned int >', ('ns3::Ipv4Address', 'unsigned int'), container_type='map')
module.add_container('std::vector< ns3::Ipv4Address >', 'ns3::Ipv4Address', container_type='vector')
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_Ns3IntToType__0_methods(root_module, root_module['ns3::IntToType< 0 >'])
register_Ns3IntToType__1_methods(root_module, root_module['ns3::IntToType< 1 >'])
register_Ns3IntToType__2_methods(root_module, root_module['ns3::IntToType< 2 >'])
register_Ns3IntToType__3_methods(root_module, root_module['ns3::IntToType< 3 >'])
register_Ns3IntToType__4_methods(root_module, root_module['ns3::IntToType< 4 >'])
register_Ns3IntToType__5_methods(root_module, root_module['ns3::IntToType< 5 >'])
register_Ns3IntToType__6_methods(root_module, root_module['ns3::IntToType< 6 >'])
register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address'])
register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress'])
register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask'])
register_Ns3Ipv4RoutingHelper_methods(root_module, root_module['ns3::Ipv4RoutingHelper'])
register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address'])
register_Ns3Ipv6InterfaceAddress_methods(root_module, root_module['ns3::Ipv6InterfaceAddress'])
register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix'])
register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address'])
register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer'])
register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase'])
register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter'])
register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory'])
register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata'])
register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item'])
register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator'])
register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator'])
register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item'])
register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList'])
register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData'])
register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >'])
register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator'])
register_Ns3Tag_methods(root_module, root_module['ns3::Tag'])
register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer'])
register_Ns3Timer_methods(root_module, root_module['ns3::Timer'])
register_Ns3TimerImpl_methods(root_module, root_module['ns3::TimerImpl'])
register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId'])
register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation'])
register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation'])
register_Ns3Empty_methods(root_module, root_module['ns3::empty'])
register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t'])
register_Ns3AodvHelper_methods(root_module, root_module['ns3::AodvHelper'])
register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk'])
register_Ns3Header_methods(root_module, root_module['ns3::Header'])
register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header'])
register_Ns3Ipv6Header_methods(root_module, root_module['ns3::Ipv6Header'])
register_Ns3Object_methods(root_module, root_module['ns3::Object'])
register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator'])
register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream'])
register_Ns3SequentialRandomVariable_methods(root_module, root_module['ns3::SequentialRandomVariable'])
register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >'])
register_Ns3SimpleRefCount__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_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag'])
register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag'])
register_Ns3Time_methods(root_module, root_module['ns3::Time'])
register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor'])
register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer'])
register_Ns3TriangularRandomVariable_methods(root_module, root_module['ns3::TriangularRandomVariable'])
register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable'])
register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable'])
register_Ns3WifiMacHeader_methods(root_module, root_module['ns3::WifiMacHeader'])
register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable'])
register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable'])
register_Ns3ArpCache_methods(root_module, root_module['ns3::ArpCache'])
register_Ns3ArpCacheEntry_methods(root_module, root_module['ns3::ArpCache::Entry'])
register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor'])
register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker'])
register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue'])
register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker'])
register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase'])
register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue'])
register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable'])
register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable'])
register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable'])
register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue'])
register_Ns3EnumChecker_methods(root_module, root_module['ns3::EnumChecker'])
register_Ns3EnumValue_methods(root_module, root_module['ns3::EnumValue'])
register_Ns3ErlangRandomVariable_methods(root_module, root_module['ns3::ErlangRandomVariable'])
register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl'])
register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable'])
register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable'])
register_Ns3IpL4Protocol_methods(root_module, root_module['ns3::IpL4Protocol'])
register_Ns3Ipv4_methods(root_module, root_module['ns3::Ipv4'])
register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker'])
register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue'])
register_Ns3Ipv4Interface_methods(root_module, root_module['ns3::Ipv4Interface'])
register_Ns3Ipv4L3Protocol_methods(root_module, root_module['ns3::Ipv4L3Protocol'])
register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker'])
register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue'])
register_Ns3Ipv4MulticastRoute_methods(root_module, root_module['ns3::Ipv4MulticastRoute'])
register_Ns3Ipv4Route_methods(root_module, root_module['ns3::Ipv4Route'])
register_Ns3Ipv4RoutingProtocol_methods(root_module, root_module['ns3::Ipv4RoutingProtocol'])
register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker'])
register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue'])
register_Ns3Ipv6Interface_methods(root_module, root_module['ns3::Ipv6Interface'])
register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker'])
register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue'])
register_Ns3LogNormalRandomVariable_methods(root_module, root_module['ns3::LogNormalRandomVariable'])
register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker'])
register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue'])
register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice'])
register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector'])
register_Ns3Node_methods(root_module, root_module['ns3::Node'])
register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable'])
register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker'])
register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue'])
register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper'])
register_Ns3Packet_methods(root_module, root_module['ns3::Packet'])
register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable'])
register_Ns3TimeChecker_methods(root_module, root_module['ns3::TimeChecker'])
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_Ns3AodvDuplicatePacketDetection_methods(root_module, root_module['ns3::aodv::DuplicatePacketDetection'])
register_Ns3AodvIdCache_methods(root_module, root_module['ns3::aodv::IdCache'])
register_Ns3AodvNeighbors_methods(root_module, root_module['ns3::aodv::Neighbors'])
register_Ns3AodvNeighborsNeighbor_methods(root_module, root_module['ns3::aodv::Neighbors::Neighbor'])
register_Ns3AodvQueueEntry_methods(root_module, root_module['ns3::aodv::QueueEntry'])
register_Ns3AodvRequestQueue_methods(root_module, root_module['ns3::aodv::RequestQueue'])
register_Ns3AodvRerrHeader_methods(root_module, root_module['ns3::aodv::RerrHeader'])
register_Ns3AodvRoutingProtocol_methods(root_module, root_module['ns3::aodv::RoutingProtocol'])
register_Ns3AodvRoutingTable_methods(root_module, root_module['ns3::aodv::RoutingTable'])
register_Ns3AodvRoutingTableEntry_methods(root_module, root_module['ns3::aodv::RoutingTableEntry'])
register_Ns3AodvRrepAckHeader_methods(root_module, root_module['ns3::aodv::RrepAckHeader'])
register_Ns3AodvRrepHeader_methods(root_module, root_module['ns3::aodv::RrepHeader'])
register_Ns3AodvRreqHeader_methods(root_module, root_module['ns3::aodv::RreqHeader'])
register_Ns3AodvTypeHeader_methods(root_module, root_module['ns3::aodv::TypeHeader'])
return
def register_Ns3Address_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## address.h (module 'network'): ns3::Address::Address() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor]
cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')])
## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor]
cls.add_constructor([param('ns3::Address const &', 'address')])
## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function]
cls.add_method('CheckCompatible',
'bool',
[param('uint8_t', 'type'), param('uint8_t', 'len')],
is_const=True)
## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function]
cls.add_method('CopyAllFrom',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint8_t', 'len')])
## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function]
cls.add_method('CopyAllTo',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint8_t', 'len')],
is_const=True)
## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function]
cls.add_method('CopyFrom',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint8_t', 'len')])
## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function]
cls.add_method('CopyTo',
'uint32_t',
[param('uint8_t *', 'buffer')],
is_const=True)
## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'buffer')])
## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function]
cls.add_method('GetLength',
'uint8_t',
[],
is_const=True)
## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function]
cls.add_method('IsInvalid',
'bool',
[],
is_const=True)
## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function]
cls.add_method('IsMatchingType',
'bool',
[param('uint8_t', 'type')],
is_const=True)
## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function]
cls.add_method('Register',
'uint8_t',
[],
is_static=True)
## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'buffer')],
is_const=True)
return
def register_Ns3AttributeConstructionList_methods(root_module, cls):
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor]
cls.add_constructor([])
## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')])
## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function]
cls.add_method('Begin',
'std::_List_const_iterator< ns3::AttributeConstructionList::Item >',
[],
is_const=True)
## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function]
cls.add_method('End',
'std::_List_const_iterator< ns3::AttributeConstructionList::Item >',
[],
is_const=True)
## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('Find',
'ns3::Ptr< ns3::AttributeValue >',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True)
return
def register_Ns3AttributeConstructionListItem_methods(root_module, cls):
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor]
cls.add_constructor([])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable]
cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False)
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable]
cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False)
return
def register_Ns3Buffer_methods(root_module, cls):
## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor]
cls.add_constructor([])
## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor]
cls.add_constructor([param('uint32_t', 'dataSize')])
## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor]
cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')])
## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor]
cls.add_constructor([param('ns3::Buffer const &', 'o')])
## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function]
cls.add_method('AddAtEnd',
'bool',
[param('uint32_t', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::Buffer const &', 'o')])
## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function]
cls.add_method('AddAtStart',
'bool',
[param('uint32_t', 'start')])
## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function]
cls.add_method('Begin',
'ns3::Buffer::Iterator',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function]
cls.add_method('CopyData',
'void',
[param('std::ostream *', 'os'), param('uint32_t', 'size')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function]
cls.add_method('CopyData',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')],
is_const=True)
## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function]
cls.add_method('CreateFragment',
'ns3::Buffer',
[param('uint32_t', 'start'), param('uint32_t', 'length')],
is_const=True)
## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function]
cls.add_method('CreateFullCopy',
'ns3::Buffer',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function]
cls.add_method('End',
'ns3::Buffer::Iterator',
[],
is_const=True)
## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function]
cls.add_method('GetCurrentEndOffset',
'int32_t',
[],
is_const=True)
## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function]
cls.add_method('GetCurrentStartOffset',
'int32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function]
cls.add_method('PeekData',
'uint8_t const *',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'start')])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3BufferIterator_methods(root_module, cls):
## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')])
## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor]
cls.add_constructor([])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function]
cls.add_method('CalculateIpChecksum',
'uint16_t',
[param('uint16_t', 'size')])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function]
cls.add_method('CalculateIpChecksum',
'uint16_t',
[param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function]
cls.add_method('GetDistanceFrom',
'uint32_t',
[param('ns3::Buffer::Iterator const &', 'o')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function]
cls.add_method('IsEnd',
'bool',
[],
is_const=True)
## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function]
cls.add_method('IsStart',
'bool',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function]
cls.add_method('Next',
'void',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function]
cls.add_method('Next',
'void',
[param('uint32_t', 'delta')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function]
cls.add_method('Prev',
'void',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function]
cls.add_method('Prev',
'void',
[param('uint32_t', 'delta')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function]
cls.add_method('ReadLsbtohU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function]
cls.add_method('ReadLsbtohU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function]
cls.add_method('ReadLsbtohU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function]
cls.add_method('ReadNtohU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function]
cls.add_method('ReadNtohU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function]
cls.add_method('ReadNtohU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function]
cls.add_method('Write',
'void',
[param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function]
cls.add_method('WriteHtolsbU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function]
cls.add_method('WriteHtolsbU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function]
cls.add_method('WriteHtolsbU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function]
cls.add_method('WriteHtonU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function]
cls.add_method('WriteHtonU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function]
cls.add_method('WriteHtonU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'data'), param('uint32_t', 'len')])
return
def register_Ns3ByteTagIterator_methods(root_module, cls):
## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')])
## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function]
cls.add_method('Next',
'ns3::ByteTagIterator::Item',
[])
return
def register_Ns3ByteTagIteratorItem_methods(root_module, cls):
## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')])
## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function]
cls.add_method('GetEnd',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function]
cls.add_method('GetStart',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function]
cls.add_method('GetTag',
'void',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
return
def register_Ns3ByteTagList_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor]
cls.add_constructor([])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList const &', 'o')])
## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function]
cls.add_method('Add',
'ns3::TagBuffer',
[param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function]
cls.add_method('Add',
'void',
[param('ns3::ByteTagList const &', 'o')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t adjustment, int32_t appendOffset) [member function]
cls.add_method('AddAtEnd',
'void',
[param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function]
cls.add_method('AddAtStart',
'void',
[param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function]
cls.add_method('Begin',
'ns3::ByteTagList::Iterator',
[param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')],
is_const=True)
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function]
cls.add_method('RemoveAll',
'void',
[])
return
def register_Ns3ByteTagListIterator_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')])
## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function]
cls.add_method('GetOffsetStart',
'uint32_t',
[],
is_const=True)
## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function]
cls.add_method('Next',
'ns3::ByteTagList::Iterator::Item',
[])
return
def register_Ns3ByteTagListIteratorItem_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor]
cls.add_constructor([param('ns3::TagBuffer', 'buf')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable]
cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable]
cls.add_instance_attribute('end', 'int32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable]
cls.add_instance_attribute('size', 'uint32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable]
cls.add_instance_attribute('start', 'int32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3CallbackBase_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')])
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function]
cls.add_method('GetImpl',
'ns3::Ptr< ns3::CallbackImplBase >',
[],
is_const=True)
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')],
visibility='protected')
## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function]
cls.add_method('Demangle',
'std::string',
[param('std::string const &', 'mangled')],
is_static=True, visibility='protected')
return
def register_Ns3EventId_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('==')
## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EventId const &', 'arg0')])
## event-id.h (module 'core'): ns3::EventId::EventId() [constructor]
cls.add_constructor([])
## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')])
## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_const=True)
## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function]
cls.add_method('GetTs',
'uint64_t',
[],
is_const=True)
## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function]
cls.add_method('GetUid',
'uint32_t',
[],
is_const=True)
## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function]
cls.add_method('IsExpired',
'bool',
[],
is_const=True)
## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function]
cls.add_method('IsRunning',
'bool',
[],
is_const=True)
## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function]
cls.add_method('PeekEventImpl',
'ns3::EventImpl *',
[],
is_const=True)
return
def register_Ns3IntToType__0_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType(ns3::IntToType<0> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 0 > const &', 'arg0')])
return
def register_Ns3IntToType__1_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType(ns3::IntToType<1> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 1 > const &', 'arg0')])
return
def register_Ns3IntToType__2_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType(ns3::IntToType<2> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 2 > const &', 'arg0')])
return
def register_Ns3IntToType__3_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType(ns3::IntToType<3> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 3 > const &', 'arg0')])
return
def register_Ns3IntToType__4_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType(ns3::IntToType<4> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 4 > const &', 'arg0')])
return
def register_Ns3IntToType__5_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType(ns3::IntToType<5> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 5 > const &', 'arg0')])
return
def register_Ns3IntToType__6_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType(ns3::IntToType<6> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 6 > const &', 'arg0')])
return
def register_Ns3Ipv4Address_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor]
cls.add_constructor([param('uint32_t', 'address')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor]
cls.add_constructor([param('char const *', 'address')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('CombineMask',
'ns3::Ipv4Address',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Ipv4Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function]
cls.add_method('Deserialize',
'ns3::Ipv4Address',
[param('uint8_t const *', 'buf')],
is_static=True)
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function]
cls.add_method('Get',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function]
cls.add_method('GetAny',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('GetSubnetDirectedBroadcast',
'ns3::Ipv4Address',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv4Address const &', 'other')],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function]
cls.add_method('IsLocalMulticast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('IsSubnetDirectedBroadcast',
'bool',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function]
cls.add_method('Serialize',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function]
cls.add_method('Set',
'void',
[param('uint32_t', 'address')])
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function]
cls.add_method('Set',
'void',
[param('char const *', 'address')])
return
def register_Ns3Ipv4InterfaceAddress_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress() [constructor]
cls.add_constructor([])
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4Address local, ns3::Ipv4Mask mask) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'local'), param('ns3::Ipv4Mask', 'mask')])
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4InterfaceAddress const & o) [copy constructor]
cls.add_constructor([param('ns3::Ipv4InterfaceAddress const &', 'o')])
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetLocal() const [member function]
cls.add_method('GetLocal',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Mask ns3::Ipv4InterfaceAddress::GetMask() const [member function]
cls.add_method('GetMask',
'ns3::Ipv4Mask',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e ns3::Ipv4InterfaceAddress::GetScope() const [member function]
cls.add_method('GetScope',
'ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): bool ns3::Ipv4InterfaceAddress::IsSecondary() const [member function]
cls.add_method('IsSecondary',
'bool',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetBroadcast(ns3::Ipv4Address broadcast) [member function]
cls.add_method('SetBroadcast',
'void',
[param('ns3::Ipv4Address', 'broadcast')])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetLocal(ns3::Ipv4Address local) [member function]
cls.add_method('SetLocal',
'void',
[param('ns3::Ipv4Address', 'local')])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetMask(ns3::Ipv4Mask mask) [member function]
cls.add_method('SetMask',
'void',
[param('ns3::Ipv4Mask', 'mask')])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetPrimary() [member function]
cls.add_method('SetPrimary',
'void',
[])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetScope(ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function]
cls.add_method('SetScope',
'void',
[param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetSecondary() [member function]
cls.add_method('SetSecondary',
'void',
[])
return
def register_Ns3Ipv4Mask_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor]
cls.add_constructor([param('uint32_t', 'mask')])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor]
cls.add_constructor([param('char const *', 'mask')])
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function]
cls.add_method('Get',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function]
cls.add_method('GetInverse',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function]
cls.add_method('GetPrefixLength',
'uint16_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv4Mask', 'other')],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function]
cls.add_method('IsMatch',
'bool',
[param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function]
cls.add_method('Set',
'void',
[param('uint32_t', 'mask')])
return
def register_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'): void ns3::Ipv4RoutingHelper::PrintRoutingTableAllAt(ns3::Time printTime, ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function]
cls.add_method('PrintRoutingTableAllAt',
'void',
[param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_const=True)
## ipv4-routing-helper.h (module 'internet'): void ns3::Ipv4RoutingHelper::PrintRoutingTableAllEvery(ns3::Time printInterval, ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function]
cls.add_method('PrintRoutingTableAllEvery',
'void',
[param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_const=True)
## ipv4-routing-helper.h (module 'internet'): void ns3::Ipv4RoutingHelper::PrintRoutingTableAt(ns3::Time printTime, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function]
cls.add_method('PrintRoutingTableAt',
'void',
[param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_const=True)
## ipv4-routing-helper.h (module 'internet'): void ns3::Ipv4RoutingHelper::PrintRoutingTableEvery(ns3::Time printInterval, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function]
cls.add_method('PrintRoutingTableEvery',
'void',
[param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_const=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::IsEqual(ns3::Ipv6Address const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv6Address const &', 'other')],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() [member function]
cls.add_method('IsIpv4MappedAddress',
'bool',
[])
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function]
cls.add_method('IsLinkLocal',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function]
cls.add_method('IsLinkLocalMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function]
cls.add_method('IsLocalhost',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function]
cls.add_method('IsSolicitedMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::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::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::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function]
cls.add_method('MakeIpv4MappedAddress',
'ns3::Ipv6Address',
[param('ns3::Ipv4Address', 'addr')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function]
cls.add_method('MakeSolicitedAddress',
'ns3::Ipv6Address',
[param('ns3::Ipv6Address', 'addr')],
is_static=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function]
cls.add_method('Serialize',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function]
cls.add_method('Set',
'void',
[param('char const *', 'address')])
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function]
cls.add_method('Set',
'void',
[param('uint8_t *', 'address')])
return
def register_Ns3Ipv6InterfaceAddress_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress() [constructor]
cls.add_constructor([])
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6Address address) [constructor]
cls.add_constructor([param('ns3::Ipv6Address', 'address')])
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6Address address, ns3::Ipv6Prefix prefix) [constructor]
cls.add_constructor([param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6Prefix', 'prefix')])
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6InterfaceAddress const & o) [copy constructor]
cls.add_constructor([param('ns3::Ipv6InterfaceAddress const &', 'o')])
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6InterfaceAddress::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Ipv6Address',
[],
is_const=True)
## ipv6-interface-address.h (module 'internet'): uint32_t ns3::Ipv6InterfaceAddress::GetNsDadUid() const [member function]
cls.add_method('GetNsDadUid',
'uint32_t',
[],
is_const=True)
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6Prefix ns3::Ipv6InterfaceAddress::GetPrefix() const [member function]
cls.add_method('GetPrefix',
'ns3::Ipv6Prefix',
[],
is_const=True)
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Scope_e ns3::Ipv6InterfaceAddress::GetScope() const [member function]
cls.add_method('GetScope',
'ns3::Ipv6InterfaceAddress::Scope_e',
[],
is_const=True)
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::State_e ns3::Ipv6InterfaceAddress::GetState() const [member function]
cls.add_method('GetState',
'ns3::Ipv6InterfaceAddress::State_e',
[],
is_const=True)
## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetAddress(ns3::Ipv6Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Ipv6Address', 'address')])
## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetNsDadUid(uint32_t uid) [member function]
cls.add_method('SetNsDadUid',
'void',
[param('uint32_t', 'uid')])
## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetScope(ns3::Ipv6InterfaceAddress::Scope_e scope) [member function]
cls.add_method('SetScope',
'void',
[param('ns3::Ipv6InterfaceAddress::Scope_e', 'scope')])
## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetState(ns3::Ipv6InterfaceAddress::State_e state) [member function]
cls.add_method('SetState',
'void',
[param('ns3::Ipv6InterfaceAddress::State_e', 'state')])
return
def register_Ns3Ipv6Prefix_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor]
cls.add_constructor([param('uint8_t *', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor]
cls.add_constructor([param('char const *', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor]
cls.add_constructor([param('uint8_t', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')])
## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function]
cls.add_method('GetBytes',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function]
cls.add_method('GetPrefixLength',
'uint8_t',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv6Prefix const &', 'other')],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function]
cls.add_method('IsMatch',
'bool',
[param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
return
def register_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_Ns3NodeContainer_methods(root_module, cls):
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor]
cls.add_constructor([])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor]
cls.add_constructor([param('std::string', 'nodeName')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::NodeContainer', 'other')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'nodeName')])
## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_const=True)
## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function]
cls.add_method('Create',
'void',
[param('uint32_t', 'n')])
## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function]
cls.add_method('Create',
'void',
[param('uint32_t', 'n'), param('uint32_t', 'systemId')])
## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_const=True)
## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::Node >',
[param('uint32_t', 'i')],
is_const=True)
## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function]
cls.add_method('GetGlobal',
'ns3::NodeContainer',
[],
is_static=True)
## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
return
def register_Ns3ObjectBase_methods(root_module, cls):
## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor]
cls.add_constructor([])
## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')])
## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function]
cls.add_method('GetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'value')],
is_const=True)
## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function]
cls.add_method('GetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')],
is_const=True)
## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceConnect',
'bool',
[param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceConnectWithoutContext',
'bool',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceDisconnect',
'bool',
[param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceDisconnectWithoutContext',
'bool',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function]
cls.add_method('ConstructSelf',
'void',
[param('ns3::AttributeConstructionList const &', 'attributes')],
visibility='protected')
## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function]
cls.add_method('NotifyConstructionCompleted',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ObjectDeleter_methods(root_module, cls):
## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor]
cls.add_constructor([])
## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')])
## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function]
cls.add_method('Delete',
'void',
[param('ns3::Object *', 'object')],
is_static=True)
return
def register_Ns3ObjectFactory_methods(root_module, cls):
cls.add_output_stream_operator()
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')])
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor]
cls.add_constructor([param('std::string', 'typeId')])
## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::Object >',
[],
is_const=True)
## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('ns3::TypeId', 'tid')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('char const *', 'tid')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('std::string', 'tid')])
return
def register_Ns3PacketMetadata_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor]
cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata const &', 'o')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::PacketMetadata const &', 'o')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function]
cls.add_method('AddHeader',
'void',
[param('ns3::Header const &', 'header'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function]
cls.add_method('AddPaddingAtEnd',
'void',
[param('uint32_t', 'end')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function]
cls.add_method('AddTrailer',
'void',
[param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function]
cls.add_method('BeginItem',
'ns3::PacketMetadata::ItemIterator',
[param('ns3::Buffer', 'buffer')],
is_const=True)
## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function]
cls.add_method('CreateFragment',
'ns3::PacketMetadata',
[param('uint32_t', 'start'), param('uint32_t', 'end')],
is_const=True)
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function]
cls.add_method('Enable',
'void',
[],
is_static=True)
## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function]
cls.add_method('EnableChecking',
'void',
[],
is_static=True)
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function]
cls.add_method('GetUid',
'uint64_t',
[],
is_const=True)
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'end')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'start')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function]
cls.add_method('RemoveHeader',
'void',
[param('ns3::Header const &', 'header'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function]
cls.add_method('RemoveTrailer',
'void',
[param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3PacketMetadataItem_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor]
cls.add_constructor([])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable]
cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable]
cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable]
cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable]
cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable]
cls.add_instance_attribute('isFragment', 'bool', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3PacketMetadataItemIterator_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor]
cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')])
## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketMetadata::Item',
[])
return
def register_Ns3PacketTagIterator_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')])
## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketTagIterator::Item',
[])
return
def register_Ns3PacketTagIteratorItem_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')])
## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function]
cls.add_method('GetTag',
'void',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
return
def register_Ns3PacketTagList_methods(root_module, cls):
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor]
cls.add_constructor([])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketTagList const &', 'o')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function]
cls.add_method('Add',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function]
cls.add_method('Head',
'ns3::PacketTagList::TagData const *',
[],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function]
cls.add_method('Peek',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function]
cls.add_method('Remove',
'bool',
[param('ns3::Tag &', 'tag')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function]
cls.add_method('RemoveAll',
'void',
[])
return
def register_Ns3PacketTagListTagData_methods(root_module, cls):
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor]
cls.add_constructor([])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable]
cls.add_instance_attribute('count', 'uint32_t', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable]
cls.add_instance_attribute('data', 'uint8_t [ 20 ]', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable]
cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3Simulator_methods(root_module, cls):
## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Simulator const &', 'arg0')])
## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function]
cls.add_method('Cancel',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function]
cls.add_method('Destroy',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function]
cls.add_method('GetDelayLeft',
'ns3::Time',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function]
cls.add_method('GetImplementation',
'ns3::Ptr< ns3::SimulatorImpl >',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function]
cls.add_method('GetMaximumSimulationTime',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function]
cls.add_method('IsExpired',
'bool',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function]
cls.add_method('IsFinished',
'bool',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function]
cls.add_method('Now',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function]
cls.add_method('Remove',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function]
cls.add_method('SetImplementation',
'void',
[param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function]
cls.add_method('SetScheduler',
'void',
[param('ns3::ObjectFactory', 'schedulerFactory')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function]
cls.add_method('Stop',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & time) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time const &', 'time')],
is_static=True)
return
def register_Ns3Tag_methods(root_module, cls):
## tag.h (module 'network'): ns3::Tag::Tag() [constructor]
cls.add_constructor([])
## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Tag const &', 'arg0')])
## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_virtual=True)
## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3TagBuffer_methods(root_module, cls):
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')])
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor]
cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function]
cls.add_method('CopyFrom',
'void',
[param('ns3::TagBuffer', 'o')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function]
cls.add_method('ReadDouble',
'double',
[])
## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function]
cls.add_method('TrimAtEnd',
'void',
[param('uint32_t', 'trim')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function]
cls.add_method('WriteDouble',
'void',
[param('double', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'v')])
return
def register_Ns3Timer_methods(root_module, cls):
## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Timer const &', 'arg0')])
## timer.h (module 'core'): ns3::Timer::Timer() [constructor]
cls.add_constructor([])
## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer::DestroyPolicy destroyPolicy) [constructor]
cls.add_constructor([param('ns3::Timer::DestroyPolicy', 'destroyPolicy')])
## timer.h (module 'core'): void ns3::Timer::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelay() const [member function]
cls.add_method('GetDelay',
'ns3::Time',
[],
is_const=True)
## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelayLeft() const [member function]
cls.add_method('GetDelayLeft',
'ns3::Time',
[],
is_const=True)
## timer.h (module 'core'): ns3::Timer::State ns3::Timer::GetState() const [member function]
cls.add_method('GetState',
'ns3::Timer::State',
[],
is_const=True)
## timer.h (module 'core'): bool ns3::Timer::IsExpired() const [member function]
cls.add_method('IsExpired',
'bool',
[],
is_const=True)
## timer.h (module 'core'): bool ns3::Timer::IsRunning() const [member function]
cls.add_method('IsRunning',
'bool',
[],
is_const=True)
## timer.h (module 'core'): bool ns3::Timer::IsSuspended() const [member function]
cls.add_method('IsSuspended',
'bool',
[],
is_const=True)
## timer.h (module 'core'): void ns3::Timer::Remove() [member function]
cls.add_method('Remove',
'void',
[])
## timer.h (module 'core'): void ns3::Timer::Resume() [member function]
cls.add_method('Resume',
'void',
[])
## timer.h (module 'core'): void ns3::Timer::Schedule() [member function]
cls.add_method('Schedule',
'void',
[])
## timer.h (module 'core'): void ns3::Timer::Schedule(ns3::Time delay) [member function]
cls.add_method('Schedule',
'void',
[param('ns3::Time', 'delay')])
## timer.h (module 'core'): void ns3::Timer::SetDelay(ns3::Time const & delay) [member function]
cls.add_method('SetDelay',
'void',
[param('ns3::Time const &', 'delay')])
## timer.h (module 'core'): void ns3::Timer::Suspend() [member function]
cls.add_method('Suspend',
'void',
[])
return
def register_Ns3TimerImpl_methods(root_module, cls):
## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl() [constructor]
cls.add_constructor([])
## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl(ns3::TimerImpl const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimerImpl const &', 'arg0')])
## timer-impl.h (module 'core'): void ns3::TimerImpl::Invoke() [member function]
cls.add_method('Invoke',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## timer-impl.h (module 'core'): ns3::EventId ns3::TimerImpl::Schedule(ns3::Time const & delay) [member function]
cls.add_method('Schedule',
'ns3::EventId',
[param('ns3::Time const &', 'delay')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3TypeId_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor]
cls.add_constructor([param('char const *', 'name')])
## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor]
cls.add_constructor([param('ns3::TypeId const &', 'o')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('AddAttribute',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('AddAttribute',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function]
cls.add_method('AddTraceSource',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function]
cls.add_method('GetAttribute',
'ns3::TypeId::AttributeInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function]
cls.add_method('GetAttributeFullName',
'std::string',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function]
cls.add_method('GetAttributeN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function]
cls.add_method('GetConstructor',
'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function]
cls.add_method('GetGroupName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function]
cls.add_method('GetName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function]
cls.add_method('GetParent',
'ns3::TypeId',
[],
is_const=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function]
cls.add_method('GetRegistered',
'ns3::TypeId',
[param('uint32_t', 'i')],
is_static=True)
## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function]
cls.add_method('GetRegisteredN',
'uint32_t',
[],
is_static=True)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function]
cls.add_method('GetTraceSource',
'ns3::TypeId::TraceSourceInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function]
cls.add_method('GetTraceSourceN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function]
cls.add_method('GetUid',
'uint16_t',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function]
cls.add_method('HasConstructor',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function]
cls.add_method('HasParent',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function]
cls.add_method('HideFromDocumentation',
'ns3::TypeId',
[])
## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function]
cls.add_method('IsChildOf',
'bool',
[param('ns3::TypeId', 'other')],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function]
cls.add_method('LookupAttributeByName',
'bool',
[param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)],
is_const=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function]
cls.add_method('LookupByName',
'ns3::TypeId',
[param('std::string', 'name')],
is_static=True)
## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function]
cls.add_method('LookupTraceSourceByName',
'ns3::Ptr< ns3::TraceSourceAccessor const >',
[param('std::string', 'name')],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function]
cls.add_method('MustHideFromDocumentation',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function]
cls.add_method('SetAttributeInitialValue',
'bool',
[param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function]
cls.add_method('SetGroupName',
'ns3::TypeId',
[param('std::string', 'groupName')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function]
cls.add_method('SetParent',
'ns3::TypeId',
[param('ns3::TypeId', 'tid')])
## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function]
cls.add_method('SetUid',
'void',
[param('uint16_t', 'tid')])
return
def register_Ns3TypeIdAttributeInformation_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable]
cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable]
cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable]
cls.add_instance_attribute('flags', 'uint32_t', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable]
cls.add_instance_attribute('help', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable]
cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable]
cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False)
return
def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable]
cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable]
cls.add_instance_attribute('help', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
return
def register_Ns3Empty_methods(root_module, cls):
## empty.h (module 'core'): ns3::empty::empty() [constructor]
cls.add_constructor([])
## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor]
cls.add_constructor([param('ns3::empty const &', 'arg0')])
return
def register_Ns3Int64x64_t_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_unary_numeric_operator('-')
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', 'right'))
cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', 'right'))
cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', 'right'))
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>=')
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor]
cls.add_constructor([])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor]
cls.add_constructor([param('double', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor]
cls.add_constructor([param('long int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor]
cls.add_constructor([param('long long int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor]
cls.add_constructor([param('unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor]
cls.add_constructor([param('long unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor]
cls.add_constructor([param('long long unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor]
cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'o')])
## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function]
cls.add_method('GetDouble',
'double',
[],
is_const=True)
## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function]
cls.add_method('GetHigh',
'int64_t',
[],
is_const=True)
## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function]
cls.add_method('GetLow',
'uint64_t',
[],
is_const=True)
## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function]
cls.add_method('Invert',
'ns3::int64x64_t',
[param('uint64_t', 'v')],
is_static=True)
## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function]
cls.add_method('MulByInvert',
'void',
[param('ns3::int64x64_t const &', 'o')])
return
def register_Ns3AodvHelper_methods(root_module, cls):
## aodv-helper.h (module 'aodv'): ns3::AodvHelper::AodvHelper(ns3::AodvHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AodvHelper const &', 'arg0')])
## aodv-helper.h (module 'aodv'): ns3::AodvHelper::AodvHelper() [constructor]
cls.add_constructor([])
## aodv-helper.h (module 'aodv'): int64_t ns3::AodvHelper::AssignStreams(ns3::NodeContainer c, int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('ns3::NodeContainer', 'c'), param('int64_t', 'stream')])
## aodv-helper.h (module 'aodv'): ns3::AodvHelper * ns3::AodvHelper::Copy() const [member function]
cls.add_method('Copy',
'ns3::AodvHelper *',
[],
is_const=True, is_virtual=True)
## aodv-helper.h (module 'aodv'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::AodvHelper::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)
## aodv-helper.h (module 'aodv'): void ns3::AodvHelper::Set(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
return
def register_Ns3Chunk_methods(root_module, cls):
## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor]
cls.add_constructor([])
## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Chunk const &', 'arg0')])
## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_virtual=True)
## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3Header_methods(root_module, cls):
cls.add_output_stream_operator()
## header.h (module 'network'): ns3::Header::Header() [constructor]
cls.add_constructor([])
## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Header const &', 'arg0')])
## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_virtual=True)
## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3Ipv4Header_methods(root_module, cls):
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header(ns3::Ipv4Header const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Header const &', 'arg0')])
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header() [constructor]
cls.add_constructor([])
## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::DscpTypeToString(ns3::Ipv4Header::DscpType dscp) const [member function]
cls.add_method('DscpTypeToString',
'std::string',
[param('ns3::Ipv4Header::DscpType', 'dscp')],
is_const=True)
## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::EcnTypeToString(ns3::Ipv4Header::EcnType ecn) const [member function]
cls.add_method('EcnTypeToString',
'std::string',
[param('ns3::Ipv4Header::EcnType', 'ecn')],
is_const=True)
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::EnableChecksum() [member function]
cls.add_method('EnableChecksum',
'void',
[])
## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetDestination() const [member function]
cls.add_method('GetDestination',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType ns3::Ipv4Header::GetDscp() const [member function]
cls.add_method('GetDscp',
'ns3::Ipv4Header::DscpType',
[],
is_const=True)
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType ns3::Ipv4Header::GetEcn() const [member function]
cls.add_method('GetEcn',
'ns3::Ipv4Header::EcnType',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetFragmentOffset() const [member function]
cls.add_method('GetFragmentOffset',
'uint16_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetIdentification() const [member function]
cls.add_method('GetIdentification',
'uint16_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): ns3::TypeId ns3::Ipv4Header::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetPayloadSize() const [member function]
cls.add_method('GetPayloadSize',
'uint16_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetProtocol() const [member function]
cls.add_method('GetProtocol',
'uint8_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetSource() const [member function]
cls.add_method('GetSource',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTos() const [member function]
cls.add_method('GetTos',
'uint8_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTtl() const [member function]
cls.add_method('GetTtl',
'uint8_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): static ns3::TypeId ns3::Ipv4Header::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsChecksumOk() const [member function]
cls.add_method('IsChecksumOk',
'bool',
[],
is_const=True)
## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsDontFragment() const [member function]
cls.add_method('IsDontFragment',
'bool',
[],
is_const=True)
## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsLastFragment() const [member function]
cls.add_method('IsLastFragment',
'bool',
[],
is_const=True)
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDestination(ns3::Ipv4Address destination) [member function]
cls.add_method('SetDestination',
'void',
[param('ns3::Ipv4Address', 'destination')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDontFragment() [member function]
cls.add_method('SetDontFragment',
'void',
[])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDscp(ns3::Ipv4Header::DscpType dscp) [member function]
cls.add_method('SetDscp',
'void',
[param('ns3::Ipv4Header::DscpType', 'dscp')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetEcn(ns3::Ipv4Header::EcnType ecn) [member function]
cls.add_method('SetEcn',
'void',
[param('ns3::Ipv4Header::EcnType', 'ecn')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetFragmentOffset(uint16_t offsetBytes) [member function]
cls.add_method('SetFragmentOffset',
'void',
[param('uint16_t', 'offsetBytes')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetIdentification(uint16_t identification) [member function]
cls.add_method('SetIdentification',
'void',
[param('uint16_t', 'identification')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetLastFragment() [member function]
cls.add_method('SetLastFragment',
'void',
[])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMayFragment() [member function]
cls.add_method('SetMayFragment',
'void',
[])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMoreFragments() [member function]
cls.add_method('SetMoreFragments',
'void',
[])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetPayloadSize(uint16_t size) [member function]
cls.add_method('SetPayloadSize',
'void',
[param('uint16_t', 'size')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetProtocol(uint8_t num) [member function]
cls.add_method('SetProtocol',
'void',
[param('uint8_t', 'num')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetSource(ns3::Ipv4Address source) [member function]
cls.add_method('SetSource',
'void',
[param('ns3::Ipv4Address', 'source')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTos(uint8_t tos) [member function]
cls.add_method('SetTos',
'void',
[param('uint8_t', 'tos')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTtl(uint8_t ttl) [member function]
cls.add_method('SetTtl',
'void',
[param('uint8_t', 'ttl')])
return
def register_Ns3Ipv6Header_methods(root_module, cls):
## ipv6-header.h (module 'internet'): ns3::Ipv6Header::Ipv6Header(ns3::Ipv6Header const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Header const &', 'arg0')])
## ipv6-header.h (module 'internet'): ns3::Ipv6Header::Ipv6Header() [constructor]
cls.add_constructor([])
## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## ipv6-header.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6Header::GetDestinationAddress() const [member function]
cls.add_method('GetDestinationAddress',
'ns3::Ipv6Address',
[],
is_const=True)
## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::GetFlowLabel() const [member function]
cls.add_method('GetFlowLabel',
'uint32_t',
[],
is_const=True)
## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetHopLimit() const [member function]
cls.add_method('GetHopLimit',
'uint8_t',
[],
is_const=True)
## ipv6-header.h (module 'internet'): ns3::TypeId ns3::Ipv6Header::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetNextHeader() const [member function]
cls.add_method('GetNextHeader',
'uint8_t',
[],
is_const=True)
## ipv6-header.h (module 'internet'): uint16_t ns3::Ipv6Header::GetPayloadLength() const [member function]
cls.add_method('GetPayloadLength',
'uint16_t',
[],
is_const=True)
## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ipv6-header.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6Header::GetSourceAddress() const [member function]
cls.add_method('GetSourceAddress',
'ns3::Ipv6Address',
[],
is_const=True)
## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetTrafficClass() const [member function]
cls.add_method('GetTrafficClass',
'uint8_t',
[],
is_const=True)
## ipv6-header.h (module 'internet'): static ns3::TypeId ns3::Ipv6Header::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetDestinationAddress(ns3::Ipv6Address dst) [member function]
cls.add_method('SetDestinationAddress',
'void',
[param('ns3::Ipv6Address', 'dst')])
## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetFlowLabel(uint32_t flow) [member function]
cls.add_method('SetFlowLabel',
'void',
[param('uint32_t', 'flow')])
## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetHopLimit(uint8_t limit) [member function]
cls.add_method('SetHopLimit',
'void',
[param('uint8_t', 'limit')])
## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetNextHeader(uint8_t next) [member function]
cls.add_method('SetNextHeader',
'void',
[param('uint8_t', 'next')])
## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetPayloadLength(uint16_t len) [member function]
cls.add_method('SetPayloadLength',
'void',
[param('uint16_t', 'len')])
## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetSourceAddress(ns3::Ipv6Address src) [member function]
cls.add_method('SetSourceAddress',
'void',
[param('ns3::Ipv6Address', 'src')])
## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetTrafficClass(uint8_t traffic) [member function]
cls.add_method('SetTrafficClass',
'void',
[param('uint8_t', 'traffic')])
return
def register_Ns3Object_methods(root_module, cls):
## object.h (module 'core'): ns3::Object::Object() [constructor]
cls.add_constructor([])
## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function]
cls.add_method('AggregateObject',
'void',
[param('ns3::Ptr< ns3::Object >', 'other')])
## object.h (module 'core'): void ns3::Object::Dispose() [member function]
cls.add_method('Dispose',
'void',
[])
## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function]
cls.add_method('GetAggregateIterator',
'ns3::Object::AggregateIterator',
[],
is_const=True)
## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## object.h (module 'core'): void ns3::Object::Start() [member function]
cls.add_method('Start',
'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::DoStart() [member function]
cls.add_method('DoStart',
'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_Ns3RandomVariableStream_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::RandomVariableStream::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::RandomVariableStream::RandomVariableStream() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetStream(int64_t stream) [member function]
cls.add_method('SetStream',
'void',
[param('int64_t', 'stream')])
## random-variable-stream.h (module 'core'): int64_t ns3::RandomVariableStream::GetStream() const [member function]
cls.add_method('GetStream',
'int64_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetAntithetic(bool isAntithetic) [member function]
cls.add_method('SetAntithetic',
'void',
[param('bool', 'isAntithetic')])
## random-variable-stream.h (module 'core'): bool ns3::RandomVariableStream::IsAntithetic() const [member function]
cls.add_method('IsAntithetic',
'bool',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::RandomVariableStream::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_pure_virtual=True, is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::RandomVariableStream::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_pure_virtual=True, is_virtual=True)
## random-variable-stream.h (module 'core'): ns3::RngStream * ns3::RandomVariableStream::Peek() const [member function]
cls.add_method('Peek',
'ns3::RngStream *',
[],
is_const=True, visibility='protected')
return
def register_Ns3SequentialRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::SequentialRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable::SequentialRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMin() const [member function]
cls.add_method('GetMin',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMax() const [member function]
cls.add_method('GetMax',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): ns3::Ptr<ns3::RandomVariableStream> ns3::SequentialRandomVariable::GetIncrement() const [member function]
cls.add_method('GetIncrement',
'ns3::Ptr< ns3::RandomVariableStream >',
[],
is_const=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetConsecutive() const [member function]
cls.add_method('GetConsecutive',
'uint32_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [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__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'): 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::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::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'): 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_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_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_comparison_operator('!=')
cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', 'right'))
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>=')
## nstime.h (module 'core'): ns3::Time::Time() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor]
cls.add_constructor([param('ns3::Time const &', 'o')])
## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor]
cls.add_constructor([param('double', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor]
cls.add_constructor([param('long int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor]
cls.add_constructor([param('long long int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor]
cls.add_constructor([param('unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor]
cls.add_constructor([param('long unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor]
cls.add_constructor([param('long long unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor]
cls.add_constructor([param('std::string const &', 's')])
## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & value) [constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'value')])
## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function]
cls.add_method('Compare',
'int',
[param('ns3::Time const &', 'o')],
is_const=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & from, ns3::Time::Unit timeUnit) [member function]
cls.add_method('From',
'ns3::Time',
[param('ns3::int64x64_t const &', 'from'), param('ns3::Time::Unit', 'timeUnit')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function]
cls.add_method('From',
'ns3::Time',
[param('ns3::int64x64_t const &', 'value')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit timeUnit) [member function]
cls.add_method('FromDouble',
'ns3::Time',
[param('double', 'value'), param('ns3::Time::Unit', 'timeUnit')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit timeUnit) [member function]
cls.add_method('FromInteger',
'ns3::Time',
[param('uint64_t', 'value'), param('ns3::Time::Unit', 'timeUnit')],
is_static=True)
## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function]
cls.add_method('GetDouble',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function]
cls.add_method('GetFemtoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function]
cls.add_method('GetInteger',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function]
cls.add_method('GetMicroSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function]
cls.add_method('GetMilliSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function]
cls.add_method('GetNanoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function]
cls.add_method('GetPicoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function]
cls.add_method('GetResolution',
'ns3::Time::Unit',
[],
is_static=True)
## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function]
cls.add_method('GetSeconds',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function]
cls.add_method('GetTimeStep',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function]
cls.add_method('IsNegative',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function]
cls.add_method('IsPositive',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function]
cls.add_method('IsStrictlyNegative',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function]
cls.add_method('IsStrictlyPositive',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function]
cls.add_method('IsZero',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): static 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'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit timeUnit) const [member function]
cls.add_method('To',
'ns3::int64x64_t',
[param('ns3::Time::Unit', 'timeUnit')],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit timeUnit) const [member function]
cls.add_method('ToDouble',
'double',
[param('ns3::Time::Unit', 'timeUnit')],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit timeUnit) const [member function]
cls.add_method('ToInteger',
'int64_t',
[param('ns3::Time::Unit', 'timeUnit')],
is_const=True)
return
def register_Ns3TraceSourceAccessor_methods(root_module, cls):
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')])
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor]
cls.add_constructor([])
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function]
cls.add_method('Connect',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function]
cls.add_method('ConnectWithoutContext',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function]
cls.add_method('Disconnect',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function]
cls.add_method('DisconnectWithoutContext',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3Trailer_methods(root_module, cls):
cls.add_output_stream_operator()
## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor]
cls.add_constructor([])
## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Trailer const &', 'arg0')])
## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'end')],
is_pure_virtual=True, is_virtual=True)
## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3TriangularRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::TriangularRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable::TriangularRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMin() const [member function]
cls.add_method('GetMin',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMax() const [member function]
cls.add_method('GetMax',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue(double mean, double min, double max) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'min'), param('double', 'max')])
## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger(uint32_t mean, uint32_t min, uint32_t max) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'min'), param('uint32_t', 'max')])
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3UniformRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::UniformRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable::UniformRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMin() const [member function]
cls.add_method('GetMin',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMax() const [member function]
cls.add_method('GetMax',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue(double min, double max) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'min'), param('double', 'max')])
## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger(uint32_t min, uint32_t max) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'min'), param('uint32_t', 'max')])
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3WeibullRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::WeibullRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable::WeibullRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetScale() const [member function]
cls.add_method('GetScale',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetShape() const [member function]
cls.add_method('GetShape',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue(double scale, double shape, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'scale'), param('double', 'shape'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger(uint32_t scale, uint32_t shape, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'scale'), param('uint32_t', 'shape'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3WifiMacHeader_methods(root_module, cls):
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader::WifiMacHeader(ns3::WifiMacHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiMacHeader const &', 'arg0')])
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader::WifiMacHeader() [constructor]
cls.add_constructor([])
## wifi-mac-header.h (module 'wifi'): uint32_t ns3::WifiMacHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## wifi-mac-header.h (module 'wifi'): ns3::Mac48Address ns3::WifiMacHeader::GetAddr1() const [member function]
cls.add_method('GetAddr1',
'ns3::Mac48Address',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): ns3::Mac48Address ns3::WifiMacHeader::GetAddr2() const [member function]
cls.add_method('GetAddr2',
'ns3::Mac48Address',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): ns3::Mac48Address ns3::WifiMacHeader::GetAddr3() const [member function]
cls.add_method('GetAddr3',
'ns3::Mac48Address',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): ns3::Mac48Address ns3::WifiMacHeader::GetAddr4() const [member function]
cls.add_method('GetAddr4',
'ns3::Mac48Address',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): ns3::Time ns3::WifiMacHeader::GetDuration() const [member function]
cls.add_method('GetDuration',
'ns3::Time',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint16_t ns3::WifiMacHeader::GetFragmentNumber() const [member function]
cls.add_method('GetFragmentNumber',
'uint16_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): ns3::TypeId ns3::WifiMacHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader::QosAckPolicy ns3::WifiMacHeader::GetQosAckPolicy() const [member function]
cls.add_method('GetQosAckPolicy',
'ns3::WifiMacHeader::QosAckPolicy',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint8_t ns3::WifiMacHeader::GetQosTid() const [member function]
cls.add_method('GetQosTid',
'uint8_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint8_t ns3::WifiMacHeader::GetQosTxopLimit() const [member function]
cls.add_method('GetQosTxopLimit',
'uint8_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint16_t ns3::WifiMacHeader::GetRawDuration() const [member function]
cls.add_method('GetRawDuration',
'uint16_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint16_t ns3::WifiMacHeader::GetSequenceControl() const [member function]
cls.add_method('GetSequenceControl',
'uint16_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint16_t ns3::WifiMacHeader::GetSequenceNumber() const [member function]
cls.add_method('GetSequenceNumber',
'uint16_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint32_t ns3::WifiMacHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## wifi-mac-header.h (module 'wifi'): uint32_t ns3::WifiMacHeader::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacType ns3::WifiMacHeader::GetType() const [member function]
cls.add_method('GetType',
'ns3::WifiMacType',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): static ns3::TypeId ns3::WifiMacHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wifi-mac-header.h (module 'wifi'): char const * ns3::WifiMacHeader::GetTypeString() const [member function]
cls.add_method('GetTypeString',
'char const *',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsAck() const [member function]
cls.add_method('IsAck',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsAction() const [member function]
cls.add_method('IsAction',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsAssocReq() const [member function]
cls.add_method('IsAssocReq',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsAssocResp() const [member function]
cls.add_method('IsAssocResp',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsAuthentication() const [member function]
cls.add_method('IsAuthentication',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsBeacon() const [member function]
cls.add_method('IsBeacon',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsBlockAck() const [member function]
cls.add_method('IsBlockAck',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsBlockAckReq() const [member function]
cls.add_method('IsBlockAckReq',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsCfpoll() const [member function]
cls.add_method('IsCfpoll',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsCtl() const [member function]
cls.add_method('IsCtl',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsCts() const [member function]
cls.add_method('IsCts',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsData() const [member function]
cls.add_method('IsData',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsDeauthentication() const [member function]
cls.add_method('IsDeauthentication',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsDisassociation() const [member function]
cls.add_method('IsDisassociation',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsFromDs() const [member function]
cls.add_method('IsFromDs',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsMgt() const [member function]
cls.add_method('IsMgt',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsMoreFragments() const [member function]
cls.add_method('IsMoreFragments',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsMultihopAction() const [member function]
cls.add_method('IsMultihopAction',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsProbeReq() const [member function]
cls.add_method('IsProbeReq',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsProbeResp() const [member function]
cls.add_method('IsProbeResp',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsQosAck() const [member function]
cls.add_method('IsQosAck',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsQosAmsdu() const [member function]
cls.add_method('IsQosAmsdu',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsQosBlockAck() const [member function]
cls.add_method('IsQosBlockAck',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsQosData() const [member function]
cls.add_method('IsQosData',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsQosEosp() const [member function]
cls.add_method('IsQosEosp',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsQosNoAck() const [member function]
cls.add_method('IsQosNoAck',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsReassocReq() const [member function]
cls.add_method('IsReassocReq',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsReassocResp() const [member function]
cls.add_method('IsReassocResp',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsRetry() const [member function]
cls.add_method('IsRetry',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsRts() const [member function]
cls.add_method('IsRts',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsToDs() const [member function]
cls.add_method('IsToDs',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAction() [member function]
cls.add_method('SetAction',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAddr1(ns3::Mac48Address address) [member function]
cls.add_method('SetAddr1',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAddr2(ns3::Mac48Address address) [member function]
cls.add_method('SetAddr2',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAddr3(ns3::Mac48Address address) [member function]
cls.add_method('SetAddr3',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAddr4(ns3::Mac48Address address) [member function]
cls.add_method('SetAddr4',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAssocReq() [member function]
cls.add_method('SetAssocReq',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAssocResp() [member function]
cls.add_method('SetAssocResp',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetBeacon() [member function]
cls.add_method('SetBeacon',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetBlockAck() [member function]
cls.add_method('SetBlockAck',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetBlockAckReq() [member function]
cls.add_method('SetBlockAckReq',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetDsFrom() [member function]
cls.add_method('SetDsFrom',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetDsNotFrom() [member function]
cls.add_method('SetDsNotFrom',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetDsNotTo() [member function]
cls.add_method('SetDsNotTo',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetDsTo() [member function]
cls.add_method('SetDsTo',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetDuration(ns3::Time duration) [member function]
cls.add_method('SetDuration',
'void',
[param('ns3::Time', 'duration')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetFragmentNumber(uint8_t frag) [member function]
cls.add_method('SetFragmentNumber',
'void',
[param('uint8_t', 'frag')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetId(uint16_t id) [member function]
cls.add_method('SetId',
'void',
[param('uint16_t', 'id')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetMoreFragments() [member function]
cls.add_method('SetMoreFragments',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetMultihopAction() [member function]
cls.add_method('SetMultihopAction',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetNoMoreFragments() [member function]
cls.add_method('SetNoMoreFragments',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetNoRetry() [member function]
cls.add_method('SetNoRetry',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetProbeReq() [member function]
cls.add_method('SetProbeReq',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetProbeResp() [member function]
cls.add_method('SetProbeResp',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosAckPolicy(ns3::WifiMacHeader::QosAckPolicy arg0) [member function]
cls.add_method('SetQosAckPolicy',
'void',
[param('ns3::WifiMacHeader::QosAckPolicy', 'arg0')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosAmsdu() [member function]
cls.add_method('SetQosAmsdu',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosBlockAck() [member function]
cls.add_method('SetQosBlockAck',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosEosp() [member function]
cls.add_method('SetQosEosp',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosNoAck() [member function]
cls.add_method('SetQosNoAck',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosNoAmsdu() [member function]
cls.add_method('SetQosNoAmsdu',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosNoEosp() [member function]
cls.add_method('SetQosNoEosp',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosNormalAck() [member function]
cls.add_method('SetQosNormalAck',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosTid(uint8_t tid) [member function]
cls.add_method('SetQosTid',
'void',
[param('uint8_t', 'tid')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosTxopLimit(uint8_t txop) [member function]
cls.add_method('SetQosTxopLimit',
'void',
[param('uint8_t', 'txop')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetRawDuration(uint16_t duration) [member function]
cls.add_method('SetRawDuration',
'void',
[param('uint16_t', 'duration')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetRetry() [member function]
cls.add_method('SetRetry',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetSequenceNumber(uint16_t seq) [member function]
cls.add_method('SetSequenceNumber',
'void',
[param('uint16_t', 'seq')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetType(ns3::WifiMacType type) [member function]
cls.add_method('SetType',
'void',
[param('ns3::WifiMacType', 'type')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetTypeData() [member function]
cls.add_method('SetTypeData',
'void',
[])
return
def register_Ns3ZetaRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZetaRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable::ZetaRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue(double alpha) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'alpha')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger(uint32_t alpha) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'alpha')])
## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ZipfRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZipfRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable::ZipfRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue(uint32_t n, double alpha) [member function]
cls.add_method('GetValue',
'double',
[param('uint32_t', 'n'), param('double', 'alpha')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger(uint32_t n, uint32_t alpha) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'n'), param('uint32_t', 'alpha')])
## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ArpCache_methods(root_module, cls):
## arp-cache.h (module 'internet'): ns3::ArpCache::ArpCache() [constructor]
cls.add_constructor([])
## arp-cache.h (module 'internet'): ns3::ArpCache::Entry * ns3::ArpCache::Add(ns3::Ipv4Address to) [member function]
cls.add_method('Add',
'ns3::ArpCache::Entry *',
[param('ns3::Ipv4Address', 'to')])
## arp-cache.h (module 'internet'): void ns3::ArpCache::Flush() [member function]
cls.add_method('Flush',
'void',
[])
## arp-cache.h (module 'internet'): ns3::Time ns3::ArpCache::GetAliveTimeout() const [member function]
cls.add_method('GetAliveTimeout',
'ns3::Time',
[],
is_const=True)
## arp-cache.h (module 'internet'): ns3::Time ns3::ArpCache::GetDeadTimeout() const [member function]
cls.add_method('GetDeadTimeout',
'ns3::Time',
[],
is_const=True)
## arp-cache.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::ArpCache::GetDevice() const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[],
is_const=True)
## arp-cache.h (module 'internet'): ns3::Ptr<ns3::Ipv4Interface> ns3::ArpCache::GetInterface() const [member function]
cls.add_method('GetInterface',
'ns3::Ptr< ns3::Ipv4Interface >',
[],
is_const=True)
## arp-cache.h (module 'internet'): static ns3::TypeId ns3::ArpCache::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## arp-cache.h (module 'internet'): ns3::Time ns3::ArpCache::GetWaitReplyTimeout() const [member function]
cls.add_method('GetWaitReplyTimeout',
'ns3::Time',
[],
is_const=True)
## arp-cache.h (module 'internet'): ns3::ArpCache::Entry * ns3::ArpCache::Lookup(ns3::Ipv4Address destination) [member function]
cls.add_method('Lookup',
'ns3::ArpCache::Entry *',
[param('ns3::Ipv4Address', 'destination')])
## arp-cache.h (module 'internet'): void ns3::ArpCache::SetAliveTimeout(ns3::Time aliveTimeout) [member function]
cls.add_method('SetAliveTimeout',
'void',
[param('ns3::Time', 'aliveTimeout')])
## arp-cache.h (module 'internet'): void ns3::ArpCache::SetArpRequestCallback(ns3::Callback<void, ns3::Ptr<ns3::ArpCache const>, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arpRequestCallback) [member function]
cls.add_method('SetArpRequestCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::ArpCache const >, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arpRequestCallback')])
## arp-cache.h (module 'internet'): void ns3::ArpCache::SetDeadTimeout(ns3::Time deadTimeout) [member function]
cls.add_method('SetDeadTimeout',
'void',
[param('ns3::Time', 'deadTimeout')])
## arp-cache.h (module 'internet'): void ns3::ArpCache::SetDevice(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::Ipv4Interface> interface) [member function]
cls.add_method('SetDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Ipv4Interface >', 'interface')])
## arp-cache.h (module 'internet'): void ns3::ArpCache::SetWaitReplyTimeout(ns3::Time waitReplyTimeout) [member function]
cls.add_method('SetWaitReplyTimeout',
'void',
[param('ns3::Time', 'waitReplyTimeout')])
## arp-cache.h (module 'internet'): void ns3::ArpCache::StartWaitReplyTimer() [member function]
cls.add_method('StartWaitReplyTimer',
'void',
[])
## arp-cache.h (module 'internet'): void ns3::ArpCache::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3ArpCacheEntry_methods(root_module, cls):
## arp-cache.h (module 'internet'): ns3::ArpCache::Entry::Entry(ns3::ArpCache::Entry const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ArpCache::Entry const &', 'arg0')])
## arp-cache.h (module 'internet'): ns3::ArpCache::Entry::Entry(ns3::ArpCache * arp) [constructor]
cls.add_constructor([param('ns3::ArpCache *', 'arp')])
## arp-cache.h (module 'internet'): void ns3::ArpCache::Entry::ClearRetries() [member function]
cls.add_method('ClearRetries',
'void',
[])
## arp-cache.h (module 'internet'): ns3::Ptr<ns3::Packet> ns3::ArpCache::Entry::DequeuePending() [member function]
cls.add_method('DequeuePending',
'ns3::Ptr< ns3::Packet >',
[])
## arp-cache.h (module 'internet'): ns3::Ipv4Address ns3::ArpCache::Entry::GetIpv4Address() const [member function]
cls.add_method('GetIpv4Address',
'ns3::Ipv4Address',
[],
is_const=True)
## arp-cache.h (module 'internet'): ns3::Address ns3::ArpCache::Entry::GetMacAddress() const [member function]
cls.add_method('GetMacAddress',
'ns3::Address',
[],
is_const=True)
## arp-cache.h (module 'internet'): uint32_t ns3::ArpCache::Entry::GetRetries() const [member function]
cls.add_method('GetRetries',
'uint32_t',
[],
is_const=True)
## arp-cache.h (module 'internet'): void ns3::ArpCache::Entry::IncrementRetries() [member function]
cls.add_method('IncrementRetries',
'void',
[])
## arp-cache.h (module 'internet'): bool ns3::ArpCache::Entry::IsAlive() [member function]
cls.add_method('IsAlive',
'bool',
[])
## arp-cache.h (module 'internet'): bool ns3::ArpCache::Entry::IsDead() [member function]
cls.add_method('IsDead',
'bool',
[])
## arp-cache.h (module 'internet'): bool ns3::ArpCache::Entry::IsExpired() const [member function]
cls.add_method('IsExpired',
'bool',
[],
is_const=True)
## arp-cache.h (module 'internet'): bool ns3::ArpCache::Entry::IsWaitReply() [member function]
cls.add_method('IsWaitReply',
'bool',
[])
## arp-cache.h (module 'internet'): void ns3::ArpCache::Entry::MarkAlive(ns3::Address macAddress) [member function]
cls.add_method('MarkAlive',
'void',
[param('ns3::Address', 'macAddress')])
## arp-cache.h (module 'internet'): void ns3::ArpCache::Entry::MarkDead() [member function]
cls.add_method('MarkDead',
'void',
[])
## arp-cache.h (module 'internet'): void ns3::ArpCache::Entry::MarkWaitReply(ns3::Ptr<ns3::Packet> waiting) [member function]
cls.add_method('MarkWaitReply',
'void',
[param('ns3::Ptr< ns3::Packet >', 'waiting')])
## arp-cache.h (module 'internet'): void ns3::ArpCache::Entry::SetIpv4Address(ns3::Ipv4Address destination) [member function]
cls.add_method('SetIpv4Address',
'void',
[param('ns3::Ipv4Address', 'destination')])
## arp-cache.h (module 'internet'): bool ns3::ArpCache::Entry::UpdateWaitReply(ns3::Ptr<ns3::Packet> waiting) [member function]
cls.add_method('UpdateWaitReply',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'waiting')])
return
def register_Ns3AttributeAccessor_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function]
cls.add_method('Get',
'bool',
[param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function]
cls.add_method('HasGetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function]
cls.add_method('HasSetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function]
cls.add_method('Set',
'bool',
[param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeChecker_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function]
cls.add_method('Copy',
'bool',
[param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function]
cls.add_method('CreateValidValue',
'ns3::Ptr< ns3::AttributeValue >',
[param('ns3::AttributeValue const &', 'value')],
is_const=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3CallbackChecker_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')])
return
def register_Ns3CallbackImplBase_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')])
## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3CallbackValue_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor]
cls.add_constructor([param('ns3::CallbackBase const &', 'base')])
## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function]
cls.add_method('Set',
'void',
[param('ns3::CallbackBase', 'base')])
return
def register_Ns3ConstantRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ConstantRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable::ConstantRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetConstant() const [member function]
cls.add_method('GetConstant',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue(double constant) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'constant')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger(uint32_t constant) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'constant')])
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3DeterministicRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::DeterministicRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable::DeterministicRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::DeterministicRandomVariable::SetValueArray(double * values, uint64_t length) [member function]
cls.add_method('SetValueArray',
'void',
[param('double *', 'values'), param('uint64_t', 'length')])
## random-variable-stream.h (module 'core'): double ns3::DeterministicRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::DeterministicRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3EmpiricalRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable::EmpiricalRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::CDF(double v, double c) [member function]
cls.add_method('CDF',
'void',
[param('double', 'v'), param('double', 'c')])
## random-variable-stream.h (module 'core'): uint32_t ns3::EmpiricalRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::EmpiricalRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::Interpolate(double arg0, double arg1, double arg2, double arg3, double arg4) [member function]
cls.add_method('Interpolate',
'double',
[param('double', 'arg0'), param('double', 'arg1'), param('double', 'arg2'), param('double', 'arg3'), param('double', 'arg4')],
visibility='private', is_virtual=True)
## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::Validate() [member function]
cls.add_method('Validate',
'void',
[],
visibility='private', is_virtual=True)
return
def register_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_Ns3EnumChecker_methods(root_module, cls):
## enum.h (module 'core'): ns3::EnumChecker::EnumChecker(ns3::EnumChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnumChecker const &', 'arg0')])
## enum.h (module 'core'): ns3::EnumChecker::EnumChecker() [constructor]
cls.add_constructor([])
## enum.h (module 'core'): void ns3::EnumChecker::Add(int v, std::string name) [member function]
cls.add_method('Add',
'void',
[param('int', 'v'), param('std::string', 'name')])
## enum.h (module 'core'): void ns3::EnumChecker::AddDefault(int v, std::string name) [member function]
cls.add_method('AddDefault',
'void',
[param('int', 'v'), param('std::string', 'name')])
## enum.h (module 'core'): bool ns3::EnumChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumChecker::Copy(ns3::AttributeValue const & src, ns3::AttributeValue & dst) const [member function]
cls.add_method('Copy',
'bool',
[param('ns3::AttributeValue const &', 'src'), param('ns3::AttributeValue &', 'dst')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): std::string ns3::EnumChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): std::string ns3::EnumChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_const=True, is_virtual=True)
return
def register_Ns3EnumValue_methods(root_module, cls):
## enum.h (module 'core'): ns3::EnumValue::EnumValue(ns3::EnumValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnumValue const &', 'arg0')])
## enum.h (module 'core'): ns3::EnumValue::EnumValue() [constructor]
cls.add_constructor([])
## enum.h (module 'core'): ns3::EnumValue::EnumValue(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumValue::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)
## enum.h (module 'core'): int ns3::EnumValue::Get() const [member function]
cls.add_method('Get',
'int',
[],
is_const=True)
## enum.h (module 'core'): std::string ns3::EnumValue::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)
## enum.h (module 'core'): void ns3::EnumValue::Set(int v) [member function]
cls.add_method('Set',
'void',
[param('int', 'v')])
return
def register_Ns3ErlangRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ErlangRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable::ErlangRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetK() const [member function]
cls.add_method('GetK',
'uint32_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetLambda() const [member function]
cls.add_method('GetLambda',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue(uint32_t k, double lambda) [member function]
cls.add_method('GetValue',
'double',
[param('uint32_t', 'k'), param('double', 'lambda')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger(uint32_t k, uint32_t lambda) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'k'), param('uint32_t', 'lambda')])
## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3EventImpl_methods(root_module, cls):
## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [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_Ns3ExponentialRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ExponentialRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable::ExponentialRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue(double mean, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger(uint32_t mean, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3GammaRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::GammaRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable::GammaRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetBeta() const [member function]
cls.add_method('GetBeta',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue(double alpha, double beta) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'alpha'), param('double', 'beta')])
## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger(uint32_t alpha, uint32_t beta) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'alpha'), param('uint32_t', 'beta')])
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3IpL4Protocol_methods(root_module, cls):
## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::IpL4Protocol() [constructor]
cls.add_constructor([])
## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::IpL4Protocol(ns3::IpL4Protocol const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IpL4Protocol const &', 'arg0')])
## ip-l4-protocol.h (module 'internet'): ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv4Address,ns3::Ipv4Address,unsigned char,ns3::Ptr<ns3::Ipv4Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::IpL4Protocol::GetDownTarget() const [member function]
cls.add_method('GetDownTarget',
'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv4Address, ns3::Ipv4Address, unsigned char, ns3::Ptr< ns3::Ipv4Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ip-l4-protocol.h (module 'internet'): ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv6Address,ns3::Ipv6Address,unsigned char,ns3::Ptr<ns3::Ipv6Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::IpL4Protocol::GetDownTarget6() const [member function]
cls.add_method('GetDownTarget6',
'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv6Address, ns3::Ipv6Address, unsigned char, ns3::Ptr< ns3::Ipv6Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ip-l4-protocol.h (module 'internet'): int ns3::IpL4Protocol::GetProtocolNumber() const [member function]
cls.add_method('GetProtocolNumber',
'int',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ip-l4-protocol.h (module 'internet'): static ns3::TypeId ns3::IpL4Protocol::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::IpL4Protocol::Receive(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::Ipv4Interface> incomingInterface) [member function]
cls.add_method('Receive',
'ns3::IpL4Protocol::RxStatus',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::Ipv4Interface >', 'incomingInterface')],
is_pure_virtual=True, is_virtual=True)
## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::IpL4Protocol::Receive(ns3::Ptr<ns3::Packet> p, ns3::Ipv6Address & src, ns3::Ipv6Address & dst, ns3::Ptr<ns3::Ipv6Interface> incomingInterface) [member function]
cls.add_method('Receive',
'ns3::IpL4Protocol::RxStatus',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv6Address &', 'src'), param('ns3::Ipv6Address &', 'dst'), param('ns3::Ptr< ns3::Ipv6Interface >', 'incomingInterface')],
is_pure_virtual=True, is_virtual=True)
## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::ReceiveIcmp(ns3::Ipv4Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, ns3::Ipv4Address payloadSource, ns3::Ipv4Address payloadDestination, uint8_t const * payload) [member function]
cls.add_method('ReceiveIcmp',
'void',
[param('ns3::Ipv4Address', 'icmpSource'), param('uint8_t', 'icmpTtl'), param('uint8_t', 'icmpType'), param('uint8_t', 'icmpCode'), param('uint32_t', 'icmpInfo'), param('ns3::Ipv4Address', 'payloadSource'), param('ns3::Ipv4Address', 'payloadDestination'), param('uint8_t const *', 'payload')],
is_virtual=True)
## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::ReceiveIcmp(ns3::Ipv6Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, ns3::Ipv6Address payloadSource, ns3::Ipv6Address payloadDestination, uint8_t const * payload) [member function]
cls.add_method('ReceiveIcmp',
'void',
[param('ns3::Ipv6Address', 'icmpSource'), param('uint8_t', 'icmpTtl'), param('uint8_t', 'icmpType'), param('uint8_t', 'icmpCode'), param('uint32_t', 'icmpInfo'), param('ns3::Ipv6Address', 'payloadSource'), param('ns3::Ipv6Address', 'payloadDestination'), param('uint8_t const *', 'payload')],
is_virtual=True)
## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::SetDownTarget(ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv4Address,ns3::Ipv4Address,unsigned char,ns3::Ptr<ns3::Ipv4Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function]
cls.add_method('SetDownTarget',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv4Address, ns3::Ipv4Address, unsigned char, ns3::Ptr< ns3::Ipv4Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::SetDownTarget6(ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv6Address,ns3::Ipv6Address,unsigned char,ns3::Ptr<ns3::Ipv6Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function]
cls.add_method('SetDownTarget6',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv6Address, ns3::Ipv6Address, unsigned char, ns3::Ptr< ns3::Ipv6Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3Ipv4_methods(root_module, cls):
## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4(ns3::Ipv4 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4 const &', 'arg0')])
## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4() [constructor]
cls.add_constructor([])
## ipv4.h (module 'internet'): bool ns3::Ipv4::AddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('AddAddress',
'bool',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('AddInterface',
'uint32_t',
[param('ns3::Ptr< ns3::NetDevice >', 'device')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4::CreateRawSocket() [member function]
cls.add_method('CreateRawSocket',
'ns3::Ptr< ns3::Socket >',
[],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function]
cls.add_method('DeleteRawSocket',
'void',
[param('ns3::Ptr< ns3::Socket >', 'socket')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4::GetAddress(uint32_t interface, uint32_t addressIndex) const [member function]
cls.add_method('GetAddress',
'ns3::Ipv4InterfaceAddress',
[param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForAddress(ns3::Ipv4Address address) const [member function]
cls.add_method('GetInterfaceForAddress',
'int32_t',
[param('ns3::Ipv4Address', 'address')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function]
cls.add_method('GetInterfaceForDevice',
'int32_t',
[param('ns3::Ptr< ns3::NetDevice const >', 'device')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForPrefix(ns3::Ipv4Address address, ns3::Ipv4Mask mask) const [member function]
cls.add_method('GetInterfaceForPrefix',
'int32_t',
[param('ns3::Ipv4Address', 'address'), param('ns3::Ipv4Mask', 'mask')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMetric(uint32_t interface) const [member function]
cls.add_method('GetMetric',
'uint16_t',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMtu(uint32_t interface) const [member function]
cls.add_method('GetMtu',
'uint16_t',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNAddresses(uint32_t interface) const [member function]
cls.add_method('GetNAddresses',
'uint32_t',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNInterfaces() const [member function]
cls.add_method('GetNInterfaces',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4::GetNetDevice(uint32_t interface) [member function]
cls.add_method('GetNetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber) const [member function]
cls.add_method('GetProtocol',
'ns3::Ptr< ns3::IpL4Protocol >',
[param('int', 'protocolNumber')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4::GetRoutingProtocol() const [member function]
cls.add_method('GetRoutingProtocol',
'ns3::Ptr< ns3::Ipv4RoutingProtocol >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): static ns3::TypeId ns3::Ipv4::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function]
cls.add_method('Insert',
'void',
[param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function]
cls.add_method('IsDestinationAddress',
'bool',
[param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::IsForwarding(uint32_t interface) const [member function]
cls.add_method('IsForwarding',
'bool',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::IsUp(uint32_t interface) const [member function]
cls.add_method('IsUp',
'bool',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, uint32_t addressIndex) [member function]
cls.add_method('RemoveAddress',
'bool',
[param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function]
cls.add_method('SelectSourceAddress',
'ns3::Ipv4Address',
[param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('SendWithHeader',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetDown(uint32_t interface) [member function]
cls.add_method('SetDown',
'void',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetForwarding(uint32_t interface, bool val) [member function]
cls.add_method('SetForwarding',
'void',
[param('uint32_t', 'interface'), param('bool', 'val')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetMetric(uint32_t interface, uint16_t metric) [member function]
cls.add_method('SetMetric',
'void',
[param('uint32_t', 'interface'), param('uint16_t', 'metric')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function]
cls.add_method('SetRoutingProtocol',
'void',
[param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetUp(uint32_t interface) [member function]
cls.add_method('SetUp',
'void',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ipv4::IF_ANY [variable]
cls.add_static_attribute('IF_ANY', 'uint32_t const', is_const=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::GetIpForward() const [member function]
cls.add_method('GetIpForward',
'bool',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::GetWeakEsModel() const [member function]
cls.add_method('GetWeakEsModel',
'bool',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetIpForward(bool forward) [member function]
cls.add_method('SetIpForward',
'void',
[param('bool', 'forward')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetWeakEsModel(bool model) [member function]
cls.add_method('SetWeakEsModel',
'void',
[param('bool', 'model')],
is_pure_virtual=True, visibility='private', is_virtual=True)
return
def register_Ns3Ipv4AddressChecker_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')])
return
def register_Ns3Ipv4AddressValue_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor]
cls.add_constructor([param('ns3::Ipv4Address const &', 'value')])
## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv4Address const &', 'value')])
return
def register_Ns3Ipv4Interface_methods(root_module, cls):
## ipv4-interface.h (module 'internet'): ns3::Ipv4Interface::Ipv4Interface(ns3::Ipv4Interface const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Interface const &', 'arg0')])
## ipv4-interface.h (module 'internet'): ns3::Ipv4Interface::Ipv4Interface() [constructor]
cls.add_constructor([])
## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::AddAddress(ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('AddAddress',
'bool',
[param('ns3::Ipv4InterfaceAddress', 'address')])
## ipv4-interface.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4Interface::GetAddress(uint32_t index) const [member function]
cls.add_method('GetAddress',
'ns3::Ipv4InterfaceAddress',
[param('uint32_t', 'index')],
is_const=True)
## ipv4-interface.h (module 'internet'): ns3::Ptr<ns3::ArpCache> ns3::Ipv4Interface::GetArpCache() const [member function]
cls.add_method('GetArpCache',
'ns3::Ptr< ns3::ArpCache >',
[],
is_const=True)
## ipv4-interface.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Interface::GetDevice() const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[],
is_const=True)
## ipv4-interface.h (module 'internet'): uint16_t ns3::Ipv4Interface::GetMetric() const [member function]
cls.add_method('GetMetric',
'uint16_t',
[],
is_const=True)
## ipv4-interface.h (module 'internet'): uint32_t ns3::Ipv4Interface::GetNAddresses() const [member function]
cls.add_method('GetNAddresses',
'uint32_t',
[],
is_const=True)
## ipv4-interface.h (module 'internet'): static ns3::TypeId ns3::Ipv4Interface::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::IsDown() const [member function]
cls.add_method('IsDown',
'bool',
[],
is_const=True)
## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::IsForwarding() const [member function]
cls.add_method('IsForwarding',
'bool',
[],
is_const=True)
## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::IsUp() const [member function]
cls.add_method('IsUp',
'bool',
[],
is_const=True)
## ipv4-interface.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4Interface::RemoveAddress(uint32_t index) [member function]
cls.add_method('RemoveAddress',
'ns3::Ipv4InterfaceAddress',
[param('uint32_t', 'index')])
## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::Send(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Address dest) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Address', 'dest')])
## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetArpCache(ns3::Ptr<ns3::ArpCache> arg0) [member function]
cls.add_method('SetArpCache',
'void',
[param('ns3::Ptr< ns3::ArpCache >', 'arg0')])
## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetDevice(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('SetDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetDown() [member function]
cls.add_method('SetDown',
'void',
[])
## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetForwarding(bool val) [member function]
cls.add_method('SetForwarding',
'void',
[param('bool', 'val')])
## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetMetric(uint16_t metric) [member function]
cls.add_method('SetMetric',
'void',
[param('uint16_t', 'metric')])
## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetUp() [member function]
cls.add_method('SetUp',
'void',
[])
## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3Ipv4L3Protocol_methods(root_module, cls):
## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::Ipv4L3Protocol() [constructor]
cls.add_constructor([])
## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::AddAddress(uint32_t i, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('AddAddress',
'bool',
[param('uint32_t', 'i'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('AddInterface',
'uint32_t',
[param('ns3::Ptr< ns3::NetDevice >', 'device')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4L3Protocol::CreateRawSocket() [member function]
cls.add_method('CreateRawSocket',
'ns3::Ptr< ns3::Socket >',
[],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function]
cls.add_method('DeleteRawSocket',
'void',
[param('ns3::Ptr< ns3::Socket >', 'socket')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4L3Protocol::GetAddress(uint32_t interfaceIndex, uint32_t addressIndex) const [member function]
cls.add_method('GetAddress',
'ns3::Ipv4InterfaceAddress',
[param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Interface> ns3::Ipv4L3Protocol::GetInterface(uint32_t i) const [member function]
cls.add_method('GetInterface',
'ns3::Ptr< ns3::Ipv4Interface >',
[param('uint32_t', 'i')],
is_const=True)
## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForAddress(ns3::Ipv4Address addr) const [member function]
cls.add_method('GetInterfaceForAddress',
'int32_t',
[param('ns3::Ipv4Address', 'addr')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function]
cls.add_method('GetInterfaceForDevice',
'int32_t',
[param('ns3::Ptr< ns3::NetDevice const >', 'device')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForPrefix(ns3::Ipv4Address addr, ns3::Ipv4Mask mask) const [member function]
cls.add_method('GetInterfaceForPrefix',
'int32_t',
[param('ns3::Ipv4Address', 'addr'), param('ns3::Ipv4Mask', 'mask')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMetric(uint32_t i) const [member function]
cls.add_method('GetMetric',
'uint16_t',
[param('uint32_t', 'i')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMtu(uint32_t i) const [member function]
cls.add_method('GetMtu',
'uint16_t',
[param('uint32_t', 'i')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNAddresses(uint32_t interface) const [member function]
cls.add_method('GetNAddresses',
'uint32_t',
[param('uint32_t', 'interface')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNInterfaces() const [member function]
cls.add_method('GetNInterfaces',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4L3Protocol::GetNetDevice(uint32_t i) [member function]
cls.add_method('GetNetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4L3Protocol::GetProtocol(int protocolNumber) const [member function]
cls.add_method('GetProtocol',
'ns3::Ptr< ns3::IpL4Protocol >',
[param('int', 'protocolNumber')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4L3Protocol::GetRoutingProtocol() const [member function]
cls.add_method('GetRoutingProtocol',
'ns3::Ptr< ns3::Ipv4RoutingProtocol >',
[],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4L3Protocol::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function]
cls.add_method('Insert',
'void',
[param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function]
cls.add_method('IsDestinationAddress',
'bool',
[param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsForwarding(uint32_t i) const [member function]
cls.add_method('IsForwarding',
'bool',
[param('uint32_t', 'i')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsUp(uint32_t i) const [member function]
cls.add_method('IsUp',
'bool',
[param('uint32_t', 'i')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Receive(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::Packet const> p, uint16_t protocol, ns3::Address const & from, ns3::Address const & to, ns3::NetDevice::PacketType packetType) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'p'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'from'), param('ns3::Address const &', 'to'), param('ns3::NetDevice::PacketType', 'packetType')])
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function]
cls.add_method('Remove',
'void',
[param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')])
## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::RemoveAddress(uint32_t interfaceIndex, uint32_t addressIndex) [member function]
cls.add_method('RemoveAddress',
'bool',
[param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4L3Protocol::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function]
cls.add_method('SelectSourceAddress',
'ns3::Ipv4Address',
[param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('SendWithHeader',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDefaultTtl(uint8_t ttl) [member function]
cls.add_method('SetDefaultTtl',
'void',
[param('uint8_t', 'ttl')])
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDown(uint32_t i) [member function]
cls.add_method('SetDown',
'void',
[param('uint32_t', 'i')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetForwarding(uint32_t i, bool val) [member function]
cls.add_method('SetForwarding',
'void',
[param('uint32_t', 'i'), param('bool', 'val')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetMetric(uint32_t i, uint16_t metric) [member function]
cls.add_method('SetMetric',
'void',
[param('uint32_t', 'i'), param('uint16_t', 'metric')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function]
cls.add_method('SetRoutingProtocol',
'void',
[param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetUp(uint32_t i) [member function]
cls.add_method('SetUp',
'void',
[param('uint32_t', 'i')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::PROT_NUMBER [variable]
cls.add_static_attribute('PROT_NUMBER', 'uint16_t const', is_const=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::NotifyNewAggregate() [member function]
cls.add_method('NotifyNewAggregate',
'void',
[],
visibility='protected', is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetIpForward() const [member function]
cls.add_method('GetIpForward',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetWeakEsModel() const [member function]
cls.add_method('GetWeakEsModel',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetIpForward(bool forward) [member function]
cls.add_method('SetIpForward',
'void',
[param('bool', 'forward')],
visibility='private', is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetWeakEsModel(bool model) [member function]
cls.add_method('SetWeakEsModel',
'void',
[param('bool', 'model')],
visibility='private', is_virtual=True)
return
def register_Ns3Ipv4MaskChecker_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')])
return
def register_Ns3Ipv4MaskValue_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor]
cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')])
## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv4Mask',
[],
is_const=True)
## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv4Mask const &', 'value')])
return
def register_Ns3Ipv4MulticastRoute_methods(root_module, cls):
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute(ns3::Ipv4MulticastRoute const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MulticastRoute const &', 'arg0')])
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute() [constructor]
cls.add_constructor([])
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetGroup() const [member function]
cls.add_method('GetGroup',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetOrigin() const [member function]
cls.add_method('GetOrigin',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetOutputTtl(uint32_t oif) [member function]
cls.add_method('GetOutputTtl',
'uint32_t',
[param('uint32_t', 'oif')],
deprecated=True)
## ipv4-route.h (module 'internet'): std::map<unsigned int, unsigned int, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, unsigned int> > > ns3::Ipv4MulticastRoute::GetOutputTtlMap() const [member function]
cls.add_method('GetOutputTtlMap',
'std::map< unsigned int, unsigned int >',
[],
is_const=True)
## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetParent() const [member function]
cls.add_method('GetParent',
'uint32_t',
[],
is_const=True)
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetGroup(ns3::Ipv4Address const group) [member function]
cls.add_method('SetGroup',
'void',
[param('ns3::Ipv4Address const', 'group')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOrigin(ns3::Ipv4Address const origin) [member function]
cls.add_method('SetOrigin',
'void',
[param('ns3::Ipv4Address const', 'origin')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOutputTtl(uint32_t oif, uint32_t ttl) [member function]
cls.add_method('SetOutputTtl',
'void',
[param('uint32_t', 'oif'), param('uint32_t', 'ttl')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetParent(uint32_t iif) [member function]
cls.add_method('SetParent',
'void',
[param('uint32_t', 'iif')])
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_INTERFACES [variable]
cls.add_static_attribute('MAX_INTERFACES', 'uint32_t const', is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_TTL [variable]
cls.add_static_attribute('MAX_TTL', 'uint32_t const', is_const=True)
return
def register_Ns3Ipv4Route_methods(root_module, cls):
cls.add_output_stream_operator()
## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route(ns3::Ipv4Route const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Route const &', 'arg0')])
## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route() [constructor]
cls.add_constructor([])
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetDestination() const [member function]
cls.add_method('GetDestination',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetGateway() const [member function]
cls.add_method('GetGateway',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Route::GetOutputDevice() const [member function]
cls.add_method('GetOutputDevice',
'ns3::Ptr< ns3::NetDevice >',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetSource() const [member function]
cls.add_method('GetSource',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetDestination(ns3::Ipv4Address dest) [member function]
cls.add_method('SetDestination',
'void',
[param('ns3::Ipv4Address', 'dest')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetGateway(ns3::Ipv4Address gw) [member function]
cls.add_method('SetGateway',
'void',
[param('ns3::Ipv4Address', 'gw')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetOutputDevice(ns3::Ptr<ns3::NetDevice> outputDevice) [member function]
cls.add_method('SetOutputDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'outputDevice')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetSource(ns3::Ipv4Address src) [member function]
cls.add_method('SetSource',
'void',
[param('ns3::Ipv4Address', 'src')])
return
def register_Ns3Ipv4RoutingProtocol_methods(root_module, cls):
## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol() [constructor]
cls.add_constructor([])
## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol(ns3::Ipv4RoutingProtocol const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4RoutingProtocol const &', 'arg0')])
## ipv4-routing-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4RoutingProtocol::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyAddAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceDown',
'void',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceUp',
'void',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyRemoveAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function]
cls.add_method('PrintRoutingTable',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): bool ns3::Ipv4RoutingProtocol::RouteInput(ns3::Ptr<ns3::Packet const> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, 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, 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<ns3::Packet const>, ns3::Ipv4Header const&, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ecb) [member function]
cls.add_method('RouteInput',
'bool',
[param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function]
cls.add_method('RouteOutput',
'ns3::Ptr< ns3::Ipv4Route >',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function]
cls.add_method('SetIpv4',
'void',
[param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3Ipv6AddressChecker_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')])
return
def register_Ns3Ipv6AddressValue_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor]
cls.add_constructor([param('ns3::Ipv6Address const &', 'value')])
## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv6Address',
[],
is_const=True)
## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv6Address const &', 'value')])
return
def register_Ns3Ipv6Interface_methods(root_module, cls):
## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface::Ipv6Interface(ns3::Ipv6Interface const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Interface const &', 'arg0')])
## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface::Ipv6Interface() [constructor]
cls.add_constructor([])
## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::AddAddress(ns3::Ipv6InterfaceAddress iface) [member function]
cls.add_method('AddAddress',
'bool',
[param('ns3::Ipv6InterfaceAddress', 'iface')])
## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetAddress(uint32_t index) const [member function]
cls.add_method('GetAddress',
'ns3::Ipv6InterfaceAddress',
[param('uint32_t', 'index')],
is_const=True)
## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetAddressMatchingDestination(ns3::Ipv6Address dst) [member function]
cls.add_method('GetAddressMatchingDestination',
'ns3::Ipv6InterfaceAddress',
[param('ns3::Ipv6Address', 'dst')])
## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetBaseReachableTime() const [member function]
cls.add_method('GetBaseReachableTime',
'uint16_t',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): uint8_t ns3::Ipv6Interface::GetCurHopLimit() const [member function]
cls.add_method('GetCurHopLimit',
'uint8_t',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv6Interface::GetDevice() const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[],
is_const=True, is_virtual=True)
## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetLinkLocalAddress() const [member function]
cls.add_method('GetLinkLocalAddress',
'ns3::Ipv6InterfaceAddress',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetMetric() const [member function]
cls.add_method('GetMetric',
'uint16_t',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): uint32_t ns3::Ipv6Interface::GetNAddresses() const [member function]
cls.add_method('GetNAddresses',
'uint32_t',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetReachableTime() const [member function]
cls.add_method('GetReachableTime',
'uint16_t',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetRetransTimer() const [member function]
cls.add_method('GetRetransTimer',
'uint16_t',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): static ns3::TypeId ns3::Ipv6Interface::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsDown() const [member function]
cls.add_method('IsDown',
'bool',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsForwarding() const [member function]
cls.add_method('IsForwarding',
'bool',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsUp() const [member function]
cls.add_method('IsUp',
'bool',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::RemoveAddress(uint32_t index) [member function]
cls.add_method('RemoveAddress',
'ns3::Ipv6InterfaceAddress',
[param('uint32_t', 'index')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::Send(ns3::Ptr<ns3::Packet> p, ns3::Ipv6Address dest) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv6Address', 'dest')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetBaseReachableTime(uint16_t baseReachableTime) [member function]
cls.add_method('SetBaseReachableTime',
'void',
[param('uint16_t', 'baseReachableTime')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetCurHopLimit(uint8_t curHopLimit) [member function]
cls.add_method('SetCurHopLimit',
'void',
[param('uint8_t', 'curHopLimit')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetDevice(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('SetDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetDown() [member function]
cls.add_method('SetDown',
'void',
[])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetForwarding(bool forward) [member function]
cls.add_method('SetForwarding',
'void',
[param('bool', 'forward')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetMetric(uint16_t metric) [member function]
cls.add_method('SetMetric',
'void',
[param('uint16_t', 'metric')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetNsDadUid(ns3::Ipv6Address address, uint32_t uid) [member function]
cls.add_method('SetNsDadUid',
'void',
[param('ns3::Ipv6Address', 'address'), param('uint32_t', 'uid')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetReachableTime(uint16_t reachableTime) [member function]
cls.add_method('SetReachableTime',
'void',
[param('uint16_t', 'reachableTime')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetRetransTimer(uint16_t retransTimer) [member function]
cls.add_method('SetRetransTimer',
'void',
[param('uint16_t', 'retransTimer')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetState(ns3::Ipv6Address address, ns3::Ipv6InterfaceAddress::State_e state) [member function]
cls.add_method('SetState',
'void',
[param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6InterfaceAddress::State_e', 'state')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetUp() [member function]
cls.add_method('SetUp',
'void',
[])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3Ipv6PrefixChecker_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')])
return
def register_Ns3Ipv6PrefixValue_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')])
## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv6Prefix',
[],
is_const=True)
## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv6Prefix const &', 'value')])
return
def register_Ns3LogNormalRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::LogNormalRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable::LogNormalRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetMu() const [member function]
cls.add_method('GetMu',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetSigma() const [member function]
cls.add_method('GetSigma',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue(double mu, double sigma) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mu'), param('double', 'sigma')])
## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger(uint32_t mu, uint32_t sigma) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mu'), param('uint32_t', 'sigma')])
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3Mac48AddressChecker_methods(root_module, cls):
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor]
cls.add_constructor([])
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [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<const ns3::Packet>,short unsigned int,const ns3::Address&,const ns3::Address&,ns3::NetDevice::PacketType,ns3::empty,ns3::empty,ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function]
cls.add_method('SetReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3NixVector_methods(root_module, cls):
cls.add_output_stream_operator()
## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor]
cls.add_constructor([])
## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor]
cls.add_constructor([param('ns3::NixVector const &', 'o')])
## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function]
cls.add_method('AddNeighborIndex',
'void',
[param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function]
cls.add_method('BitCount',
'uint32_t',
[param('uint32_t', 'numberOfNeighbors')],
is_const=True)
## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::NixVector >',
[],
is_const=True)
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint32_t const *', 'buffer'), param('uint32_t', 'size')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function]
cls.add_method('ExtractNeighborIndex',
'uint32_t',
[param('uint32_t', 'numberOfBits')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function]
cls.add_method('GetRemainingBits',
'uint32_t',
[])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_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::DoStart() [member function]
cls.add_method('DoStart',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3NormalRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::INFINITE_VALUE [variable]
cls.add_static_attribute('INFINITE_VALUE', 'double const', is_const=True)
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::NormalRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::NormalRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetVariance() const [member function]
cls.add_method('GetVariance',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue(double mean, double variance, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'variance'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger(uint32_t mean, uint32_t variance, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'variance'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ObjectFactoryChecker_methods(root_module, cls):
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [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<ns3::Packet const> packet) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function]
cls.add_method('AddByteTag',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function]
cls.add_method('AddHeader',
'void',
[param('ns3::Header const &', 'header')])
## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function]
cls.add_method('AddPacketTag',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function]
cls.add_method('AddPaddingAtEnd',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function]
cls.add_method('AddTrailer',
'void',
[param('ns3::Trailer const &', 'trailer')])
## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function]
cls.add_method('BeginItem',
'ns3::PacketMetadata::ItemIterator',
[],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function]
cls.add_method('CopyData',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function]
cls.add_method('CopyData',
'void',
[param('std::ostream *', 'os'), param('uint32_t', 'size')],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function]
cls.add_method('CreateFragment',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'start'), param('uint32_t', 'length')],
is_const=True)
## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function]
cls.add_method('EnableChecking',
'void',
[],
is_static=True)
## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function]
cls.add_method('EnablePrinting',
'void',
[],
is_static=True)
## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function]
cls.add_method('FindFirstMatchingByteTag',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function]
cls.add_method('GetByteTagIterator',
'ns3::ByteTagIterator',
[],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function]
cls.add_method('GetNixVector',
'ns3::Ptr< ns3::NixVector >',
[],
is_const=True)
## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function]
cls.add_method('GetPacketTagIterator',
'ns3::PacketTagIterator',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function]
cls.add_method('GetUid',
'uint64_t',
[],
is_const=True)
## packet.h (module 'network'): uint8_t const * ns3::Packet::PeekData() const [member function]
cls.add_method('PeekData',
'uint8_t const *',
[],
deprecated=True, is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function]
cls.add_method('PeekHeader',
'uint32_t',
[param('ns3::Header &', 'header')],
is_const=True)
## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function]
cls.add_method('PeekPacketTag',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function]
cls.add_method('PeekTrailer',
'uint32_t',
[param('ns3::Trailer &', 'trailer')])
## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function]
cls.add_method('PrintByteTags',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function]
cls.add_method('PrintPacketTags',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function]
cls.add_method('RemoveAllByteTags',
'void',
[])
## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function]
cls.add_method('RemoveAllPacketTags',
'void',
[])
## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function]
cls.add_method('RemoveHeader',
'uint32_t',
[param('ns3::Header &', 'header')])
## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function]
cls.add_method('RemovePacketTag',
'bool',
[param('ns3::Tag &', 'tag')])
## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function]
cls.add_method('RemoveTrailer',
'uint32_t',
[param('ns3::Trailer &', 'trailer')])
## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> arg0) [member function]
cls.add_method('SetNixVector',
'void',
[param('ns3::Ptr< ns3::NixVector >', 'arg0')])
return
def register_Ns3ParetoRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ParetoRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable::ParetoRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetShape() const [member function]
cls.add_method('GetShape',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue(double mean, double shape, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'shape'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger(uint32_t mean, uint32_t shape, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'shape'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3TimeChecker_methods(root_module, cls):
## nstime.h (module 'core'): ns3::TimeChecker::TimeChecker() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::TimeChecker::TimeChecker(ns3::TimeChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimeChecker const &', 'arg0')])
return
def register_Ns3TimeValue_methods(root_module, cls):
## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimeValue const &', 'arg0')])
## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor]
cls.add_constructor([param('ns3::Time const &', 'value')])
## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function]
cls.add_method('Get',
'ns3::Time',
[],
is_const=True)
## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Time const &', 'value')])
return
def register_Ns3TypeIdChecker_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')])
return
def register_Ns3TypeIdValue_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor]
cls.add_constructor([param('ns3::TypeId const &', 'value')])
## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function]
cls.add_method('Get',
'ns3::TypeId',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::TypeId const &', 'value')])
return
def register_Ns3AddressChecker_methods(root_module, cls):
## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')])
return
def register_Ns3AddressValue_methods(root_module, cls):
## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AddressValue const &', 'arg0')])
## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor]
cls.add_constructor([param('ns3::Address const &', 'value')])
## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Address',
[],
is_const=True)
## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Address const &', 'value')])
return
def register_Ns3AodvDuplicatePacketDetection_methods(root_module, cls):
## aodv-dpd.h (module 'aodv'): ns3::aodv::DuplicatePacketDetection::DuplicatePacketDetection(ns3::aodv::DuplicatePacketDetection const & arg0) [copy constructor]
cls.add_constructor([param('ns3::aodv::DuplicatePacketDetection const &', 'arg0')])
## aodv-dpd.h (module 'aodv'): ns3::aodv::DuplicatePacketDetection::DuplicatePacketDetection(ns3::Time lifetime) [constructor]
cls.add_constructor([param('ns3::Time', 'lifetime')])
## aodv-dpd.h (module 'aodv'): ns3::Time ns3::aodv::DuplicatePacketDetection::GetLifetime() const [member function]
cls.add_method('GetLifetime',
'ns3::Time',
[],
is_const=True)
## aodv-dpd.h (module 'aodv'): bool ns3::aodv::DuplicatePacketDetection::IsDuplicate(ns3::Ptr<ns3::Packet const> p, ns3::Ipv4Header const & header) [member function]
cls.add_method('IsDuplicate',
'bool',
[param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header')])
## aodv-dpd.h (module 'aodv'): void ns3::aodv::DuplicatePacketDetection::SetLifetime(ns3::Time lifetime) [member function]
cls.add_method('SetLifetime',
'void',
[param('ns3::Time', 'lifetime')])
return
def register_Ns3AodvIdCache_methods(root_module, cls):
## aodv-id-cache.h (module 'aodv'): ns3::aodv::IdCache::IdCache(ns3::aodv::IdCache const & arg0) [copy constructor]
cls.add_constructor([param('ns3::aodv::IdCache const &', 'arg0')])
## aodv-id-cache.h (module 'aodv'): ns3::aodv::IdCache::IdCache(ns3::Time lifetime) [constructor]
cls.add_constructor([param('ns3::Time', 'lifetime')])
## aodv-id-cache.h (module 'aodv'): ns3::Time ns3::aodv::IdCache::GetLifeTime() const [member function]
cls.add_method('GetLifeTime',
'ns3::Time',
[],
is_const=True)
## aodv-id-cache.h (module 'aodv'): uint32_t ns3::aodv::IdCache::GetSize() [member function]
cls.add_method('GetSize',
'uint32_t',
[])
## aodv-id-cache.h (module 'aodv'): bool ns3::aodv::IdCache::IsDuplicate(ns3::Ipv4Address addr, uint32_t id) [member function]
cls.add_method('IsDuplicate',
'bool',
[param('ns3::Ipv4Address', 'addr'), param('uint32_t', 'id')])
## aodv-id-cache.h (module 'aodv'): void ns3::aodv::IdCache::Purge() [member function]
cls.add_method('Purge',
'void',
[])
## aodv-id-cache.h (module 'aodv'): void ns3::aodv::IdCache::SetLifetime(ns3::Time lifetime) [member function]
cls.add_method('SetLifetime',
'void',
[param('ns3::Time', 'lifetime')])
return
def register_Ns3AodvNeighbors_methods(root_module, cls):
## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbors(ns3::aodv::Neighbors const & arg0) [copy constructor]
cls.add_constructor([param('ns3::aodv::Neighbors const &', 'arg0')])
## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbors(ns3::Time delay) [constructor]
cls.add_constructor([param('ns3::Time', 'delay')])
## aodv-neighbor.h (module 'aodv'): void ns3::aodv::Neighbors::AddArpCache(ns3::Ptr<ns3::ArpCache> arg0) [member function]
cls.add_method('AddArpCache',
'void',
[param('ns3::Ptr< ns3::ArpCache >', 'arg0')])
## aodv-neighbor.h (module 'aodv'): void ns3::aodv::Neighbors::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## aodv-neighbor.h (module 'aodv'): void ns3::aodv::Neighbors::DelArpCache(ns3::Ptr<ns3::ArpCache> arg0) [member function]
cls.add_method('DelArpCache',
'void',
[param('ns3::Ptr< ns3::ArpCache >', 'arg0')])
## aodv-neighbor.h (module 'aodv'): ns3::Callback<void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::aodv::Neighbors::GetCallback() const [member function]
cls.add_method('GetCallback',
'ns3::Callback< void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_const=True)
## aodv-neighbor.h (module 'aodv'): ns3::Time ns3::aodv::Neighbors::GetExpireTime(ns3::Ipv4Address addr) [member function]
cls.add_method('GetExpireTime',
'ns3::Time',
[param('ns3::Ipv4Address', 'addr')])
## aodv-neighbor.h (module 'aodv'): ns3::Callback<void, ns3::WifiMacHeader const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::aodv::Neighbors::GetTxErrorCallback() const [member function]
cls.add_method('GetTxErrorCallback',
'ns3::Callback< void, ns3::WifiMacHeader const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_const=True)
## aodv-neighbor.h (module 'aodv'): bool ns3::aodv::Neighbors::IsNeighbor(ns3::Ipv4Address addr) [member function]
cls.add_method('IsNeighbor',
'bool',
[param('ns3::Ipv4Address', 'addr')])
## aodv-neighbor.h (module 'aodv'): void ns3::aodv::Neighbors::Purge() [member function]
cls.add_method('Purge',
'void',
[])
## aodv-neighbor.h (module 'aodv'): void ns3::aodv::Neighbors::ScheduleTimer() [member function]
cls.add_method('ScheduleTimer',
'void',
[])
## aodv-neighbor.h (module 'aodv'): void ns3::aodv::Neighbors::SetCallback(ns3::Callback<void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetCallback',
'void',
[param('ns3::Callback< void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')])
## aodv-neighbor.h (module 'aodv'): void ns3::aodv::Neighbors::Update(ns3::Ipv4Address addr, ns3::Time expire) [member function]
cls.add_method('Update',
'void',
[param('ns3::Ipv4Address', 'addr'), param('ns3::Time', 'expire')])
return
def register_Ns3AodvNeighborsNeighbor_methods(root_module, cls):
## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbor::Neighbor(ns3::aodv::Neighbors::Neighbor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::aodv::Neighbors::Neighbor const &', 'arg0')])
## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbor::Neighbor(ns3::Ipv4Address ip, ns3::Mac48Address mac, ns3::Time t) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'ip'), param('ns3::Mac48Address', 'mac'), param('ns3::Time', 't')])
## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbor::close [variable]
cls.add_instance_attribute('close', 'bool', is_const=False)
## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbor::m_expireTime [variable]
cls.add_instance_attribute('m_expireTime', 'ns3::Time', is_const=False)
## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbor::m_hardwareAddress [variable]
cls.add_instance_attribute('m_hardwareAddress', 'ns3::Mac48Address', is_const=False)
## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbor::m_neighborAddress [variable]
cls.add_instance_attribute('m_neighborAddress', 'ns3::Ipv4Address', is_const=False)
return
def register_Ns3AodvQueueEntry_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
## aodv-rqueue.h (module 'aodv'): ns3::aodv::QueueEntry::QueueEntry(ns3::aodv::QueueEntry const & arg0) [copy constructor]
cls.add_constructor([param('ns3::aodv::QueueEntry const &', 'arg0')])
## aodv-rqueue.h (module 'aodv'): ns3::aodv::QueueEntry::QueueEntry(ns3::Ptr<ns3::Packet const> pa=0, ns3::Ipv4Header const & h=ns3::Ipv4Header(), 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=ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>(), ns3::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=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>(), ns3::Time exp=ns3::Simulator::Now( )) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Packet const >', 'pa', default_value='0'), param('ns3::Ipv4Header const &', 'h', default_value='ns3::Ipv4Header()'), param('ns3::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', default_value='ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>()'), param('ns3::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', default_value='ns3::Callback<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header&, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>()'), param('ns3::Time', 'exp', default_value='ns3::Simulator::Now( )')])
## aodv-rqueue.h (module 'aodv'): 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> ns3::aodv::QueueEntry::GetErrorCallback() const [member function]
cls.add_method('GetErrorCallback',
'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 >',
[],
is_const=True)
## aodv-rqueue.h (module 'aodv'): ns3::Time ns3::aodv::QueueEntry::GetExpireTime() const [member function]
cls.add_method('GetExpireTime',
'ns3::Time',
[],
is_const=True)
## aodv-rqueue.h (module 'aodv'): ns3::Ipv4Header ns3::aodv::QueueEntry::GetIpv4Header() const [member function]
cls.add_method('GetIpv4Header',
'ns3::Ipv4Header',
[],
is_const=True)
## aodv-rqueue.h (module 'aodv'): ns3::Ptr<ns3::Packet const> ns3::aodv::QueueEntry::GetPacket() const [member function]
cls.add_method('GetPacket',
'ns3::Ptr< ns3::Packet const >',
[],
is_const=True)
## aodv-rqueue.h (module 'aodv'): 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> ns3::aodv::QueueEntry::GetUnicastForwardCallback() const [member function]
cls.add_method('GetUnicastForwardCallback',
'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 >',
[],
is_const=True)
## aodv-rqueue.h (module 'aodv'): void ns3::aodv::QueueEntry::SetErrorCallback(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) [member function]
cls.add_method('SetErrorCallback',
'void',
[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')])
## aodv-rqueue.h (module 'aodv'): void ns3::aodv::QueueEntry::SetExpireTime(ns3::Time exp) [member function]
cls.add_method('SetExpireTime',
'void',
[param('ns3::Time', 'exp')])
## aodv-rqueue.h (module 'aodv'): void ns3::aodv::QueueEntry::SetIpv4Header(ns3::Ipv4Header h) [member function]
cls.add_method('SetIpv4Header',
'void',
[param('ns3::Ipv4Header', 'h')])
## aodv-rqueue.h (module 'aodv'): void ns3::aodv::QueueEntry::SetPacket(ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('SetPacket',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'p')])
## aodv-rqueue.h (module 'aodv'): void ns3::aodv::QueueEntry::SetUnicastForwardCallback(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) [member function]
cls.add_method('SetUnicastForwardCallback',
'void',
[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')])
return
def register_Ns3AodvRequestQueue_methods(root_module, cls):
## aodv-rqueue.h (module 'aodv'): ns3::aodv::RequestQueue::RequestQueue(ns3::aodv::RequestQueue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::aodv::RequestQueue const &', 'arg0')])
## aodv-rqueue.h (module 'aodv'): ns3::aodv::RequestQueue::RequestQueue(uint32_t maxLen, ns3::Time routeToQueueTimeout) [constructor]
cls.add_constructor([param('uint32_t', 'maxLen'), param('ns3::Time', 'routeToQueueTimeout')])
## aodv-rqueue.h (module 'aodv'): bool ns3::aodv::RequestQueue::Dequeue(ns3::Ipv4Address dst, ns3::aodv::QueueEntry & entry) [member function]
cls.add_method('Dequeue',
'bool',
[param('ns3::Ipv4Address', 'dst'), param('ns3::aodv::QueueEntry &', 'entry')])
## aodv-rqueue.h (module 'aodv'): void ns3::aodv::RequestQueue::DropPacketWithDst(ns3::Ipv4Address dst) [member function]
cls.add_method('DropPacketWithDst',
'void',
[param('ns3::Ipv4Address', 'dst')])
## aodv-rqueue.h (module 'aodv'): bool ns3::aodv::RequestQueue::Enqueue(ns3::aodv::QueueEntry & entry) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::aodv::QueueEntry &', 'entry')])
## aodv-rqueue.h (module 'aodv'): bool ns3::aodv::RequestQueue::Find(ns3::Ipv4Address dst) [member function]
cls.add_method('Find',
'bool',
[param('ns3::Ipv4Address', 'dst')])
## aodv-rqueue.h (module 'aodv'): uint32_t ns3::aodv::RequestQueue::GetMaxQueueLen() const [member function]
cls.add_method('GetMaxQueueLen',
'uint32_t',
[],
is_const=True)
## aodv-rqueue.h (module 'aodv'): ns3::Time ns3::aodv::RequestQueue::GetQueueTimeout() const [member function]
cls.add_method('GetQueueTimeout',
'ns3::Time',
[],
is_const=True)
## aodv-rqueue.h (module 'aodv'): uint32_t ns3::aodv::RequestQueue::GetSize() [member function]
cls.add_method('GetSize',
'uint32_t',
[])
## aodv-rqueue.h (module 'aodv'): void ns3::aodv::RequestQueue::SetMaxQueueLen(uint32_t len) [member function]
cls.add_method('SetMaxQueueLen',
'void',
[param('uint32_t', 'len')])
## aodv-rqueue.h (module 'aodv'): void ns3::aodv::RequestQueue::SetQueueTimeout(ns3::Time t) [member function]
cls.add_method('SetQueueTimeout',
'void',
[param('ns3::Time', 't')])
return
def register_Ns3AodvRerrHeader_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## aodv-packet.h (module 'aodv'): ns3::aodv::RerrHeader::RerrHeader(ns3::aodv::RerrHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::aodv::RerrHeader const &', 'arg0')])
## aodv-packet.h (module 'aodv'): ns3::aodv::RerrHeader::RerrHeader() [constructor]
cls.add_constructor([])
## aodv-packet.h (module 'aodv'): bool ns3::aodv::RerrHeader::AddUnDestination(ns3::Ipv4Address dst, uint32_t seqNo) [member function]
cls.add_method('AddUnDestination',
'bool',
[param('ns3::Ipv4Address', 'dst'), param('uint32_t', 'seqNo')])
## aodv-packet.h (module 'aodv'): void ns3::aodv::RerrHeader::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RerrHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## aodv-packet.h (module 'aodv'): uint8_t ns3::aodv::RerrHeader::GetDestCount() const [member function]
cls.add_method('GetDestCount',
'uint8_t',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): ns3::TypeId ns3::aodv::RerrHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## aodv-packet.h (module 'aodv'): bool ns3::aodv::RerrHeader::GetNoDelete() const [member function]
cls.add_method('GetNoDelete',
'bool',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RerrHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## aodv-packet.h (module 'aodv'): static ns3::TypeId ns3::aodv::RerrHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## aodv-packet.h (module 'aodv'): void ns3::aodv::RerrHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## aodv-packet.h (module 'aodv'): bool ns3::aodv::RerrHeader::RemoveUnDestination(std::pair<ns3::Ipv4Address,unsigned int> & un) [member function]
cls.add_method('RemoveUnDestination',
'bool',
[param('std::pair< ns3::Ipv4Address, unsigned int > &', 'un')])
## aodv-packet.h (module 'aodv'): void ns3::aodv::RerrHeader::Serialize(ns3::Buffer::Iterator i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'i')],
is_const=True, is_virtual=True)
## aodv-packet.h (module 'aodv'): void ns3::aodv::RerrHeader::SetNoDelete(bool f) [member function]
cls.add_method('SetNoDelete',
'void',
[param('bool', 'f')])
return
def register_Ns3AodvRoutingProtocol_methods(root_module, cls):
## aodv-routing-protocol.h (module 'aodv'): ns3::aodv::RoutingProtocol::RoutingProtocol(ns3::aodv::RoutingProtocol const & arg0) [copy constructor]
cls.add_constructor([param('ns3::aodv::RoutingProtocol const &', 'arg0')])
## aodv-routing-protocol.h (module 'aodv'): ns3::aodv::RoutingProtocol::RoutingProtocol() [constructor]
cls.add_constructor([])
## aodv-routing-protocol.h (module 'aodv'): int64_t ns3::aodv::RoutingProtocol::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## aodv-routing-protocol.h (module 'aodv'): bool ns3::aodv::RoutingProtocol::GetBroadcastEnable() const [member function]
cls.add_method('GetBroadcastEnable',
'bool',
[],
is_const=True)
## aodv-routing-protocol.h (module 'aodv'): bool ns3::aodv::RoutingProtocol::GetDesinationOnlyFlag() const [member function]
cls.add_method('GetDesinationOnlyFlag',
'bool',
[],
is_const=True)
## aodv-routing-protocol.h (module 'aodv'): bool ns3::aodv::RoutingProtocol::GetGratuitousReplyFlag() const [member function]
cls.add_method('GetGratuitousReplyFlag',
'bool',
[],
is_const=True)
## aodv-routing-protocol.h (module 'aodv'): bool ns3::aodv::RoutingProtocol::GetHelloEnable() const [member function]
cls.add_method('GetHelloEnable',
'bool',
[],
is_const=True)
## aodv-routing-protocol.h (module 'aodv'): uint32_t ns3::aodv::RoutingProtocol::GetMaxQueueLen() const [member function]
cls.add_method('GetMaxQueueLen',
'uint32_t',
[],
is_const=True)
## aodv-routing-protocol.h (module 'aodv'): ns3::Time ns3::aodv::RoutingProtocol::GetMaxQueueTime() const [member function]
cls.add_method('GetMaxQueueTime',
'ns3::Time',
[],
is_const=True)
## aodv-routing-protocol.h (module 'aodv'): static ns3::TypeId ns3::aodv::RoutingProtocol::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyAddAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_virtual=True)
## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceDown',
'void',
[param('uint32_t', 'interface')],
is_virtual=True)
## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceUp',
'void',
[param('uint32_t', 'interface')],
is_virtual=True)
## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyRemoveAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_virtual=True)
## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::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)
## aodv-routing-protocol.h (module 'aodv'): bool ns3::aodv::RoutingProtocol::RouteInput(ns3::Ptr<ns3::Packet const> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, 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, 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<ns3::Packet const>, ns3::Ipv4Header const&, 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)
## aodv-routing-protocol.h (module 'aodv'): ns3::Ptr<ns3::Ipv4Route> ns3::aodv::RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function]
cls.add_method('RouteOutput',
'ns3::Ptr< ns3::Ipv4Route >',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')],
is_virtual=True)
## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::SetBroadcastEnable(bool f) [member function]
cls.add_method('SetBroadcastEnable',
'void',
[param('bool', 'f')])
## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::SetDesinationOnlyFlag(bool f) [member function]
cls.add_method('SetDesinationOnlyFlag',
'void',
[param('bool', 'f')])
## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::SetGratuitousReplyFlag(bool f) [member function]
cls.add_method('SetGratuitousReplyFlag',
'void',
[param('bool', 'f')])
## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::SetHelloEnable(bool f) [member function]
cls.add_method('SetHelloEnable',
'void',
[param('bool', 'f')])
## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function]
cls.add_method('SetIpv4',
'void',
[param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')],
is_virtual=True)
## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::SetMaxQueueLen(uint32_t len) [member function]
cls.add_method('SetMaxQueueLen',
'void',
[param('uint32_t', 'len')])
## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::SetMaxQueueTime(ns3::Time t) [member function]
cls.add_method('SetMaxQueueTime',
'void',
[param('ns3::Time', 't')])
## aodv-routing-protocol.h (module 'aodv'): ns3::aodv::RoutingProtocol::AODV_PORT [variable]
cls.add_static_attribute('AODV_PORT', 'uint32_t const', is_const=True)
return
def register_Ns3AodvRoutingTable_methods(root_module, cls):
## aodv-rtable.h (module 'aodv'): ns3::aodv::RoutingTable::RoutingTable(ns3::aodv::RoutingTable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::aodv::RoutingTable const &', 'arg0')])
## aodv-rtable.h (module 'aodv'): ns3::aodv::RoutingTable::RoutingTable(ns3::Time t) [constructor]
cls.add_constructor([param('ns3::Time', 't')])
## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTable::AddRoute(ns3::aodv::RoutingTableEntry & r) [member function]
cls.add_method('AddRoute',
'bool',
[param('ns3::aodv::RoutingTableEntry &', 'r')])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTable::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTable::DeleteAllRoutesFromInterface(ns3::Ipv4InterfaceAddress iface) [member function]
cls.add_method('DeleteAllRoutesFromInterface',
'void',
[param('ns3::Ipv4InterfaceAddress', 'iface')])
## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTable::DeleteRoute(ns3::Ipv4Address dst) [member function]
cls.add_method('DeleteRoute',
'bool',
[param('ns3::Ipv4Address', 'dst')])
## aodv-rtable.h (module 'aodv'): ns3::Time ns3::aodv::RoutingTable::GetBadLinkLifetime() const [member function]
cls.add_method('GetBadLinkLifetime',
'ns3::Time',
[],
is_const=True)
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTable::GetListOfDestinationWithNextHop(ns3::Ipv4Address nextHop, std::map<ns3::Ipv4Address, unsigned int, std::less<ns3::Ipv4Address>, std::allocator<std::pair<ns3::Ipv4Address const, unsigned int> > > & unreachable) [member function]
cls.add_method('GetListOfDestinationWithNextHop',
'void',
[param('ns3::Ipv4Address', 'nextHop'), param('std::map< ns3::Ipv4Address, unsigned int > &', 'unreachable')])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTable::InvalidateRoutesWithDst(std::map<ns3::Ipv4Address, unsigned int, std::less<ns3::Ipv4Address>, std::allocator<std::pair<ns3::Ipv4Address const, unsigned int> > > const & unreachable) [member function]
cls.add_method('InvalidateRoutesWithDst',
'void',
[param('std::map< ns3::Ipv4Address, unsigned int > const &', 'unreachable')])
## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTable::LookupRoute(ns3::Ipv4Address dst, ns3::aodv::RoutingTableEntry & rt) [member function]
cls.add_method('LookupRoute',
'bool',
[param('ns3::Ipv4Address', 'dst'), param('ns3::aodv::RoutingTableEntry &', 'rt')])
## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTable::LookupValidRoute(ns3::Ipv4Address dst, ns3::aodv::RoutingTableEntry & rt) [member function]
cls.add_method('LookupValidRoute',
'bool',
[param('ns3::Ipv4Address', 'dst'), param('ns3::aodv::RoutingTableEntry &', 'rt')])
## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTable::MarkLinkAsUnidirectional(ns3::Ipv4Address neighbor, ns3::Time blacklistTimeout) [member function]
cls.add_method('MarkLinkAsUnidirectional',
'bool',
[param('ns3::Ipv4Address', 'neighbor'), param('ns3::Time', 'blacklistTimeout')])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTable::Print(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function]
cls.add_method('Print',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_const=True)
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTable::Purge() [member function]
cls.add_method('Purge',
'void',
[])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTable::SetBadLinkLifetime(ns3::Time t) [member function]
cls.add_method('SetBadLinkLifetime',
'void',
[param('ns3::Time', 't')])
## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTable::SetEntryState(ns3::Ipv4Address dst, ns3::aodv::RouteFlags state) [member function]
cls.add_method('SetEntryState',
'bool',
[param('ns3::Ipv4Address', 'dst'), param('ns3::aodv::RouteFlags', 'state')])
## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTable::Update(ns3::aodv::RoutingTableEntry & rt) [member function]
cls.add_method('Update',
'bool',
[param('ns3::aodv::RoutingTableEntry &', 'rt')])
return
def register_Ns3AodvRoutingTableEntry_methods(root_module, cls):
## aodv-rtable.h (module 'aodv'): ns3::aodv::RoutingTableEntry::RoutingTableEntry(ns3::aodv::RoutingTableEntry const & arg0) [copy constructor]
cls.add_constructor([param('ns3::aodv::RoutingTableEntry const &', 'arg0')])
## aodv-rtable.h (module 'aodv'): ns3::aodv::RoutingTableEntry::RoutingTableEntry(ns3::Ptr<ns3::NetDevice> dev=0, ns3::Ipv4Address dst=ns3::Ipv4Address(), bool vSeqNo=false, uint32_t m_seqNo=0, ns3::Ipv4InterfaceAddress iface=ns3::Ipv4InterfaceAddress(), uint16_t hops=0, ns3::Ipv4Address nextHop=ns3::Ipv4Address(), ns3::Time lifetime=ns3::Simulator::Now( )) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev', default_value='0'), param('ns3::Ipv4Address', 'dst', default_value='ns3::Ipv4Address()'), param('bool', 'vSeqNo', default_value='false'), param('uint32_t', 'm_seqNo', default_value='0'), param('ns3::Ipv4InterfaceAddress', 'iface', default_value='ns3::Ipv4InterfaceAddress()'), param('uint16_t', 'hops', default_value='0'), param('ns3::Ipv4Address', 'nextHop', default_value='ns3::Ipv4Address()'), param('ns3::Time', 'lifetime', default_value='ns3::Simulator::Now( )')])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::DeleteAllPrecursors() [member function]
cls.add_method('DeleteAllPrecursors',
'void',
[])
## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTableEntry::DeletePrecursor(ns3::Ipv4Address id) [member function]
cls.add_method('DeletePrecursor',
'bool',
[param('ns3::Ipv4Address', 'id')])
## aodv-rtable.h (module 'aodv'): ns3::Time ns3::aodv::RoutingTableEntry::GetBlacklistTimeout() const [member function]
cls.add_method('GetBlacklistTimeout',
'ns3::Time',
[],
is_const=True)
## aodv-rtable.h (module 'aodv'): ns3::Ipv4Address ns3::aodv::RoutingTableEntry::GetDestination() const [member function]
cls.add_method('GetDestination',
'ns3::Ipv4Address',
[],
is_const=True)
## aodv-rtable.h (module 'aodv'): ns3::aodv::RouteFlags ns3::aodv::RoutingTableEntry::GetFlag() const [member function]
cls.add_method('GetFlag',
'ns3::aodv::RouteFlags',
[],
is_const=True)
## aodv-rtable.h (module 'aodv'): uint16_t ns3::aodv::RoutingTableEntry::GetHop() const [member function]
cls.add_method('GetHop',
'uint16_t',
[],
is_const=True)
## aodv-rtable.h (module 'aodv'): ns3::Ipv4InterfaceAddress ns3::aodv::RoutingTableEntry::GetInterface() const [member function]
cls.add_method('GetInterface',
'ns3::Ipv4InterfaceAddress',
[],
is_const=True)
## aodv-rtable.h (module 'aodv'): ns3::Time ns3::aodv::RoutingTableEntry::GetLifeTime() const [member function]
cls.add_method('GetLifeTime',
'ns3::Time',
[],
is_const=True)
## aodv-rtable.h (module 'aodv'): ns3::Ipv4Address ns3::aodv::RoutingTableEntry::GetNextHop() const [member function]
cls.add_method('GetNextHop',
'ns3::Ipv4Address',
[],
is_const=True)
## aodv-rtable.h (module 'aodv'): ns3::Ptr<ns3::NetDevice> ns3::aodv::RoutingTableEntry::GetOutputDevice() const [member function]
cls.add_method('GetOutputDevice',
'ns3::Ptr< ns3::NetDevice >',
[],
is_const=True)
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::GetPrecursors(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > & prec) const [member function]
cls.add_method('GetPrecursors',
'void',
[param('std::vector< ns3::Ipv4Address > &', 'prec')],
is_const=True)
## aodv-rtable.h (module 'aodv'): ns3::Ptr<ns3::Ipv4Route> ns3::aodv::RoutingTableEntry::GetRoute() const [member function]
cls.add_method('GetRoute',
'ns3::Ptr< ns3::Ipv4Route >',
[],
is_const=True)
## aodv-rtable.h (module 'aodv'): uint8_t ns3::aodv::RoutingTableEntry::GetRreqCnt() const [member function]
cls.add_method('GetRreqCnt',
'uint8_t',
[],
is_const=True)
## aodv-rtable.h (module 'aodv'): uint32_t ns3::aodv::RoutingTableEntry::GetSeqNo() const [member function]
cls.add_method('GetSeqNo',
'uint32_t',
[],
is_const=True)
## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTableEntry::GetValidSeqNo() const [member function]
cls.add_method('GetValidSeqNo',
'bool',
[],
is_const=True)
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::IncrementRreqCnt() [member function]
cls.add_method('IncrementRreqCnt',
'void',
[])
## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTableEntry::InsertPrecursor(ns3::Ipv4Address id) [member function]
cls.add_method('InsertPrecursor',
'bool',
[param('ns3::Ipv4Address', 'id')])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::Invalidate(ns3::Time badLinkLifetime) [member function]
cls.add_method('Invalidate',
'void',
[param('ns3::Time', 'badLinkLifetime')])
## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTableEntry::IsPrecursorListEmpty() const [member function]
cls.add_method('IsPrecursorListEmpty',
'bool',
[],
is_const=True)
## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTableEntry::IsUnidirectional() const [member function]
cls.add_method('IsUnidirectional',
'bool',
[],
is_const=True)
## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTableEntry::LookupPrecursor(ns3::Ipv4Address id) [member function]
cls.add_method('LookupPrecursor',
'bool',
[param('ns3::Ipv4Address', 'id')])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::Print(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function]
cls.add_method('Print',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_const=True)
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetBalcklistTimeout(ns3::Time t) [member function]
cls.add_method('SetBalcklistTimeout',
'void',
[param('ns3::Time', 't')])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetFlag(ns3::aodv::RouteFlags flag) [member function]
cls.add_method('SetFlag',
'void',
[param('ns3::aodv::RouteFlags', 'flag')])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetHop(uint16_t hop) [member function]
cls.add_method('SetHop',
'void',
[param('uint16_t', 'hop')])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetInterface(ns3::Ipv4InterfaceAddress iface) [member function]
cls.add_method('SetInterface',
'void',
[param('ns3::Ipv4InterfaceAddress', 'iface')])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetLifeTime(ns3::Time lt) [member function]
cls.add_method('SetLifeTime',
'void',
[param('ns3::Time', 'lt')])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetNextHop(ns3::Ipv4Address nextHop) [member function]
cls.add_method('SetNextHop',
'void',
[param('ns3::Ipv4Address', 'nextHop')])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetOutputDevice(ns3::Ptr<ns3::NetDevice> dev) [member function]
cls.add_method('SetOutputDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'dev')])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetRoute(ns3::Ptr<ns3::Ipv4Route> r) [member function]
cls.add_method('SetRoute',
'void',
[param('ns3::Ptr< ns3::Ipv4Route >', 'r')])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetRreqCnt(uint8_t n) [member function]
cls.add_method('SetRreqCnt',
'void',
[param('uint8_t', 'n')])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetSeqNo(uint32_t sn) [member function]
cls.add_method('SetSeqNo',
'void',
[param('uint32_t', 'sn')])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetUnidirectional(bool u) [member function]
cls.add_method('SetUnidirectional',
'void',
[param('bool', 'u')])
## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetValidSeqNo(bool s) [member function]
cls.add_method('SetValidSeqNo',
'void',
[param('bool', 's')])
## aodv-rtable.h (module 'aodv'): ns3::aodv::RoutingTableEntry::m_ackTimer [variable]
cls.add_instance_attribute('m_ackTimer', 'ns3::Timer', is_const=False)
return
def register_Ns3AodvRrepAckHeader_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## aodv-packet.h (module 'aodv'): ns3::aodv::RrepAckHeader::RrepAckHeader(ns3::aodv::RrepAckHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::aodv::RrepAckHeader const &', 'arg0')])
## aodv-packet.h (module 'aodv'): ns3::aodv::RrepAckHeader::RrepAckHeader() [constructor]
cls.add_constructor([])
## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RrepAckHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## aodv-packet.h (module 'aodv'): ns3::TypeId ns3::aodv::RrepAckHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RrepAckHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## aodv-packet.h (module 'aodv'): static ns3::TypeId ns3::aodv::RrepAckHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepAckHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepAckHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
return
def register_Ns3AodvRrepHeader_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## aodv-packet.h (module 'aodv'): ns3::aodv::RrepHeader::RrepHeader(ns3::aodv::RrepHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::aodv::RrepHeader const &', 'arg0')])
## aodv-packet.h (module 'aodv'): ns3::aodv::RrepHeader::RrepHeader(uint8_t prefixSize=0, uint8_t hopCount=0, ns3::Ipv4Address dst=ns3::Ipv4Address(), uint32_t dstSeqNo=0, ns3::Ipv4Address origin=ns3::Ipv4Address(), ns3::Time lifetime=ns3::MilliSeconds( )) [constructor]
cls.add_constructor([param('uint8_t', 'prefixSize', default_value='0'), param('uint8_t', 'hopCount', default_value='0'), param('ns3::Ipv4Address', 'dst', default_value='ns3::Ipv4Address()'), param('uint32_t', 'dstSeqNo', default_value='0'), param('ns3::Ipv4Address', 'origin', default_value='ns3::Ipv4Address()'), param('ns3::Time', 'lifetime', default_value='ns3::MilliSeconds(0)')])
## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RrepHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## aodv-packet.h (module 'aodv'): bool ns3::aodv::RrepHeader::GetAckRequired() const [member function]
cls.add_method('GetAckRequired',
'bool',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): ns3::Ipv4Address ns3::aodv::RrepHeader::GetDst() const [member function]
cls.add_method('GetDst',
'ns3::Ipv4Address',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RrepHeader::GetDstSeqno() const [member function]
cls.add_method('GetDstSeqno',
'uint32_t',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): uint8_t ns3::aodv::RrepHeader::GetHopCount() const [member function]
cls.add_method('GetHopCount',
'uint8_t',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): ns3::TypeId ns3::aodv::RrepHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## aodv-packet.h (module 'aodv'): ns3::Time ns3::aodv::RrepHeader::GetLifeTime() const [member function]
cls.add_method('GetLifeTime',
'ns3::Time',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): ns3::Ipv4Address ns3::aodv::RrepHeader::GetOrigin() const [member function]
cls.add_method('GetOrigin',
'ns3::Ipv4Address',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): uint8_t ns3::aodv::RrepHeader::GetPrefixSize() const [member function]
cls.add_method('GetPrefixSize',
'uint8_t',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RrepHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## aodv-packet.h (module 'aodv'): static ns3::TypeId ns3::aodv::RrepHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::SetAckRequired(bool f) [member function]
cls.add_method('SetAckRequired',
'void',
[param('bool', 'f')])
## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::SetDst(ns3::Ipv4Address a) [member function]
cls.add_method('SetDst',
'void',
[param('ns3::Ipv4Address', 'a')])
## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::SetDstSeqno(uint32_t s) [member function]
cls.add_method('SetDstSeqno',
'void',
[param('uint32_t', 's')])
## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::SetHello(ns3::Ipv4Address src, uint32_t srcSeqNo, ns3::Time lifetime) [member function]
cls.add_method('SetHello',
'void',
[param('ns3::Ipv4Address', 'src'), param('uint32_t', 'srcSeqNo'), param('ns3::Time', 'lifetime')])
## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::SetHopCount(uint8_t count) [member function]
cls.add_method('SetHopCount',
'void',
[param('uint8_t', 'count')])
## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::SetLifeTime(ns3::Time t) [member function]
cls.add_method('SetLifeTime',
'void',
[param('ns3::Time', 't')])
## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::SetOrigin(ns3::Ipv4Address a) [member function]
cls.add_method('SetOrigin',
'void',
[param('ns3::Ipv4Address', 'a')])
## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::SetPrefixSize(uint8_t sz) [member function]
cls.add_method('SetPrefixSize',
'void',
[param('uint8_t', 'sz')])
return
def register_Ns3AodvRreqHeader_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## aodv-packet.h (module 'aodv'): ns3::aodv::RreqHeader::RreqHeader(ns3::aodv::RreqHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::aodv::RreqHeader const &', 'arg0')])
## aodv-packet.h (module 'aodv'): ns3::aodv::RreqHeader::RreqHeader(uint8_t flags=0, uint8_t reserved=0, uint8_t hopCount=0, uint32_t requestID=0, ns3::Ipv4Address dst=ns3::Ipv4Address(), uint32_t dstSeqNo=0, ns3::Ipv4Address origin=ns3::Ipv4Address(), uint32_t originSeqNo=0) [constructor]
cls.add_constructor([param('uint8_t', 'flags', default_value='0'), param('uint8_t', 'reserved', default_value='0'), param('uint8_t', 'hopCount', default_value='0'), param('uint32_t', 'requestID', default_value='0'), param('ns3::Ipv4Address', 'dst', default_value='ns3::Ipv4Address()'), param('uint32_t', 'dstSeqNo', default_value='0'), param('ns3::Ipv4Address', 'origin', default_value='ns3::Ipv4Address()'), param('uint32_t', 'originSeqNo', default_value='0')])
## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RreqHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## aodv-packet.h (module 'aodv'): bool ns3::aodv::RreqHeader::GetDestinationOnly() const [member function]
cls.add_method('GetDestinationOnly',
'bool',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): ns3::Ipv4Address ns3::aodv::RreqHeader::GetDst() const [member function]
cls.add_method('GetDst',
'ns3::Ipv4Address',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RreqHeader::GetDstSeqno() const [member function]
cls.add_method('GetDstSeqno',
'uint32_t',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): bool ns3::aodv::RreqHeader::GetGratiousRrep() const [member function]
cls.add_method('GetGratiousRrep',
'bool',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): uint8_t ns3::aodv::RreqHeader::GetHopCount() const [member function]
cls.add_method('GetHopCount',
'uint8_t',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RreqHeader::GetId() const [member function]
cls.add_method('GetId',
'uint32_t',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): ns3::TypeId ns3::aodv::RreqHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## aodv-packet.h (module 'aodv'): ns3::Ipv4Address ns3::aodv::RreqHeader::GetOrigin() const [member function]
cls.add_method('GetOrigin',
'ns3::Ipv4Address',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RreqHeader::GetOriginSeqno() const [member function]
cls.add_method('GetOriginSeqno',
'uint32_t',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RreqHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## aodv-packet.h (module 'aodv'): static ns3::TypeId ns3::aodv::RreqHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## aodv-packet.h (module 'aodv'): bool ns3::aodv::RreqHeader::GetUnknownSeqno() const [member function]
cls.add_method('GetUnknownSeqno',
'bool',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::SetDestinationOnly(bool f) [member function]
cls.add_method('SetDestinationOnly',
'void',
[param('bool', 'f')])
## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::SetDst(ns3::Ipv4Address a) [member function]
cls.add_method('SetDst',
'void',
[param('ns3::Ipv4Address', 'a')])
## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::SetDstSeqno(uint32_t s) [member function]
cls.add_method('SetDstSeqno',
'void',
[param('uint32_t', 's')])
## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::SetGratiousRrep(bool f) [member function]
cls.add_method('SetGratiousRrep',
'void',
[param('bool', 'f')])
## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::SetHopCount(uint8_t count) [member function]
cls.add_method('SetHopCount',
'void',
[param('uint8_t', 'count')])
## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::SetId(uint32_t id) [member function]
cls.add_method('SetId',
'void',
[param('uint32_t', 'id')])
## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::SetOrigin(ns3::Ipv4Address a) [member function]
cls.add_method('SetOrigin',
'void',
[param('ns3::Ipv4Address', 'a')])
## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::SetOriginSeqno(uint32_t s) [member function]
cls.add_method('SetOriginSeqno',
'void',
[param('uint32_t', 's')])
## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::SetUnknownSeqno(bool f) [member function]
cls.add_method('SetUnknownSeqno',
'void',
[param('bool', 'f')])
return
def register_Ns3AodvTypeHeader_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## aodv-packet.h (module 'aodv'): ns3::aodv::TypeHeader::TypeHeader(ns3::aodv::TypeHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::aodv::TypeHeader const &', 'arg0')])
## aodv-packet.h (module 'aodv'): ns3::aodv::TypeHeader::TypeHeader(ns3::aodv::MessageType t) [constructor]
cls.add_constructor([param('ns3::aodv::MessageType', 't')])
## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::TypeHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## aodv-packet.h (module 'aodv'): ns3::aodv::MessageType ns3::aodv::TypeHeader::Get() const [member function]
cls.add_method('Get',
'ns3::aodv::MessageType',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): ns3::TypeId ns3::aodv::TypeHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::TypeHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## aodv-packet.h (module 'aodv'): static ns3::TypeId ns3::aodv::TypeHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## aodv-packet.h (module 'aodv'): bool ns3::aodv::TypeHeader::IsValid() const [member function]
cls.add_method('IsValid',
'bool',
[],
is_const=True)
## aodv-packet.h (module 'aodv'): void ns3::aodv::TypeHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## aodv-packet.h (module 'aodv'): void ns3::aodv::TypeHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, 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_aodv(module.get_submodule('aodv'), root_module)
return
def register_functions_ns3_FatalImpl(module, root_module):
return
def register_functions_ns3_aodv(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()
|
danielcbit/vdt
|
src/aodv/bindings/modulegen__gcc_LP64.py
|
Python
|
gpl-2.0
| 494,944
|
# import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
axis('equal')
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
data = numpy.loadtxt("conv_dof_hp_iso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="hp-FEM (iso)")
data = numpy.loadtxt("conv_dof_hp_aniso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="hp-FEM (aniso)")
legend()
# finalize
show()
|
hanak/hermes2d
|
doc/src/img/singular-perturbation/plot_graph_hp_dof.py
|
Python
|
gpl-2.0
| 459
|
def hu(n, s=-1):
return [s]
a = hu(10)
c = [i for i in hu(10)]
|
RobertoMalatesta/shedskin
|
tests/40.py
|
Python
|
gpl-3.0
| 68
|
"""
Takes user input.
"""
import sys
from six.moves import input
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is one of "yes" or "no".
"""
valid = {
"yes": True,
"y": True,
"ye": True,
"no": False,
"n": False,
}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError(u"invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' (or 'y' or 'n').\n")
|
stvstnfrd/edx-platform
|
cms/djangoapps/contentstore/management/commands/prompt.py
|
Python
|
agpl-3.0
| 1,176
|
# This file is part of VoltDB.
# Copyright (C) 2008-2015 VoltDB Inc.
#
# This file contains original code and/or modifications of original code.
# Any modifications made by VoltDB Inc. are licensed under the following
# terms and conditions:
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS 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.
# Volt CLI utility functions.
# IMPORTANT: This depends on no other voltcli modules. Please keep it that way.
import sys
import os
import subprocess
import glob
import copy
import inspect
import ConfigParser
import zipfile
import re
import pkgutil
import binascii
import stat
import daemon
import signal
import textwrap
import string
#===============================================================================
class Global:
#===============================================================================
"""
Global data for utilities.
"""
verbose_enabled = False
debug_enabled = False
dryrun_enabled = False
manifest_path = 'MANIFEST'
state_directory = ''
#===============================================================================
def set_dryrun(dryrun):
#===============================================================================
"""
Enable or disable command dry run (display only/no execution).
"""
Global.dryrun_enabled = dryrun
#===============================================================================
def set_verbose(verbose):
#===============================================================================
"""
Enable or disable verbose messages. Increases the number of INFO messages.
"""
Global.verbose_enabled = verbose
#===============================================================================
def set_debug(debug):
#===============================================================================
"""
Enable or disable DEBUG messages. Also enables verbose INFO messages.
"""
Global.debug_enabled = debug
if debug:
Global.verbose_enabled = True
#===============================================================================
def set_state_directory(directory):
#===============================================================================
if not os.path.exists(directory):
try:
os.makedirs(directory)
except (OSError, IOError), e:
abort('Error creating state directory "%s".' % directory, e)
Global.state_directory = os.path.expandvars(os.path.expanduser(directory))
#===============================================================================
def get_state_directory():
#===============================================================================
"""
Return and create as needed a path for saving state.
"""
return Global.state_directory
#===============================================================================
def is_dryrun():
#===============================================================================
"""
Return True if dry-run is enabled.
"""
return Global.dryrun_enabled
#===============================================================================
def is_verbose():
#===============================================================================
"""
Return True if verbose messages are enabled.
"""
return Global.verbose_enabled
#===============================================================================
def is_debug():
#===============================================================================
"""
Return True if debug messages are enabled.
"""
return Global.debug_enabled
#===============================================================================
def get_state_directory():
#===============================================================================
return Global.state_directory
#===============================================================================
def display_messages(msgs, f = sys.stdout, tag = None, level = 0):
#===============================================================================
"""
Low level message display.
"""
if tag:
stag = '%s: ' % tag
else:
stag = ''
# Special case to allow a string instead of an iterable.
try:
# Raises TypeError if not string
var = msgs + ' '
msgs = [msgs]
except TypeError:
pass
sindent = level * ' '
# Recursively process message list and sub-lists.
for msg in msgs:
if msg is not None:
# Handle exceptions
if issubclass(msg.__class__, Exception):
f.write('%s%s%s Exception: %s\n' % (stag, sindent, msg.__class__.__name__, str(msg)))
else:
# Handle multi-line strings
if is_string(msg):
# If it is a string slice and dice it by linefeeds.
for msg2 in msg.split('\n'):
f.write('%s%s%s\n' % (stag, sindent, msg2))
else:
# Recursively display an iterable with indentation added.
if hasattr(msg, '__iter__'):
display_messages(msg, f = f, tag = tag, level = level + 1)
else:
for msg2 in str(msg).split('\n'):
f.write('%s%s%s\n' % (stag, sindent, msg2))
#===============================================================================
def info(*msgs):
#===============================================================================
"""
Display INFO level messages.
"""
display_messages(msgs, tag = 'INFO')
#===============================================================================
def verbose_info(*msgs):
#===============================================================================
"""
Display verbose INFO level messages if enabled.
"""
if Global.verbose_enabled:
display_messages(msgs, tag = 'INFO2')
#===============================================================================
def debug(*msgs):
#===============================================================================
"""
Display DEBUG level message(s) if debug is enabled.
"""
if Global.debug_enabled:
display_messages(msgs, tag = 'DEBUG')
#===============================================================================
def warning(*msgs):
#===============================================================================
"""
Display WARNING level messages.
"""
display_messages(msgs, tag = 'WARNING')
#===============================================================================
def error(*msgs):
#===============================================================================
"""
Display ERROR level messages.
"""
display_messages(msgs, tag = 'ERROR')
#===============================================================================
def abort(*msgs, **kwargs):
#===============================================================================
"""
Display ERROR messages and then abort.
:Keywords:
return_code: integer result returned to the OS (default=1)
"""
keys = kwargs.keys()
bad_keywords = [k for k in kwargs.keys() if k != 'return_code']
if bad_keywords:
warning('Bad keyword(s) passed to abort(): %s' % ' '.join(bad_keywords))
return_code = kwargs.get('return_code', 1)
error(*msgs)
# Return code must be 0-255 for shell.
if return_code != 0:
return_code = 1
sys.exit(return_code)
#===============================================================================
def find_in_path(name):
#===============================================================================
"""
Find program in the system path.
"""
# NB: non-portable
for dir in os.environ['PATH'].split(':'):
if os.path.exists(os.path.join(dir, name)):
return os.path.join(dir, name)
return None
#===============================================================================
def find_programs(*names):
#===============================================================================
"""
Check for required programs in the path.
"""
missing = []
paths = {}
for name in names:
paths[name] = find_in_path(name)
if paths[name] is None:
missing.append(name)
if missing:
abort('Required program(s) are not in the path:', missing)
return paths
#===============================================================================
class PythonSourceFinder(object):
#===============================================================================
"""
Find and invoke python source files in a set of directories and resource
subdirectories (for searching in zip packages). Execute all discovered
source files and pass in the symbols provided.
A typical usage relies on decorators to mark discoverable functions in user
code. The decorator is called when the source file is executed which serves
as an opportunity to keep track of discovered functions.
"""
class Scan(object):
def __init__(self, package, path):
self.package = package
self.path = path
def __init__(self):
self.scan_locs = []
self.manifests = {}
def add_path(self, path):
# Use the absolute path to avoid visiting the same directory more than once.
full_path = os.path.realpath(path)
for scan_loc in self.scan_locs:
if scan_loc.path == full_path:
break
else:
self.scan_locs.append(PythonSourceFinder.Scan(None, full_path))
def add_resource(self, package, path):
self.scan_locs.append(PythonSourceFinder.Scan(package, path))
def search_and_execute(self, **syms):
for scan_loc in self.scan_locs:
verbose_info('Scanning "%s" for modules to run...' % scan_loc.path)
if scan_loc.package:
# Load the manifest as needed so that individual files can be
# found in package directories. There doesn't seem to be an
# easy way to search for resource files, e.g. by glob pattern.
if scan_loc.package not in self.manifests:
try:
manifest_raw = pkgutil.get_data(scan_loc.package, Global.manifest_path)
self.manifests[scan_loc.package] = manifest_raw.split('\n')
except (IOError, OSError), e:
abort('Failed to load package %s.' % Global.manifest_path, e)
for path in self.manifests[scan_loc.package]:
if os.path.dirname(path) == scan_loc.path and path.endswith('.py'):
debug('Executing package module "%s"...' % path)
try:
code = pkgutil.get_data(scan_loc.package, path)
except (IOError, OSError), e:
abort('Failed to load package resource "%s".' % path, e)
syms_tmp = copy.copy(syms)
exec(code, syms_tmp)
elif os.path.exists(scan_loc.path):
for modpath in glob.glob(os.path.join(scan_loc.path, '*.py')):
debug('Executing module "%s"...' % modpath)
syms_tmp = copy.copy(syms)
execfile(modpath, syms_tmp)
#===============================================================================
def normalize_list(items, width, filler = None):
#===============================================================================
"""
Normalize list to a specified width, truncating or filling as needed.
Filler data can be supplied by caller. The filler will be copied to each
added item. None will be used as the filler if none is provided.
"""
assert items is not None
assert width >= 0
output = items[:width]
if len(output) < width:
output += filler * (width - len(output))
return tuple(output)
#===============================================================================
def format_table(tuples, caption = None, headings = None, indent = 0, separator = ' '):
#===============================================================================
"""
Format a table, i.e. tuple list, including an optional caption, optional
column headings, and rows of data cells. Aligns the headings and data
cells. Headings and data rows must be iterable. Each data row must provide
iterable cells. For now it only handles stringized data and right
alignment. Returns the table-formatted string.
"""
output = []
sindent = ' ' * indent
# Display the caption, if supplied.
if caption:
output.append('\n%s-- %s --\n' % (sindent, caption))
rows = []
# Add a row for headings, if supplied. Underlining is added after widths are known.
if headings:
rows.append(headings)
# Add the data rows.
rows.extend(tuples)
# Measure the column widths.
widths = []
for row in rows:
icolumn = 0
for column in row:
width = len(str(column))
if len(widths) == icolumn:
widths.append(width)
else:
widths[icolumn] = max(widths[icolumn], width)
icolumn += 1
# If we have headings inject a row with underlining based on the calculated widths.
if headings:
rows.insert(1, ['-' * widths[i] for i in range(len(widths))])
# Generate the format string and then format the headings and rows.
fmt = '%s%s' % (sindent, separator.join(['%%-%ds' % width for width in widths]))
for row in rows:
output.append(fmt % normalize_list(row, len(widths), ''))
return '\n'.join(output)
#===============================================================================
def format_tables(tuples_list, caption_list = None, heading_list = None, indent = 0):
#===============================================================================
"""
Format multiple tables, i.e. a list of tuple lists. See format_table() for
more information.
"""
output = []
for i in range(len(tuples_list)):
if caption_list is None or i >= len(caption_list):
caption = None
else:
caption = caption_list[i]
if heading_list is None or i >= len(heading_list):
heading = None
else:
heading = heading_list[i]
s = format_table(tuples_list[i], caption = caption, heading = heading, indent = indent)
output.append(s)
return '\n\n'.join(output)
#===============================================================================
def format_volt_table(table, caption = None, headings = True):
#===============================================================================
"""
Format a VoltTable for display.
"""
rows = table.tuples
if headings:
heading_row = [c.name for c in table.columns]
else:
heading_row = None
return format_table(rows, caption = caption, headings = heading_row)
#===============================================================================
def format_volt_tables(table_list, caption_list = None, headings = True):
#===============================================================================
"""
Format a list of VoltTable's for display.
"""
output = []
if table_list:
for i in range(len(table_list)):
if caption_list is None or i >= len(caption_list):
caption = None
else:
caption = caption_list[i]
output.append(format_volt_table(table_list[i], caption = caption, headings = headings))
return '\n\n'.join(output)
#===============================================================================
def quote_shell_arg(arg):
#===============================================================================
"""
Return an argument with quotes added as needed.
"""
sarg = str(arg)
if len(sarg) == 0 or len(sarg.split()) > 1:
return '"%s"' % sarg
return sarg
#===============================================================================
def unquote_shell_arg(arg):
#===============================================================================
"""
Return an argument with quotes removed if present.
"""
sarg = str(arg)
if len(sarg) == 0:
return sarg
quote_char = sarg[-1]
if quote_char not in ('"', "'"):
return sarg
# Deal with a starting quote that might not be at the beginning
if sarg[0] == quote_char:
return sarg[1:-1]
pos = sarg.find(quote_char)
if pos == len(sarg) - 1:
# No first quote, don't know what else to do but return as is
return sarg
return sarg[:pos] + sarg[pos+1:-1]
#===============================================================================
def quote_shell_args(*args_in):
#===============================================================================
"""
Return a list of arguments that are quoted as needed.
"""
return [quote_shell_arg(arg) for arg in args_in]
#===============================================================================
def unquote_shell_args(*args_in):
#===============================================================================
"""
Return a list of arguments with quotes removed when present.
"""
return [unquote_shell_arg(arg) for arg in args_in]
#===============================================================================
def join_shell_cmd(cmd, *args):
#===============================================================================
"""
Join shell command and arguments into one string.
Add quotes as appropriate.
"""
return ' '.join(quote_shell_args(cmd, *args))
#===============================================================================
def run_cmd(cmd, *args):
#===============================================================================
"""
Run external program without capturing or suppressing output and check return code.
"""
fullcmd = join_shell_cmd(cmd, *args)
if Global.dryrun_enabled:
sys.stdout.write('Run: %s\n' % fullcmd)
else:
if Global.verbose_enabled:
verbose_info('Run: %s' % fullcmd)
retcode = os.system(fullcmd)
if retcode != 0:
abort(return_code=retcode)
#===============================================================================
def exec_cmd(cmd, *args):
#===============================================================================
"""
Run external program by replacing the current (Python) process.
"""
display_cmd = join_shell_cmd(cmd, *args)
if Global.dryrun_enabled:
sys.stdout.write('Exec: %s\n' % display_cmd)
else:
if Global.verbose_enabled:
verbose_info('Exec: %s' % display_cmd)
# Need to strip out quotes because the shell won't be doing it for us.
cmd_and_args = unquote_shell_args(cmd, *args)
os.execvp(cmd, cmd_and_args)
#===============================================================================
def pipe_cmd(*args):
#===============================================================================
"""
Run an external program, capture its output, and yield each output line for
iteration.
"""
try:
proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(proc.stdout.readline, ''):
yield line.rstrip()
proc.stdout.close()
except Exception, e:
warning('Exception running command: %s' % ' '.join(args), e)
#===============================================================================
def daemon_file_name(base_name=None, host=None, instance=None):
#===============================================================================
"""
Build a daemon output file name using optional base name, host, and instance.
"""
names = []
if not base_name is None:
names.append(base_name)
if not host is None:
names.append(host.replace(':', '_'))
if not names:
names.append('server')
if not instance is None:
names.append('_%d' % instance)
daemon_name = ''.join(names)
return daemon_name
#===============================================================================
class Daemonizer(daemon.Daemon):
#===============================================================================
"""
Class that supports daemonization (inherited from the daemon module). The
current process, i.e. the running Python script is completely replaced by
the executed program.
"""
def __init__(self, name, description, output=None):
"""
Constructor. The optional "output" keyword specifies an override to
the default ~/.command_name output directory.
"""
self.name = name
self.description = description
self.output_dir = output
if self.output_dir is None:
self.output_dir = get_state_directory()
pid = os.path.join(self.output_dir, '%s.pid' % name)
out = os.path.join(self.output_dir, '%s.out' % name)
err = os.path.join(self.output_dir, '%s.err' % name)
self.output_files = [out, err]
daemon.Daemon.__init__(self, pid, stdout=out, stderr=err)
# Clean up PID files of defunct processes.
self.purge_defunct()
def start_daemon(self, *args):
"""
Start a daemon process.
"""
# Replace existing output files.
for path in self.output_files:
if os.path.exists(path):
try:
os.remove(path)
except (IOError, OSError), e:
abort('Unable to remove the existing output file "%s".' % path, e)
try:
info('Starting %s in the background...' % (self.description), [
'Output files are in "%s".' % self.output_dir
])
self.start(*args)
except daemon.Daemon.AlreadyRunningException, e:
abort('A %s background process appears to be running.' % self.description, (
'Process ID (PID): %d' % e.pid,
'PID file: %s' % e.pidfile),
'Please stop the process and try again.')
except (IOError, OSError), e:
abort('Unable to start the %s background process.' % self.description, e)
def stop_daemon(self, kill_signal=signal.SIGTERM):
"""
Stop a daemon process.
"""
try:
daemon.Daemon.stop(self, kill_signal=kill_signal)
info("%s (process ID %d) was stopped." % (self.description, self.pid))
except daemon.Daemon.NotRunningException, e:
if e.pid != -1:
addendum = ' as process ID %d' % e.pid
else:
addendum = ''
abort('%s is no longer running%s.' % (self.description, addendum))
except (IOError, OSError), e:
abort('Unable to stop the %s background process.' % self.description, e)
def on_started(self, *args_in):
"""
Post-daemonization call-back.
"""
# Strip out things requiring shell interpretation, e.g. quotes.
args = [arg.replace('"', '') for arg in args_in]
try:
os.execvp(args[0], args)
except (OSError, IOError), e:
abort('Failed to exec:', args, e)
def get_running(self):
"""
Scan for PID files that have running processes.
Returns a list of the current running PIDs.
"""
running = []
for path in glob.glob(os.path.join(self.output_dir, "*.pid")):
pid, alive = daemon.get_status(path)
if alive:
running.append(pid)
return running
def purge_defunct(self):
"""
Purge PID files of defunct daemon processes.
"""
for path in glob.glob(os.path.join(self.output_dir, "*.pid")):
pid, alive = daemon.get_status(path)
if not alive:
try:
info('Deleting stale PID file "%s"...' % path)
os.remove(path)
except (OSError, IOError), e:
warning('Failed to delete PID file "%s".' % path, e)
#===============================================================================
def is_string(item):
#===============================================================================
"""
Return True if the item behaves like a string.
"""
try:
test_string = item + ''
return True
except TypeError:
return False
#===============================================================================
def is_sequence(item):
#===============================================================================
"""
Return True if the item behaves like an iterable sequence.
"""
if is_string(item):
return False
try:
for var in item:
break
return True
except TypeError:
return False
#===============================================================================
def _flatten(item):
#===============================================================================
"""
Internal function to recursively iterate a potentially nested sequence.
None items are filtered out.
"""
if item is not None:
if is_sequence(item):
for subitem in item:
for subsubitem in _flatten(subitem):
if subsubitem is not None:
yield subsubitem
else:
yield item
#===============================================================================
def flatten(*items):
#===============================================================================
"""
Flatten and yield individual items from a potentially nested list or tuple.
"""
for item in _flatten(items):
yield item
#===============================================================================
def flatten_to_list(*items):
#===============================================================================
"""
Flatten a potentially nested list or tuple to a simple list.
"""
return [item for item in flatten(*items)]
#===============================================================================
def to_display_string(item):
#===============================================================================
"""
Recursively convert simple items and potentially nested sequences to a
string, using square brackets and commas to format sequences.
"""
if not is_sequence(item):
return str(item)
s = ''
for subitem in item:
if s:
s += ', '
s += to_display_string(subitem)
return '[%s]' % s
#===============================================================================
class Zipper(object):
#===============================================================================
"""
The Zipper class creates a zip file using the directories, strings, and
exclusion regular expresions provided. It can also add a preamble and make
the resulting file executable in order to support making a self-executable
compressed Python program.
"""
def __init__(self, excludes = []):
self.output_file = None
self.output_zip = None
self.output_path = None
self.manifest = []
self.re_excludes = [re.compile(exclude) for exclude in excludes]
def open(self, output_path, preamble = None, force = False):
if os.path.exists(output_path) and not force:
if choose('Overwrite "%s"?' % output_path, 'yes', 'no') == 'n':
abort()
self.output_path = output_path
if not Global.dryrun_enabled:
try:
self.output_file = open(output_path, 'w');
if preamble:
self.output_file.write(preamble)
self.output_zip = zipfile.ZipFile(self.output_file, 'w', zipfile.ZIP_DEFLATED)
except (IOError, OSError), e:
self._abort('Failed to open for writing.', e)
def close(self, make_executable = False):
if self.output_zip:
# Write the manifest.
try:
self.output_zip.writestr(Global.manifest_path, '\n'.join(self.manifest))
except (IOError, OSError), e:
self._abort('Failed to write %s.' % Global.manifest_path, e)
self.output_zip.close()
self.output_file.close()
if make_executable:
mode = os.stat(self.output_path).st_mode
try:
os.chmod(self.output_path, mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
except (IOError, OSError), e:
self._abort('Failed to add executable permission.', e)
def add_file(self, path_in, path_out):
for re_exclude in self.re_excludes:
path_in_full = os.path.realpath(path_in)
if re_exclude.search(path_in):
self._verbose_info('skip "%s"' % path_in_full)
break
else:
self._verbose_info('add "%s" as "%s"' % (path_in_full, path_out))
try:
if self.output_zip:
self.output_zip.write(path_in, path_out)
self.manifest.append(path_out)
except (IOError, OSError), e:
self._abort('Failed to write file "%s".' % path_out, e)
def add_file_from_string(self, s, path_out):
self._verbose_info('write string to "%s"' % path_out)
if self.output_zip:
try:
self.output_zip.writestr(path_out, s)
self.manifest.append(path_out)
except (IOError, OSError), e:
self._abort('Failed to write string to file "%s".' % path_out, e)
def add_directory(self, path_in, dst, excludes = []):
if not os.path.isdir(path_in):
self._abort('Zip source directory "%s" does not exist.' % path_in)
self._verbose_info('add directory "%s" to "%s"' % (path_in, dst))
savedir = os.getcwd()
# Get nice relative paths by temporarily switching directories.
os.chdir(path_in)
try:
for basedir, subdirs, filenames in os.walk('.'):
for filename in filenames:
file_path_in = os.path.join(basedir[2:], filename)
file_path_out = os.path.join(dst, basedir[2:], filename)
self.add_file(file_path_in, file_path_out)
finally:
os.chdir(savedir)
def _verbose_info(self, msg):
verbose_info('%s: %s' % (self.output_path, msg))
def _abort(self, *msgs):
abort('Fatal error writing zip file "%s".' % self.output_path, msgs)
#===============================================================================
def merge_java_options(*opts):
#===============================================================================
"""
Merge redundant -X... java command line options. Keep others intact.
Arguments can be lists or individual arguments. Returns the reduced list.
"""
ret_opts = []
xargs = set()
for opt in flatten(*opts):
if opt is not None:
# This is somewhat simplistic logic that might have unlikely failure scenarios.
if opt.startswith('-X'):
# The symbol is the initial string of contiguous alphabetic characters.
sym = ''.join([c for c in opt[2:] if c.isalpha()])
if sym not in xargs:
xargs.add(sym)
ret_opts.append(opt)
else:
ret_opts.append(opt)
return ret_opts
#===============================================================================
def kwargs_merge_list(kwargs, name, *args):
#===============================================================================
"""
Merge and flatten kwargs list with additional items.
"""
kwargs[name] = flatten_to_list(kwargs.get(name, None), *args)
#===============================================================================
def kwargs_merge_java_options(kwargs, name, *args):
#===============================================================================
"""
Merge and flatten kwargs Java options list with additional options.
"""
kwargs[name] = merge_java_options(kwargs.get(name, None), *args)
#===============================================================================
def choose(prompt, *choices):
#===============================================================================
"""
Prompt the user for multiple choice input. Keep prompting until a valid
choice is received. Choice shortcuts require unique first letters. The user
can either respond with a single letter or an entire word.
"""
letters = set()
choice_list = []
for choice in choices:
if not choice:
abort('Empty choice passed to choose().')
if choice[0] in letters:
abort('Non-unique choices %s passed to choose().' % str(choices))
letters.add(choice[0])
choice_list.append('[%s]%s' % (choice[0], choice[1:]))
while True:
sys.stdout.write('%s (%s) ' % (prompt, '/'.join(choice_list)))
sys.stdout.flush()
response = sys.stdin.readline().strip()
if response in letters or response in choices:
return response[0]
#===============================================================================
def dict_to_sorted_pairs(d):
#===============================================================================
"""
Convert a dictionary to a list of key/value pairs sorted by key.
"""
keys = d.keys()
keys.sort()
results = []
for key in keys:
results.append((key, d[key]))
return results
#===============================================================================
def pluralize(s, count):
#===============================================================================
"""
Return word with 's' appended if the count > 1.
"""
if count > 1:
return '%ss' % s
return s
#===============================================================================
def kwargs_extract(kwargs, defaults, remove = True, check_extras = False):
#===============================================================================
"""
Extract and optionally remove valid keyword arguments and convert to an
object with attributes. The defaults argument specifies both the list of
valid keywords and their default values. Abort on any invalid keyword.
"""
class O(object):
pass
o = O()
if check_extras:
bad = list(set(kwargs.keys()).difference(set(defaults.keys())))
if bad:
bad.sort()
abort('Bad keywords passed to kwargs_extract():', bad)
for name in defaults:
if name in kwargs:
if remove:
value = kwargs.pop(name)
else:
value = kwargs[name]
else:
value = defaults[name]
setattr(o, name, value)
return o
#===============================================================================
def kwargs_get(kwargs, name, remove = True, default = None):
#===============================================================================
defaults = {name: default}
args = kwargs_extract(kwargs, defaults, remove = remove, check_extras = False)
return getattr(args, name)
#===============================================================================
def kwargs_get_string(kwargs, name, remove = True, default = None):
#===============================================================================
value = kwargs_get(kwargs, name, remove = remove, default = default)
if value is not None:
value = str(value)
return value
#===============================================================================
def kwargs_get_integer(kwargs, name, remove = True, default = None):
#===============================================================================
value = kwargs_get(kwargs, name, remove = remove, default = default)
if value is not None:
try:
value = int(value)
except (ValueError, TypeError):
abort('Keyword argument "%s" must be an integer: %s' % (name, str(value)))
return value
#===============================================================================
def kwargs_get_boolean(kwargs, name, remove = True, default = None):
#===============================================================================
value = kwargs_get(kwargs, name, remove = remove, default = default)
if value is None or value == True or value == False:
return value
abort('Keyword argument "%s" must be a boolean value: %s' % (name, str(value)))
#===============================================================================
def kwargs_get_list(kwargs, name, remove = True, default = []):
#===============================================================================
return flatten_to_list(kwargs_get(kwargs, name, remove = remove, default = default))
#===============================================================================
def kwargs_set_defaults(kwargs, **defaults):
#===============================================================================
for name in defaults:
if name not in kwargs:
kwargs[name] = defaults[name]
#===============================================================================
def parse_hosts(host_string, min_hosts = None, max_hosts = None, default_port = None):
#===============================================================================
"""
Split host string on commas, extract optional port for each and return list
of host objects. Check against minimum/maximum quantities if specified.
"""
class Host(object):
def __init__(self, host, port):
self.host = host
self.port = port
hosts = []
for host_port in host_string.split(','):
split_host = host_port.split(':')
host = split_host[0]
if len(split_host) > 2:
abort('Bad HOST:PORT format "%s" - too many colons.' % host_port)
if len(split_host) == 1:
# Add the default port if specified. Validated by caller to be an integer.
if default_port:
port = default_port
else:
port = None
else:
try:
port = int(split_host[1])
except ValueError, e:
abort('Bad port value "%s" for host: %s' % (split_host[1], host_port))
hosts.append(Host(host, port))
if min_hosts is not None and len(hosts) < min_hosts:
abort('Too few hosts in host string "%s". The minimum is %d.'
% (host_string, min_hosts))
if max_hosts is not None and len(hosts) > max_hosts:
abort('Too many hosts in host string "%s". The maximum is %d.'
% (host_string, max_hosts))
return hosts
#===============================================================================
def paragraph(*lines):
#===============================================================================
"""
Strip leading and trailing whitespace and wrap text into a paragraph block.
The arguments can include arbitrarily nested sequences.
"""
wlines = []
for line in flatten_to_list(lines):
wlines.extend(line.strip().split('\n'))
return textwrap.fill('\n'.join(wlines))
#===============================================================================
class File(object):
#===============================================================================
"""
File reader/writer object that aborts on any error. Must explicitly call
close(). The main point is to standardize the error-handling.
"""
def __init__(self, path, mode = 'r', make_dirs=False):
if mode not in ('r', 'w'):
abort('Invalid file mode "%s".' % mode)
self.path = path
self.mode = mode
self.make_dirs = make_dirs
self.f = None
def open(self):
self.close()
if self.mode == 'w' and self.make_dirs:
dir = os.path.dirname(self.path)
if dir and not os.path.exists(dir):
try:
os.makedirs(dir)
except (IOError, OSError), e:
self._abort('Unable to create directory "%s".' % dir)
self.f = self._open()
def read(self):
if self.mode != 'r':
self._abort('File is not open for reading in call to read().')
# Reading the entire file, so we can automatically open and close here.
if self.f is None:
f = self._open()
else:
f = self.f
try:
try:
return f.read()
except (IOError, OSError), e:
self._abort('Read error.', e)
finally:
# Close locally-opened file.
if self.f is None:
f.close()
def read_hex(self):
return binascii.hexlify(self.read())
def write(self, s):
if self.mode != 'w':
self._abort('File is not open for writing in call to write().')
if self.f is None:
self._abort('File was not opened in call to write().')
try:
self.f.write(s)
except (IOError, OSError), e:
self._abort('Write error.', e)
def close(self):
if self.f:
self.f.close()
def _open(self):
try:
return open(self.path, self.mode)
except (IOError, OSError), e:
self._abort('File open error.', e)
def _abort(self, msg, e = None):
msgs = ['''File("%s",'%s'): %s''' % (self.path, self.mode, msg)]
if e:
msgs.append(str(e))
abort(*msgs)
#===============================================================================
class FileGenerator(object):
#===============================================================================
"""
File generator.
"""
def __init__(self, resource_finder, **symbols):
"""
resource_finder must implement a find_resource(path) method.
"""
self.resource_finder = resource_finder
self.symbols = copy.copy(symbols)
self.generated = []
def add_symbols(self, **symbols):
self.symbols.update(symbols)
def from_template(self, src, tgt=None, permissions=None):
if tgt is None:
tgt = src
info('Generating "%s"...' % tgt)
src_path = self.resource_finder.find_resource(src)
src_file = File(src_path)
src_file.open()
try:
template = string.Template(src_file.read())
s = template.safe_substitute(**self.symbols)
finally:
src_file.close()
tgt_file = File(tgt, mode='w', make_dirs=True)
tgt_file.open()
try:
tgt_file.write(s)
self.generated.append(tgt)
finally:
tgt_file.close()
if permissions is not None:
os.chmod(tgt, 0755)
def custom(self, tgt, callback):
info('Generating "%s"...' % tgt)
output_stream = File(tgt, 'w')
output_stream.open()
try:
callback(output_stream)
self.generated.append(tgt)
finally:
output_stream.close()
#===============================================================================
class INIConfigManager(object):
#===============================================================================
"""
Loads/saves INI format configuration to and from a dictionary.
"""
def load(self, path):
parser = ConfigParser.SafeConfigParser()
parser.read(path)
d = dict()
for section in parser.sections():
for name, value in parser.items(section):
d['%s.%s' % (section, name)] = value
return d
def save(self, path, d):
parser = ConfigParser.SafeConfigParser()
keys = d.keys()
keys.sort()
cur_section = None
for key in keys:
if key.find('.') == -1:
abort('Key "%s" must have a section, e.g. "volt.%s"' % (key, key))
else:
section, name = key.split('.', 1)
if cur_section is None or section != cur_section:
parser.add_section(section)
cur_section = section
parser.set(cur_section, name, d[key])
f = File(path, 'w')
f.open()
try:
parser.write(f)
finally:
f.close()
#===============================================================================
class PersistentConfig(object):
#===============================================================================
"""
Persistent access to configuration data. Manages two configuration
files, one for permanent configuration and the other for local state.
"""
def __init__(self, format, path, local_path):
"""
Construct persistent configuration based on specified format name, path
to permanent config file, and path to local config file.
"""
self.path = path
self.local_path = local_path
if format.lower() == 'ini':
self.config_manager = INIConfigManager()
else:
abort('Unsupported configuration format "%s".' % format)
self.permanent = self.config_manager.load(self.path)
if self.local_path:
self.local = self.config_manager.load(self.local_path)
else:
self.local = {}
def save_permanent(self):
"""
Save the permanent configuration.
"""
self.config_manager.save(self.path, self.permanent)
def save_local(self):
"""
Save the local configuration (overrides and additions to permanent).
"""
if self.local:
self.config_manager.save(self.local_path, self.local)
else:
error('No local configuration was specified. (%s)' % tag,
'For reference, the permanent configuration is "%s".' % self.path)
def get(self, key):
"""
Get a value for a key from the merged configuration.
"""
if key in self.local:
return self.local[key]
return self.permanent.get(key, None)
def set_permanent(self, key, value):
"""
Set a key/value pair in the permanent configuration.
"""
self.permanent[key] = value
self.save_permanent()
def set_local(self, key, value):
"""
Set a key/value pair in the local configuration.
"""
self.local[key] = value
if self.local:
self.save_local()
def query(self, filter = None):
"""
Query for keys and values as a merged dictionary.
The optional filter is matched against the start of each key.
"""
if filter:
results = {}
for key in self.local:
if key.startswith(filter):
results[key] = self.local[key]
for key in self.permanent:
if key not in results and key.startswith(filter):
results[key] = self.permanent[key]
else:
results = self.local
for key in self.permanent:
if key not in results:
results[key] = self.permanent[key]
return results
def query_pairs(self, filter = None):
"""
Query for keys and values as a sorted list of (key, value) pairs.
The optional filter is matched against the start of each key.
"""
return dict_to_sorted_pairs(self.query(filter = filter))
#===============================================================================
class VoltTupleWrapper(object):
#===============================================================================
"""
Wraps a Volt tuple to add error handling, type safety, etc..
"""
def __init__(self, tuple):
self.tuple = tuple
def column_count(self, index):
return len(self.tuple)
def column(self, index):
if index < 0 or index >= len(self.tuple):
abort('Bad column index %d (%d columns available).' % (index, len(self.tuple)))
return self.tuple[index]
def column_string(self, index):
return str(self.column(index))
def column_integer(self, index):
try:
return int(self.column(index))
except ValueError:
abort('Column %d value (%s) is not an integer.' % (index, str(self.column(index))))
def __str__(self):
return format_table([self.tuple])
#===============================================================================
class VoltTableWrapper(object):
#===============================================================================
"""
Wraps a voltdbclient.VoltTable to add error handling, type safety, etc..
"""
def __init__(self, table):
self.table = table
def tuple_count(self):
return len(self.table.tuples)
def tuple(self, index):
if index < 0 or index >= len(self.table.tuples):
abort('Bad tuple index %d (%d tuples available).' % (index, len(self.table.tuples)))
return VoltTupleWrapper(self.table.tuples[index])
def tuples(self):
return self.table.tuples
def format_table(self, caption = None):
return format_volt_table(self.table, caption = caption)
def __str__(self):
return self.format_table()
#===============================================================================
class VoltResponseWrapper(object):
#===============================================================================
"""
Wraps a voltdbclient.VoltResponse to add error handling, type safety, etc..
"""
def __init__(self, response):
self.response = response
def status(self):
return self.response.status
def table_count(self):
if not self.response.tables:
return 0
return len(self.response.tables)
def table(self, index):
if index < 0 or index >= self.table_count():
abort('Bad table index %d (%d tables available).' % (index, self.table_count()))
return VoltTableWrapper(self.response.tables[index])
def format_tables(self, caption_list = None):
return format_volt_tables(self.response.tables, caption_list = caption_list)
def __str__(self):
output = [str(self.response)]
if self.table_count() > 0:
output.append(self.format_tables())
return '\n\n'.join(output)
#===============================================================================
class MessageDict(dict):
#===============================================================================
"""
Message dictionary provides message numbers as attributes or the messages
by looking up that message number in the underlying dictionary.
messages.MY_MESSAGE == <integer index>
messages[messages.MY_MESSAGE] == <string>
"""
def __init__(self, **kwargs):
dict.__init__(self)
i = 0
for key in kwargs:
i += 1
self[i] = kwargs[key]
setattr(self, key, i)
#===============================================================================
class CodeFormatter(object):
#===============================================================================
"""
Useful for formatting generated code. It is currently geared for DDL, but
this isn't etched in stone.
"""
def __init__(self, separator=',', vcomment_prefix='', indent_string=' '):
self.separator = separator
self.vcomment_prefix = vcomment_prefix
self.indent_string = indent_string
self.level = 0
self.lines = []
self.pending_separator = [-1]
self.block_start_index = [0]
def _line(self, needs_separator, *lines):
if needs_separator and self.separator and self.pending_separator[-1] >= 0:
self.lines[self.pending_separator[-1]] += self.separator
for line in lines:
self.lines.append('%s%s' % (self.indent_string * self.level, line))
if needs_separator:
self.pending_separator[-1] = len(self.lines) - 1
def _block_line(self, *lines):
if self.pending_separator[-1] >= self.block_start_index[-1]:
self.pending_separator[-1] += len(lines)
for line in lines:
self.lines.insert(self.block_start_index[-1], line)
self.block_start_index[-1] += 1
def block_start(self, *lines):
if self.level == 0:
self._line(False, '')
self.block_start_index.append(len(self.lines))
self._line(False, *lines)
self._line(False, '(')
self.level += 1
self.pending_separator.append(-1)
def block_end(self, *lines):
self.level -= 1
self.pending_separator.pop()
if self.level == 0:
self._line(False, ');')
else:
self._line(True, ')')
self.block_start_index.pop()
def code(self, *lines):
self._line(False, *lines)
def code_fragment(self, *lines):
self._line(True, *lines)
def comment(self, *lines):
for line in lines:
self._line(False, '-- %s' % line)
def vcomment(self, *lines):
for line in lines:
self._line(False, '--%s %s' % (self.vcomment_prefix, line))
def block_comment(self, *lines):
for line in lines:
self._block_line('-- %s' % line)
def block_vcomment(self, *lines):
for line in lines:
self._block_line('--%s %s' % (self.vcomment_prefix, line))
def blank(self, n=1):
for line in range(n):
self._line(False, '')
def __str__(self):
return '\n'.join(self.lines)
|
kumarrus/voltdb
|
lib/python/voltcli/utility.py
|
Python
|
agpl-3.0
| 55,521
|
"""Deprecated import support. Auto-generated by import_shims/generate_shims.sh."""
# pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-too-long
from import_shims.warn import warn_deprecated_import
warn_deprecated_import('terrain.stubs.tests.test_youtube_stub', 'common.djangoapps.terrain.stubs.tests.test_youtube_stub')
from common.djangoapps.terrain.stubs.tests.test_youtube_stub import *
|
eduNEXT/edunext-platform
|
import_shims/studio/terrain/stubs/tests/test_youtube_stub.py
|
Python
|
agpl-3.0
| 440
|
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Cradl(Package):
"""The CRADL proxy application captured performance metrics during
inference on data from multiphysics codes, specifically ALE
hydrodynamics codes."""
homepage = "https://github.com/LLNL/CRADL"
url = "https://github.com/LLNL/CRADL/archive/master.zip"
git = "https://github.com/LLNL/CRADL.git"
tags = ['proxy-app']
version('master', branch='master')
depends_on('py-pandas')
depends_on('py-torch')
depends_on('py-torchvision')
depends_on('py-apex')
depends_on('py-gputil')
depends_on('py-matplotlib')
depends_on('py-mpi4py')
def install(self, spec, prefix):
# Mostly about providing an environment so just copy everything
install_tree('.', prefix)
|
LLNL/spack
|
var/spack/repos/builtin/packages/cradl/package.py
|
Python
|
lgpl-2.1
| 984
|
# ***************************************************************************
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * FreeCAD is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with FreeCAD; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
"""Provides general functions to work with topological shapes."""
## @package general
# \ingroup draftgeoutils
# \brief Provides general functions to work with topological shapes.
import math
import lazy_loader.lazy_loader as lz
import FreeCAD as App
import DraftVecUtils
# Delay import of module until first use because it is heavy
Part = lz.LazyLoader("Part", globals(), "Part")
## \addtogroup draftgeoutils
# @{
PARAMGRP = App.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft")
# Default normal direction for all geometry operations
NORM = App.Vector(0, 0, 1)
def precision():
"""Return the Draft precision setting."""
# Set precision level with a cap to avoid overspecification that:
# 1 - whilst it is precise enough (e.g. that OCC would consider
# 2 points are coincident)
# (not sure what it should be 10 or otherwise);
# 2 - but FreeCAD/OCC can handle 'internally'
# (e.g. otherwise user may set something like
# 15 that the code would never consider 2 points are coincident
# as internal float is not that precise)
precisionMax = 10
precisionInt = PARAMGRP.GetInt("precision", 6)
precisionInt = (precisionInt if precisionInt <= 10 else precisionMax)
return precisionInt # return PARAMGRP.GetInt("precision", 6)
def vec(edge):
"""Return a vector from an edge or a Part.LineSegment."""
# if edge is not straight, you'll get strange results!
if isinstance(edge, Part.Shape):
return edge.Vertexes[-1].Point.sub(edge.Vertexes[0].Point)
elif isinstance(edge, Part.LineSegment):
return edge.EndPoint.sub(edge.StartPoint)
else:
return None
def edg(p1, p2):
"""Return an edge from 2 vectors."""
if isinstance(p1, App.Vector) and isinstance(p2, App.Vector):
if DraftVecUtils.equals(p1, p2):
return None
return Part.LineSegment(p1, p2).toShape()
def getVerts(shape):
"""Return a list containing vectors of each vertex of the shape."""
if not hasattr(shape, "Vertexes"):
return []
p = []
for v in shape.Vertexes:
p.append(v.Point)
return p
def v1(edge):
"""Return the first point of an edge."""
return edge.Vertexes[0].Point
def isNull(something):
"""Return True if the given shape, vector, or placement is Null.
If the vector is (0, 0, 0), it will return True.
"""
if isinstance(something, Part.Shape):
return something.isNull()
elif isinstance(something, App.Vector):
if something == App.Vector(0, 0, 0):
return True
else:
return False
elif isinstance(something, App.Placement):
if (something.Base == App.Vector(0, 0, 0)
and something.Rotation.Q == (0, 0, 0, 1)):
return True
else:
return False
def isPtOnEdge(pt, edge):
"""Test if a point lies on an edge."""
v = Part.Vertex(pt)
try:
d = v.distToShape(edge)
except Part.OCCError:
return False
else:
if d:
if round(d[0], precision()) == 0:
return True
return False
def hasCurves(shape):
"""Check if the given shape has curves."""
for e in shape.Edges:
if not isinstance(e.Curve, (Part.LineSegment, Part.Line)):
return True
return False
def isAligned(edge, axis="x"):
"""Check if the given edge or line is aligned to the given axis.
The axis can be 'x', 'y' or 'z'.
"""
if axis == "x":
if isinstance(edge, Part.Edge):
if len(edge.Vertexes) == 2:
if edge.Vertexes[0].X == edge.Vertexes[-1].X:
return True
elif isinstance(edge, Part.LineSegment):
if edge.StartPoint.x == edge.EndPoint.x:
return True
elif axis == "y":
if isinstance(edge, Part.Edge):
if len(edge.Vertexes) == 2:
if edge.Vertexes[0].Y == edge.Vertexes[-1].Y:
return True
elif isinstance(edge, Part.LineSegment):
if edge.StartPoint.y == edge.EndPoint.y:
return True
elif axis == "z":
if isinstance(edge, Part.Edge):
if len(edge.Vertexes) == 2:
if edge.Vertexes[0].Z == edge.Vertexes[-1].Z:
return True
elif isinstance(edge, Part.LineSegment):
if edge.StartPoint.z == edge.EndPoint.z:
return True
return False
def getQuad(face):
"""Return a list of 3 vectors if the face is a quad, ortherwise None.
Returns
-------
basepoint, Xdir, Ydir
If the face is a quad.
None
If the face is not a quad.
"""
if len(face.Edges) != 4:
return None
v1 = vec(face.Edges[0]) # Warning redefinition of function v1
v2 = vec(face.Edges[1])
v3 = vec(face.Edges[2])
v4 = vec(face.Edges[3])
angles90 = [round(math.pi*0.5, precision()),
round(math.pi*1.5, precision())]
angles180 = [0,
round(math.pi, precision()),
round(math.pi*2, precision())]
for ov in [v2, v3, v4]:
if not (round(v1.getAngle(ov), precision()) in angles90 + angles180):
return None
for ov in [v2, v3, v4]:
if round(v1.getAngle(ov), precision()) in angles90:
v1.normalize()
ov.normalize()
return [face.Edges[0].Vertexes[0].Point, v1, ov]
def areColinear(e1, e2):
"""Return True if both edges are colinear."""
if not isinstance(e1.Curve, (Part.LineSegment, Part.Line)):
return False
if not isinstance(e2.Curve, (Part.LineSegment, Part.Line)):
return False
v1 = vec(e1)
v2 = vec(e2)
a = round(v1.getAngle(v2), precision())
if (a == 0) or (a == round(math.pi, precision())):
v3 = e2.Vertexes[0].Point.sub(e1.Vertexes[0].Point)
if DraftVecUtils.isNull(v3):
return True
else:
a2 = round(v1.getAngle(v3), precision())
if (a2 == 0) or (a2 == round(math.pi, precision())):
return True
return False
def hasOnlyWires(shape):
"""Return True if all edges are inside a wire."""
ne = 0
for w in shape.Wires:
ne += len(w.Edges)
if ne == len(shape.Edges):
return True
return False
def geomType(edge):
"""Return the type of geometry this edge is based on."""
try:
if isinstance(edge.Curve, (Part.LineSegment, Part.Line)):
return "Line"
elif isinstance(edge.Curve, Part.Circle):
return "Circle"
elif isinstance(edge.Curve, Part.BSplineCurve):
return "BSplineCurve"
elif isinstance(edge.Curve, Part.BezierCurve):
return "BezierCurve"
elif isinstance(edge.Curve, Part.Ellipse):
return "Ellipse"
else:
return "Unknown"
except TypeError:
return "Unknown"
def isValidPath(shape):
"""Return True if the shape can be used as an extrusion path."""
if shape.isNull():
return False
if shape.Faces:
return False
if len(shape.Wires) > 1:
return False
if shape.Wires:
if shape.Wires[0].isClosed():
return False
if shape.isClosed():
return False
return True
def findClosest(base_point, point_list):
"""Find closest point in a list of points to the base point.
Returns
-------
int
An index from the list of points is returned.
None
If point_list is empty.
"""
npoint = None
if not point_list:
return None
smallest = 1000000
for n in range(len(point_list)):
new = base_point.sub(point_list[n]).Length
if new < smallest:
smallest = new
npoint = n
return npoint
def getBoundaryAngles(angle, alist):
"""Return the 2 closest angles that encompass the given angle."""
negs = True
while negs:
negs = False
for i in range(len(alist)):
if alist[i] < 0:
alist[i] = 2*math.pi + alist[i]
negs = True
if angle < 0:
angle = 2*math.pi + angle
negs = True
lower = None
for a in alist:
if a < angle:
if lower is None:
lower = a
else:
if a > lower:
lower = a
if lower is None:
lower = 0
for a in alist:
if a > lower:
lower = a
higher = None
for a in alist:
if a > angle:
if higher is None:
higher = a
else:
if a < higher:
higher = a
if higher is None:
higher = 2*math.pi
for a in alist:
if a < higher:
higher = a
return lower, higher
## @}
|
Fat-Zer/FreeCAD_sf_master
|
src/Mod/Draft/draftgeoutils/general.py
|
Python
|
lgpl-2.1
| 10,720
|
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for the binary ops priority mechanism."""
import numpy as np
from tensorflow.python.framework import ops
from tensorflow.python.platform import test as test_lib
class TensorPriorityTest(test_lib.TestCase):
def testSupportedRhsWithoutDelegation(self):
class NumpyArraySubclass(np.ndarray):
pass
supported_rhs_without_delegation = (3, 3.0, [1.0, 2.0], np.array(
[1.0, 2.0]), NumpyArraySubclass(
shape=(1, 2), buffer=np.array([1.0, 2.0])),
ops.convert_to_tensor([[1.0, 2.0]]))
for rhs in supported_rhs_without_delegation:
tensor = ops.convert_to_tensor([[10.0, 20.0]])
res = tensor + rhs
self.assertIsInstance(res, ops.Tensor)
def testUnsupportedRhsWithoutDelegation(self):
class WithoutReverseAdd(object):
pass
tensor = ops.convert_to_tensor([[10.0, 20.0]])
rhs = WithoutReverseAdd()
with self.assertRaisesWithPredicateMatch(
TypeError, lambda e: "Expected float" in str(e)):
# pylint: disable=pointless-statement
tensor + rhs
def testUnsupportedRhsWithDelegation(self):
class WithReverseAdd(object):
def __radd__(self, lhs):
return "Works!"
tensor = ops.convert_to_tensor([[10.0, 20.0]])
rhs = WithReverseAdd()
res = tensor + rhs
self.assertEqual(res, "Works!")
def testFullDelegationControlUsingRegistry(self):
class NumpyArraySubclass(np.ndarray):
def __radd__(self, lhs):
return "Works!"
def raise_to_delegate(value, dtype=None, name=None, as_ref=False):
del value, dtype, name, as_ref # Unused.
raise TypeError
ops.register_tensor_conversion_function(
NumpyArraySubclass, raise_to_delegate, priority=0)
tensor = ops.convert_to_tensor([[10.0, 20.0]])
rhs = NumpyArraySubclass(shape=(1, 2), buffer=np.array([1.0, 2.0]))
res = tensor + rhs
self.assertEqual(res, "Works!")
if __name__ == "__main__":
test_lib.main()
|
tensorflow/tensorflow
|
tensorflow/python/kernel_tests/tensor_priority_test.py
|
Python
|
apache-2.0
| 2,678
|
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implement base classes for hid package.
This module provides the base classes implemented by the
platform-specific modules. It includes a base class for
all implementations built on interacting with file-like objects.
"""
class HidDevice(object):
"""Base class for all HID devices in this package."""
@staticmethod
def Enumerate():
"""Enumerates all the hid devices.
This function enumerates all the hid device and provides metadata
for helping the client select one.
Returns:
A list of dictionaries of metadata. Each implementation is required
to provide at least: vendor_id, product_id, product_string, usage,
usage_page, and path.
"""
pass
def __init__(self, path):
"""Initialize the device at path."""
pass
def GetInReportDataLength(self):
"""Returns the max input report data length in bytes.
Returns the max input report data length in bytes. This excludes the
report id.
"""
pass
def GetOutReportDataLength(self):
"""Returns the max output report data length in bytes.
Returns the max output report data length in bytes. This excludes the
report id.
"""
pass
def Write(self, packet):
"""Writes packet to device.
Writes the packet to the device.
Args:
packet: An array of integers to write to the device. Excludes the report
ID. Must be equal to GetOutReportLength().
"""
pass
def Read(self):
"""Reads packet from device.
Reads the packet from the device.
Returns:
An array of integers read from the device. Excludes the report ID.
The length is equal to GetInReportDataLength().
"""
pass
class DeviceDescriptor(object):
"""Descriptor for basic attributes of the device."""
usage_page = None
usage = None
vendor_id = None
product_id = None
product_string = None
path = None
internal_max_in_report_len = None
internal_max_out_report_len = None
def ToPublicDict(self):
out = {}
for k, v in self.__dict__.items():
if not k.startswith('internal_'):
out[k] = v
return out
|
KaranToor/MA450
|
google-cloud-sdk/lib/third_party/pyu2f/hid/base.py
|
Python
|
apache-2.0
| 2,716
|
# -*- coding: ascii -*-
#
# Copyright 2006, 2007, 2008, 2009, 2010, 2011
# Andr\xe9 Malo or his licensors, as applicable
#
# 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.
"""
=================================
Support for code analysis tools
=================================
Support for code analysis tools.
"""
__author__ = u"Andr\xe9 Malo"
__docformat__ = "restructuredtext en"
def pylint(config, *args):
""" Run pylint """
from _setup.dev import _pylint
return _pylint.run(config, *args)
|
ndparker/setup-common
|
py2/dev/analysis.py
|
Python
|
apache-2.0
| 1,003
|
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for mfcc_ops."""
from absl.testing import parameterized
from tensorflow.python.eager import context
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops.signal import mfcc_ops
from tensorflow.python.platform import test
# TODO(rjryan): We have no open source tests for MFCCs at the moment. Internally
# at Google, this code is tested against a reference implementation that follows
# HTK conventions.
@test_util.run_all_in_graph_and_eager_modes
class MFCCTest(test.TestCase, parameterized.TestCase):
def test_error(self):
# num_mel_bins must be positive.
with self.assertRaises(ValueError):
signal = array_ops.zeros((2, 3, 0))
mfcc_ops.mfccs_from_log_mel_spectrograms(signal)
@parameterized.parameters(dtypes.float32, dtypes.float64)
def test_basic(self, dtype):
"""A basic test that the op runs on random input."""
signal = random_ops.random_normal((2, 3, 5), dtype=dtype)
self.evaluate(mfcc_ops.mfccs_from_log_mel_spectrograms(signal))
def test_unknown_shape(self):
"""A test that the op runs when shape and rank are unknown."""
if context.executing_eagerly():
return
signal = array_ops.placeholder_with_default(
random_ops.random_normal((2, 3, 5)), tensor_shape.TensorShape(None))
self.assertIsNone(signal.shape.ndims)
self.evaluate(mfcc_ops.mfccs_from_log_mel_spectrograms(signal))
if __name__ == "__main__":
test.main()
|
tensorflow/tensorflow
|
tensorflow/python/kernel_tests/signal/mfcc_ops_test.py
|
Python
|
apache-2.0
| 2,320
|
from write import write, writebr
import sys
IN_BROWSER = sys.platform in ['mozilla', 'ie6', 'opera', 'oldmoz', 'safari']
IN_JS = sys.platform in ['mozilla', 'ie6', 'opera', 'oldmoz',
'safari', 'spidermonkey', 'pyv8']
if IN_BROWSER:
from pyjamas.Timer import Timer
class UnitTest:
def __init__(self):
self.tests_completed=0
self.tests_failed=0
self.tests_passed=0
self.test_methods=[]
self.test_idx = None
# Synonyms for assertion methods
self.assertEqual = self.assertEquals = self.failUnlessEqual
self.assertNotEqual = self.assertNotEquals = self.failIfEqual
self.assertAlmostEqual = self.assertAlmostEquals = self.failUnlessAlmostEqual
self.assertNotAlmostEqual = self.assertNotAlmostEquals = self.failIfAlmostEqual
self.assertRaises = self.failUnlessRaises
self.assert_ = self.assertTrue = self.failUnless
self.assertFalse = self.failIf
def _run_test(self, test_method_name):
self.getTestMethods()
test_method=getattr(self, test_method_name)
self.current_test_name = test_method_name
self.setUp()
try:
try:
test_method()
except Exception,e:
self.fail("uncaught exception:" + str(e))
except:
self.fail("uncaught javascript exception")
self.tearDown()
self.current_test_name = None
def run(self):
self.getTestMethods()
if not IN_BROWSER:
for test_method_name in self.test_methods:
self._run_test(test_method_name)
self.displayStats()
if hasattr(self, "start_next_test"):
self.start_next_test()
return
self.test_idx = 0
Timer(10, self)
def onTimer(self, timer):
for i in range(1):
if self.test_idx >= len(self.test_methods):
self.displayStats()
self.test_idx = 'DONE'
self.start_next_test()
return
self._run_test(self.test_methods[self.test_idx])
self.test_idx += 1
timer.schedule(10)
def setUp(self):
pass
def tearDown(self):
pass
def getName(self):
return self.__class__.__name__
def getNameFmt(self, msg=""):
if self.getName():
if msg:
msg=" " + str(msg)
if self.current_test_name:
msg += " (%s) " % self.getCurrentTestID()
return self.getName() + msg + ": "
return ""
def getCurrentTestID(self):
return "%s/%i" % (self.current_test_name,self.tests_completed)
def getTestMethods(self):
self.test_methods=[]
for m in dir(self):
if self.isTestMethod(m):
self.test_methods.append(m)
def isTestMethod(self, method):
if callable(getattr(self, method)):
if method.find("test") == 0:
return True
return False
def fail(self, msg=None):
self.startTest()
self.tests_failed+=1
if not msg:
msg="assertion failed"
else:
msg = str(msg)
octothorp = msg.find("#")
has_bugreport = octothorp >= 0 and msg[octothorp+1].isdigit()
if has_bugreport:
name_fmt = "Known issue"
bg_colour="#ffc000"
fg_colour="#000000"
else:
bg_colour="#ff8080"
fg_colour="#000000"
name_fmt = "Test failed"
output="<table style='padding-left:20px;padding-right:20px;' cellpadding=2 width=100%><tr><td bgcolor='" + bg_colour + "'><font color='" + fg_colour + "'>"
write(output)
title="<b>" + self.getNameFmt(name_fmt) + "</b>"
write(title + msg)
output="</font></td></tr></table>"
output+= "\n"
write(output)
if sys.platform in ['mozilla', 'ie6', 'opera', 'oldmoz', 'safari']:
from __pyjamas__ import JS
JS("""if (typeof @{{!console}} != 'undefined') {
if (typeof @{{!console}}['error'] == 'function') @{{!console}}['error'](@{{msg}});
if (typeof @{{!console}}['trace'] == 'function') @{{!console}}['trace']();
}""")
return False
def startTest(self):
self.tests_completed+=1
def failIf(self, expr, msg=None):
self.startTest()
if expr:
return self.fail(msg)
def failUnless(self, expr, msg=None):
self.startTest()
if not expr:
return self.fail(msg)
def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
try:
callableObj(*args, **kwargs)
except excClass:
return
else:
if hasattr(excClass,'__name__'): excName = excClass.__name__
else: excName = str(excClass)
#raise self.failureException, "%s not raised" % excName
self.fail("%s not raised" % excName)
def failUnlessEqual(self, first, second, msg=None):
self.startTest()
if not first == second:
if not msg:
msg=repr(first) + " != " + repr(second)
return self.fail(msg)
def failIfEqual(self, first, second, msg=None):
self.startTest()
if first == second:
if not msg:
msg=repr(first) + " == " + repr(second)
return self.fail(msg)
def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
self.startTest()
if round(second-first, places) != 0:
if not msg:
msg=repr(first) + " != " + repr(second) + " within " + repr(places) + " places"
return self.fail(msg)
def failIfAlmostEqual(self, first, second, places=7, msg=None):
self.startTest()
if round(second-first, places) is 0:
if not msg:
msg=repr(first) + " == " + repr(second) + " within " + repr(places) + " places"
return self.fail(msg)
# based on the Python standard library
def assertRaises(self, excClass, callableObj, *args, **kwargs):
"""
Fail unless an exception of class excClass is thrown
by callableObj when invoked with arguments args and keyword
arguments kwargs. If a different type of exception is
thrown, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.
"""
self.startTest()
try:
callableObj(*args, **kwargs)
except excClass, exc:
return
else:
if hasattr(excClass, '__name__'):
excName = excClass.__name__
else:
excName = str(excClass)
self.fail("%s not raised" % excName)
def displayStats(self):
if self.tests_failed:
bg_colour="#ff0000"
fg_colour="#ffffff"
else:
bg_colour="#00ff00"
fg_colour="#000000"
tests_passed=self.tests_completed - self.tests_failed
if sys.platform in ['mozilla', 'ie6', 'opera', 'oldmoz', 'safari']:
output="<table cellpadding=4 width=100%><tr><td bgcolor='" + bg_colour + "'><font face='arial' size=4 color='" + fg_colour + "'><b>"
else:
output = ""
output+=self.getNameFmt() + "Passed %d " % tests_passed + "/ %d" % self.tests_completed + " tests"
if self.tests_failed:
output+=" (%d failed)" % self.tests_failed
if sys.platform in ['mozilla', 'ie6', 'opera', 'oldmoz', 'safari']:
output+="</b></font></td></tr></table>"
else:
output+= "\n"
write(output)
|
spaceone/pyjs
|
pyjs/lib/test/UnitTest.py
|
Python
|
apache-2.0
| 7,837
|
"""
(c) 2011, 2012 Georgia Tech Research Corporation
This source code is released under the New BSD license. Please see
http://wiki.quantsoftware.org/index.php?title=QSTK_License
for license details.
A simple wrapper for scipy.spatial.kdtree.KDTree for doing KNN
"""
import math,random,sys,bisect,time
import numpy,scipy.spatial.distance
from scipy.spatial import cKDTree
import cProfile,pstats,gendata
import numpy as np
class kdtknn(object):
"""
A simple wrapper of scipy.spatial.kdtree.KDTree
Since the scipy KDTree implementation does not allow for incrementally adding
data points, the entire KD-tree is rebuilt on the first call to 'query' after a
call to 'addEvidence'. For this reason it is more efficient to add training data
in batches.
"""
def __init__(self,k=3,method='mean',leafsize=10):
"""
Basic setup.
"""
self.leafsize = leafsize
self.data = None
self.kdt = None
self.rebuild_tree = True
self.k = k
self.method = method
def addEvidence(self,dataX,dataY=None):
"""
@summary: Add training data
@param dataX: Data to add, either entire set with classification as last column, or not if
the Y data is provided explicitly. Must be same width as previously appended data.
@param dataY: Optional, can be used
'data' should be a numpy array matching the same dimensions as any data
provided in previous calls to addEvidence, with dataY as the
training label.
"""
''' Slap on Y column if it is provided, if not assume it is there '''
if not dataY == None:
data = numpy.zeros([dataX.shape[0],dataX.shape[1]+1])
data[:,0:dataX.shape[1]]=dataX
data[:,(dataX.shape[1])]=dataY
else:
data = dataX
self.rebuild_tree = True
if self.data is None:
self.data = data
else:
self.data = numpy.append(self.data,data,axis=0)
def rebuildKDT(self):
"""
Force the internal KDTree to be rebuilt.
"""
self.kdt = cKDTree(self.data[:,:-1],leafsize=self.leafsize)
self.rebuild_tree = False
def query(self,points,k=None,method=None):
"""
Classify a set of test points given their k nearest neighbors.
'points' should be a numpy array with each row corresponding to a specific query.
Returns the estimated class according to supplied method (currently only 'mode'
and 'mean' are supported)
"""
if k is None:
k = self.k
if method is None:
method = self.method
if self.rebuild_tree is True:
if self.data is None:
return None
self.rebuildKDT()
#kdt.query returns a list of distances and a list of indexes into the
#data array
if k == 1:
tmp = self.kdt.query(points,k)
#in the case of k==1, numpy fudges an array of 1 dimension into
#a scalar, so we handle it seperately. tmp[1] is the list of
#indecies, tmp[1][0] is the first one (we only need one),
#self.data[tmp[1][0]] is the data point corresponding to the
#first neighbor, and self.data[tmp[1][0]][-1] is the last column
#which is the class of the neighbor.
return self.data[tmp[1][0]][-1]
#for all the neighbors returned by kdt.query, get their class and stick that into a list
na_dist, na_neighbors = self.kdt.query(points,k)
n_clsses = map(lambda rslt: map(lambda p: p[-1], self.data[rslt]), na_neighbors)
#print n_clsses
if method=='mode':
return map(lambda x: scipy.stats.stats.mode(x)[0],n_clsses)[0]
elif method=='mean':
return numpy.array(map(lambda x: numpy.mean(x),n_clsses))
elif method=='median':
return numpy.array(map(lambda x: numpy.median(x),n_clsses))
elif method=='raw':
return numpy.array(n_clsses)
elif method=='all':
return numpy.array(n_clsses), na_dist
def getflatcsv(fname):
inf = open(fname)
return numpy.array([map(float,s.strip().split(',')) for s in inf.readlines()])
def testgendata():
fname = 'test2.dat'
querys = 1000
d = 2
k=3
bnds = ((-10,10),)*d
clsses = (0,1)
data = getflatcsv(fname)
kdt = kdtknn(k,method='mode')
kdt.addEvidence(data)
kdt.rebuildKDT()
stime = time.time()
for x in xrange(querys):
pnt = numpy.array(gendata.gensingle(d,bnds,clsses))
reslt = kdt.query(numpy.array([pnt[:-1]]))
print pnt,"->",reslt
etime = time.time()
print etime-stime,'/',querys,'=',(etime-stime)/float(querys),'avg wallclock time per query'
#foo.addEvidence(data[:,:-1],data[:,-1])
#foo.num_checks = 0
#for x in xrange(querys):
# pnt = numpy.array(gendata.gensingle(d,bnds,clsses))
# foo.query(pnt[:-1],3)
# if x % 50 == 0:
# print float(foo.num_checks)/float(x+1),
# print x,"/",querys
#print "Average # queries:", float(foo.num_checks)/float(querys)
def test():
testgendata()
if __name__=="__main__":
test()
#prof= cProfile.Profile()
#prof.run('test()')
#stats = pstats.Stats(prof)
#stats.sort_stats("cumulative").print_stats()
|
grahesh/Stock-Market-Event-Analysis
|
qstklearn/kdtknn.py
|
Python
|
bsd-3-clause
| 5,490
|
# -*- coding: utf-8 -*-
"""
profiling.stats
~~~~~~~~~~~~~~~
Stat classes.
"""
from __future__ import absolute_import, division
from collections import defaultdict
import inspect
import time
from six import itervalues
from six.moves import map
from .sortkeys import by_total_time
__all__ = ['Stat', 'Statistics', 'RecordingStat', 'RecordingStatistics',
'VoidRecordingStat', 'FrozenStat', 'FrozenStatistics', 'FlatStat',
'FlatStatistics']
def failure(funcname, message='{class} not allow {func}.', exctype=TypeError):
"""Generates a method which raises an exception."""
def func(self, *args, **kwargs):
fmtopts = {'func': funcname, 'obj': self, 'class': type(self).__name__}
raise exctype(message.format(**fmtopts))
func.__name__ = funcname
return func
class Stat(object):
"""Stat."""
_state_slots = ['name', 'filename', 'lineno', 'module',
'calls', 'total_time']
name = None
filename = None
lineno = None
module = None
calls = 0
total_time = 0.0
def __init__(self, stat=None, name=None, filename=None, lineno=None,
module=None):
if stat is not None:
assert name is filename is lineno is module is None
name = stat.name
filename = stat.filename
lineno = stat.lineno
module = stat.module
if name is not None:
self.name = name
if filename is not None:
self.filename = filename
if lineno is not None:
self.lineno = lineno
if module is not None:
self.module = module
def __hash__(self):
return hash((self.name, self.filename, self.lineno))
@property
def regular_name(self):
name, module = self.name, self.module
if name and module:
return ':'.join([module, name])
return name or module
@property
def own_time(self):
sub_time = sum(stat.total_time for stat in self)
return max(0., self.total_time - sub_time)
@property
def total_time_per_call(self):
try:
return self.total_time / self.calls
except ZeroDivisionError:
return 0.0
@property
def own_time_per_call(self):
try:
return self.own_time / self.calls
except ZeroDivisionError:
return 0.0
def sorted(self, order=by_total_time):
return sorted(self, key=order)
def __iter__(self):
"""Override it to walk child stats."""
return iter(())
def __len__(self):
"""Override it to count child stats."""
return 0
def __getstate__(self):
return tuple(getattr(self, attr) for attr in self._state_slots)
def __setstate__(self, state):
for attr, val in zip(self._state_slots, state):
setattr(self, attr, val)
def __repr__(self):
class_name = type(self).__name__
regular_name = self.regular_name
name_string = '' if regular_name else "'{0}'".format(regular_name)
fmt = '<{0} {1}calls={2} total_time={3:.6f} own_time={4:.6f}>'
return fmt.format(class_name, name_string, self.calls,
self.total_time, self.own_time)
class Statistics(Stat):
"""Thr root statistic of the statistics tree."""
_state_slots = ['cpu_time', 'wall_time']
cpu_time = 0.0
wall_time = 0.0
name = None
filename = None
lineno = None
module = None
@property
def cpu_usage(self):
try:
return self.cpu_time / self.wall_time
except ZeroDivisionError:
return 0.0
@property
def total_time(self):
return self.wall_time
@property
def own_time(self):
return self.cpu_time
def clear(self):
self.children.clear()
cls = type(self)
self.calls = cls.calls
self.cpu_time = cls.cpu_time
self.wall_time = cls.wall_time
try:
del self._cpu_time_started
except AttributeError:
pass
try:
del self._wall_time_started
except AttributeError:
pass
def __repr__(self):
class_name = type(self).__name__
return '<{0} cpu_usage={1:.2%}>'.format(class_name, self.cpu_usage)
class RecordingStat(Stat):
"""Recordig statistic measures execution time of a code."""
_state_slots = None
def __init__(self, code=None):
super(RecordingStat, self).__init__()
self.code = code
self.children = {}
self._times_entered = {}
@property
def name(self):
if self.code is None:
return
name = self.code.co_name
if name == '<module>':
return
return name
@property
def filename(self):
return self.code and self.code.co_filename
@property
def lineno(self):
return self.code and self.code.co_firstlineno
@property
def module(self):
if self.code is None:
return
module = inspect.getmodule(self.code)
if not module:
return
return module.__name__
def record_entering(self, time, frame_key=None):
self._times_entered[frame_key] = time
self.calls += 1
def record_leaving(self, time, frame_key=None):
time_entered = self._times_entered.pop(frame_key)
time_elapsed = time - time_entered
self.total_time += max(0, time_elapsed)
def clear(self):
self.code = None
self.children.clear()
cls = type(self)
self.calls = cls.calls
self.total_time = cls.total_time
self._times_entered.clear()
def get_child(self, code):
return self.children[code]
def add_child(self, code, stat):
self.children[code] = stat
def remove_child(self, code):
del self.children[code]
def ensure_child(self, code):
try:
return self.get_child(code)
except KeyError:
stat = VoidRecordingStat(code)
self.add_child(code, stat)
return stat
def __iter__(self):
return itervalues(self.children)
def __len__(self):
return len(self.children)
def __contains__(self, code):
return code in self.children
def __getstate__(self):
raise TypeError('Cannot dump recording statistic.')
class RecordingStatistics(RecordingStat, Statistics):
"""Thr root statistic of the recording statistics tree."""
_state_slots = None
wall = time.time
record_entering = failure('record_entering')
record_leaving = failure('record_leaving')
def record_starting(self, time):
self._cpu_time_started = time
self._wall_time_started = self.wall()
def record_stopping(self, time):
try:
self.cpu_time = max(0, time - self._cpu_time_started)
self.wall_time = max(0, self.wall() - self._wall_time_started)
except AttributeError:
raise RuntimeError('Starting does not recorded.')
self.calls = 1
del self._cpu_time_started
del self._wall_time_started
class VoidRecordingStat(RecordingStat):
"""Stat for an absent frame."""
_state_slots = None
clear = failure('clear')
@property
def total_time(self):
return sum(stat.total_time for stat in self)
def record_entering(self, time, frame=None):
pass
def record_leaving(self, time, frame=None):
pass
class FrozenStat(Stat):
"""Frozen :class:`Stat` to serialize by Pickle."""
_state_slots = ['name', 'filename', 'lineno', 'module',
'calls', 'total_time', 'children']
def __init__(self, stat):
super(FrozenStat, self).__init__(stat)
self.calls = stat.calls
self.total_time = stat.total_time
self.children = list(map(type(self), stat))
def __iter__(self):
return iter(self.children)
def __len__(self):
return len(self.children)
class FrozenStatistics(FrozenStat, Statistics):
"""Frozen :class:`Statistics` to serialize by Pickle."""
_state_slots = ['cpu_time', 'wall_time', 'children']
def __init__(self, stats):
Stat.__init__(self)
self.cpu_time = stats.cpu_time
self.wall_time = stats.wall_time
self.children = list(map(FrozenStat, stats))
class FlatStat(Stat):
_state_slots = ['name', 'filename', 'lineno', 'module',
'calls', 'total_time', 'own_time']
own_time = 0.0
class FlatStatistics(Statistics):
_state_slots = ['cpu_time', 'wall_time', 'children']
@classmethod
def _flatten_stats(cls, stats, registry=None):
if registry is None:
registry = {}
defaultdict(FlatStat)
for stat in stats:
try:
flatten_stat = registry[stat.regular_name]
except KeyError:
flatten_stat = FlatStat(stat)
registry[stat.regular_name] = flatten_stat
for attr in ['calls', 'total_time', 'own_time']:
value = getattr(flatten_stat, attr) + getattr(stat, attr)
setattr(flatten_stat, attr, value)
cls._flatten_stats(stat, registry=registry)
return registry.values()
def __init__(self, stats):
Stat.__init__(self)
self.cpu_time = stats.cpu_time
self.wall_time = stats.wall_time
self.children = type(self)._flatten_stats(stats)
def __iter__(self):
return iter(self.children)
def __len__(self):
return len(self.children)
|
tuxos/profiling
|
profiling/stats.py
|
Python
|
bsd-3-clause
| 9,694
|
# -*- coding: utf-8 -*-
import os
from whoosh import highlight, analysis, qparser
from whoosh.support.charset import accent_map
from flask import Markup
from flask_website import app
from werkzeug import import_string
def open_index():
from whoosh import index, fields as f
if os.path.isdir(app.config['WHOOSH_INDEX']):
return index.open_dir(app.config['WHOOSH_INDEX'])
os.mkdir(app.config['WHOOSH_INDEX'])
analyzer = analysis.StemmingAnalyzer() | analysis.CharsetFilter(accent_map)
schema = f.Schema(
url=f.ID(stored=True, unique=True),
id=f.ID(stored=True),
title=f.TEXT(stored=True, field_boost=2.0, analyzer=analyzer),
type=f.ID(stored=True),
keywords=f.KEYWORD(commas=True),
content=f.TEXT(analyzer=analyzer)
)
return index.create_in(app.config['WHOOSH_INDEX'], schema)
index = open_index()
class Indexable(object):
search_document_kind = None
def add_to_search_index(self, writer):
writer.add_document(url=unicode(self.url),
type=self.search_document_type,
**self.get_search_document())
@classmethod
def describe_search_result(cls, result):
return None
@property
def search_document_type(self):
cls = type(self)
return cls.__module__ + u'.' + cls.__name__
def get_search_document(self):
raise NotImplementedError()
def remove_from_search_index(self, writer):
writer.delete_by_term('url', unicode(self.url))
def highlight_all(result, field):
text = result[field]
return Markup(highlight.Highlighter(
fragmenter=highlight.WholeFragmenter(),
formatter=result.results.highlighter.formatter)
.highlight_hit(result, field, text=text)) or text
class SearchResult(object):
def __init__(self, result):
self.url = result['url']
self.title_text = result['title']
self.title = highlight_all(result, 'title')
cls = import_string(result['type'])
self.kind = cls.search_document_kind
self.description = cls.describe_search_result(result)
class SearchResultPage(object):
def __init__(self, results, page):
self.page = page
if results is None:
self.results = []
self.pages = 1
self.total = 0
else:
self.results = [SearchResult(r) for r in results]
self.pages = results.pagecount
self.total = results.total
def __iter__(self):
return iter(self.results)
def search(query, page=1, per_page=20):
with index.searcher() as s:
qp = qparser.MultifieldParser(['title', 'content'], index.schema)
q = qp.parse(unicode(query))
try:
result_page = s.search_page(q, page, pagelen=per_page)
except ValueError:
if page == 1:
return SearchResultPage(None, page)
return None
results = result_page.results
results.highlighter.fragmenter.maxchars = 512
results.highlighter.fragmenter.surround = 40
results.highlighter.formatter = highlight.HtmlFormatter('em',
classname='search-match', termclass='search-term',
between=u'<span class=ellipsis> … </span>')
return SearchResultPage(result_page, page)
def update_model_based_indexes(session, flush_context):
"""Called by a session event, updates the model based documents."""
to_delete = []
to_add = []
for model in session.new:
if isinstance(model, Indexable):
to_add.append(model)
for model in session.dirty:
if isinstance(model, Indexable):
to_delete.append(model)
to_add.append(model)
for model in session.dirty:
if isinstance(model, Indexable):
to_delete.append(model)
if not (to_delete or to_add):
return
writer = index.writer()
for model in to_delete:
model.remove_from_search_index(writer)
for model in to_add:
model.add_to_search_index(writer)
writer.commit()
def update_documentation_index():
from flask_website.docs import DocumentationPage
writer = index.writer()
for page in DocumentationPage.iter_pages():
page.remove_from_search_index(writer)
page.add_to_search_index(writer)
writer.commit()
def reindex_snippets():
from flask_website.database import Snippet
writer = index.writer()
for snippet in Snippet.query.all():
snippet.remove_from_search_index(writer)
snippet.add_to_search_index(writer)
writer.commit()
|
mitsuhiko/flask-website
|
flask_website/search.py
|
Python
|
bsd-3-clause
| 4,651
|
#
#[The "BSD license"]
# Copyright (c) 2013 Terence Parr
# Copyright (c) 2013 Sam Harwell
# Copyright (c) 2014 Eric Vergnaud
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. The name of the author may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
from enum import IntEnum
# need forward declaration
Lexer = None
class LexerActionType(IntEnum):
CHANNEL = 0 #The type of a {@link LexerChannelAction} action.
CUSTOM = 1 #The type of a {@link LexerCustomAction} action.
MODE = 2 #The type of a {@link LexerModeAction} action.
MORE = 3 #The type of a {@link LexerMoreAction} action.
POP_MODE = 4 #The type of a {@link LexerPopModeAction} action.
PUSH_MODE = 5 #The type of a {@link LexerPushModeAction} action.
SKIP = 6 #The type of a {@link LexerSkipAction} action.
TYPE = 7 #The type of a {@link LexerTypeAction} action.
class LexerAction(object):
def __init__(self, action:LexerActionType):
self.actionType = action
self.isPositionDependent = False
def __hash__(self):
return hash(str(self.actionType))
def __eq__(self, other):
return self is other
#
# Implements the {@code skip} lexer action by calling {@link Lexer#skip}.
#
# <p>The {@code skip} command does not have any parameters, so this action is
# implemented as a singleton instance exposed by {@link #INSTANCE}.</p>
class LexerSkipAction(LexerAction ):
# Provides a singleton instance of this parameterless lexer action.
INSTANCE = None
def __init__(self):
super().__init__(LexerActionType.SKIP)
def execute(self, lexer:Lexer):
lexer.skip()
def __str__(self):
return "skip"
LexerSkipAction.INSTANCE = LexerSkipAction()
# Implements the {@code type} lexer action by calling {@link Lexer#setType}
# with the assigned type.
class LexerTypeAction(LexerAction):
def __init__(self, type:int):
super().__init__(LexerActionType.TYPE)
self.type = type
def execute(self, lexer:Lexer):
lexer.type = self.type
def __hash__(self):
return hash(str(self.actionType) + str(self.type))
def __eq__(self, other):
if self is other:
return True
elif not isinstance(other, LexerTypeAction):
return False
else:
return self.type == other.type
def __str__(self):
return "type(" + str(self.type) + ")"
# Implements the {@code pushMode} lexer action by calling
# {@link Lexer#pushMode} with the assigned mode.
class LexerPushModeAction(LexerAction):
def __init__(self, mode:int):
super().__init__(LexerActionType.PUSH_MODE)
self.mode = mode
# <p>This action is implemented by calling {@link Lexer#pushMode} with the
# value provided by {@link #getMode}.</p>
def execute(self, lexer:Lexer):
lexer.pushMode(self.mode)
def __hash__(self):
return hash(str(self.actionType) + str(self.mode))
def __eq__(self, other):
if self is other:
return True
elif not isinstance(other, LexerPushModeAction):
return False
else:
return self.mode == other.mode
def __str__(self):
return "pushMode(" + str(self.mode) + ")"
# Implements the {@code popMode} lexer action by calling {@link Lexer#popMode}.
#
# <p>The {@code popMode} command does not have any parameters, so this action is
# implemented as a singleton instance exposed by {@link #INSTANCE}.</p>
class LexerPopModeAction(LexerAction):
INSTANCE = None
def __init__(self):
super().__init__(LexerActionType.POP_MODE)
# <p>This action is implemented by calling {@link Lexer#popMode}.</p>
def execute(self, lexer:Lexer):
lexer.popMode()
def __str__(self):
return "popMode"
LexerPopModeAction.INSTANCE = LexerPopModeAction()
# Implements the {@code more} lexer action by calling {@link Lexer#more}.
#
# <p>The {@code more} command does not have any parameters, so this action is
# implemented as a singleton instance exposed by {@link #INSTANCE}.</p>
class LexerMoreAction(LexerAction):
INSTANCE = None
def __init__(self):
super().__init__(LexerActionType.MORE)
# <p>This action is implemented by calling {@link Lexer#popMode}.</p>
def execute(self, lexer:Lexer):
lexer.more()
def __str__(self):
return "more"
LexerMoreAction.INSTANCE = LexerMoreAction()
# Implements the {@code mode} lexer action by calling {@link Lexer#mode} with
# the assigned mode.
class LexerModeAction(LexerAction):
def __init__(self, mode:int):
super().__init__(LexerActionType.MODE)
self.mode = mode
# <p>This action is implemented by calling {@link Lexer#mode} with the
# value provided by {@link #getMode}.</p>
def execute(self, lexer:Lexer):
lexer.mode(self.mode)
def __hash__(self):
return hash(str(self.actionType) + str(self.mode))
def __eq__(self, other):
if self is other:
return True
elif not isinstance(other, LexerModeAction):
return False
else:
return self.mode == other.mode
def __str__(self):
return "mode(" + str(self.mode) + ")"
# Executes a custom lexer action by calling {@link Recognizer#action} with the
# rule and action indexes assigned to the custom action. The implementation of
# a custom action is added to the generated code for the lexer in an override
# of {@link Recognizer#action} when the grammar is compiled.
#
# <p>This class may represent embedded actions created with the <code>{...}</code>
# syntax in ANTLR 4, as well as actions created for lexer commands where the
# command argument could not be evaluated when the grammar was compiled.</p>
class LexerCustomAction(LexerAction):
# Constructs a custom lexer action with the specified rule and action
# indexes.
#
# @param ruleIndex The rule index to use for calls to
# {@link Recognizer#action}.
# @param actionIndex The action index to use for calls to
# {@link Recognizer#action}.
#/
def __init__(self, ruleIndex:int, actionIndex:int):
super().__init__(LexerActionType.CUSTOM)
self.ruleIndex = ruleIndex
self.actionIndex = actionIndex
self.isPositionDependent = True
# <p>Custom actions are implemented by calling {@link Lexer#action} with the
# appropriate rule and action indexes.</p>
def execute(self, lexer:Lexer):
lexer.action(None, self.ruleIndex, self.actionIndex)
def __hash__(self):
return hash(str(self.actionType) + str(self.ruleIndex) + str(self.actionIndex))
def __eq__(self, other):
if self is other:
return True
elif not isinstance(other, LexerCustomAction):
return False
else:
return self.ruleIndex == other.ruleIndex and self.actionIndex == other.actionIndex
# Implements the {@code channel} lexer action by calling
# {@link Lexer#setChannel} with the assigned channel.
class LexerChannelAction(LexerAction):
# Constructs a new {@code channel} action with the specified channel value.
# @param channel The channel value to pass to {@link Lexer#setChannel}.
def __init__(self, channel:int):
super().__init__(LexerActionType.CHANNEL)
self.channel = channel
# <p>This action is implemented by calling {@link Lexer#setChannel} with the
# value provided by {@link #getChannel}.</p>
def execute(self, lexer:Lexer):
lexer._channel = self.channel
def __hash__(self):
return hash(str(self.actionType) + str(self.channel))
def __eq__(self, other):
if self is other:
return True
elif not isinstance(other, LexerChannelAction):
return False
else:
return self.channel == other.channel
def __str__(self):
return "channel(" + str(self.channel) + ")"
# This implementation of {@link LexerAction} is used for tracking input offsets
# for position-dependent actions within a {@link LexerActionExecutor}.
#
# <p>This action is not serialized as part of the ATN, and is only required for
# position-dependent lexer actions which appear at a location other than the
# end of a rule. For more information about DFA optimizations employed for
# lexer actions, see {@link LexerActionExecutor#append} and
# {@link LexerActionExecutor#fixOffsetBeforeMatch}.</p>
class LexerIndexedCustomAction(LexerAction):
# Constructs a new indexed custom action by associating a character offset
# with a {@link LexerAction}.
#
# <p>Note: This class is only required for lexer actions for which
# {@link LexerAction#isPositionDependent} returns {@code true}.</p>
#
# @param offset The offset into the input {@link CharStream}, relative to
# the token start index, at which the specified lexer action should be
# executed.
# @param action The lexer action to execute at a particular offset in the
# input {@link CharStream}.
def __init__(self, offset:int, action:LexerAction):
super().__init__(action.actionType)
self.offset = offset
self.action = action
self.isPositionDependent = True
# <p>This method calls {@link #execute} on the result of {@link #getAction}
# using the provided {@code lexer}.</p>
def execute(self, lexer:Lexer):
# assume the input stream position was properly set by the calling code
self.action.execute(lexer)
def __hash__(self):
return hash(str(self.actionType) + str(self.offset) + str(self.action))
def __eq__(self, other):
if self is other:
return True
elif not isinstance(other, LexerIndexedCustomAction):
return False
else:
return self.offset == other.offset and self.action == other.action
|
cocosli/antlr4
|
runtime/Python3/src/antlr4/atn/LexerAction.py
|
Python
|
bsd-3-clause
| 11,221
|
import collections
import numpy
import six
import cupy
from cupy import cuda
from cupy.cuda import cublas
from cupy import elementwise
from cupy import internal
def dot(a, b, out=None):
"""Returns a dot product of two arrays.
For arrays with more than one axis, it computes the dot product along the
last axis of ``a`` and the second-to-last axis of ``b``. This is just a
matrix product if the both arrays are 2-D. For 1-D arrays, it uses their
unique axis as an axis to take dot product over.
Args:
a (cupy.ndarray): The left argument.
b (cupy.ndarray): The right argument.
out (cupy.ndarray): Output array.
Returns:
cupy.ndarray: The dot product of ``a`` and ``b``.
.. seealso:: :func:`numpy.dot`
"""
a_ndim = a.ndim
b_ndim = b.ndim
assert a_ndim > 0 and b_ndim > 0
a_is_vec = a_ndim == 1
b_is_vec = b_ndim == 1
if a_is_vec:
a = cupy.reshape(a, (1, a.size))
a_ndim = 2
if b_is_vec:
b = cupy.reshape(b, (b.size, 1))
b_ndim = 2
a_axis = a_ndim - 1
b_axis = b_ndim - 2
if a.shape[a_axis] != b.shape[b_axis]:
raise ValueError('Axis dimension mismatch')
if a_axis:
a = cupy.rollaxis(a, a_axis, 0)
if b_axis:
b = cupy.rollaxis(b, b_axis, 0)
k = a.shape[0]
m = b.size // k
n = a.size // k
ret_shape = a.shape[1:] + b.shape[1:]
if out is None:
if a_is_vec:
ret_shape = () if b_is_vec else ret_shape[1:]
elif b_is_vec:
ret_shape = ret_shape[:-1]
else:
if out.size != n * m:
raise ValueError('Output array has an invalid size')
if not out.flags.c_contiguous:
raise ValueError('Output array must be C-contiguous')
return _tensordot_core(a, b, out, n, m, k, ret_shape)
def vdot(a, b):
"""Returns the dot product of two vectors.
The input arrays are flattened into 1-D vectors and then it performs inner
product of these vectors.
Args:
a (cupy.ndarray): The first argument.
b (cupy.ndarray): The second argument.
Returns:
cupy.ndarray: Zero-dimensional array of the dot product result.
.. seealso:: :func:`numpy.vdot`
"""
if a.size != b.size:
raise ValueError('Axis dimension mismatch')
return _tensordot_core(a, b, None, 1, 1, a.size, ())
def inner(a, b):
"""Returns the inner product of two arrays.
It uses the last axis of each argument to take sum product.
Args:
a (cupy.ndarray): The first argument.
b (cupy.ndarray): The second argument.
Returns:
cupy.ndarray: The inner product of ``a`` and ``b``.
.. seealso:: :func:`numpy.inner`
"""
a_ndim = a.ndim
b_ndim = b.ndim
if a_ndim == 0 or b_ndim == 0:
return cupy.multiply(a, b)
a_axis = a_ndim - 1
b_axis = b_ndim - 1
if a.shape[-1] != b.shape[-1]:
raise ValueError('Axis dimension mismatch')
if a_axis:
a = cupy.rollaxis(a, a_axis, 0)
if b_axis:
b = cupy.rollaxis(b, b_axis, 0)
ret_shape = a.shape[1:] + b.shape[1:]
k = a.shape[0]
n = a.size // k
m = b.size // k
return _tensordot_core(a, b, None, n, m, k, ret_shape)
def outer(a, b, out=None):
"""Returns the outer product of two vectors.
The input arrays are flattened into 1-D vectors and then it performs outer
product of these vectors.
Args:
a (cupy.ndarray): The first argument.
b (cupy.ndarray): The second argument.
out (cupy.ndarray): Output array.
Returns:
cupy.ndarray: 2-D array of the outer product of ``a`` and ``b``.
.. seealso:: :func:`numpy.outer`
"""
n = a.size
m = b.size
ret_shape = (n, m)
if out is None:
return _tensordot_core(a, b, None, n, m, 1, ret_shape)
if out.size != n * m:
raise ValueError('Output array has an invalid size')
if out.flags.c_contiguous:
return _tensordot_core(a, b, out, n, m, 1, ret_shape)
else:
out[:] = _tensordot_core(a, b, None, n, m, 1, ret_shape)
return out
def tensordot(a, b, axes=2):
"""Returns the tensor dot product of two arrays along specified axes.
This is equivalent to compute dot product along the specified axes which
are treated as one axis by reshaping.
Args:
a (cupy.ndarray): The first argument.
b (cupy.ndarray): The second argument.
axes:
- If it is an integer, then ``axes`` axes at the last of ``a`` and
the first of ``b`` are used.
- If it is a pair of sequences of integers, then these two
sequences specify the list of axes for ``a`` and ``b``. The
corresponding axes are paired for sum-product.
out (cupy.ndarray): Output array.
Returns:
cupy.ndarray: The tensor dot product of ``a`` and ``b`` along the
axes specified by ``axes``.
.. seealso:: :func:`numpy.tensordot`
"""
a_ndim = a.ndim
b_ndim = b.ndim
if a_ndim == 0 or b_ndim == 0:
if axes != 0 and axes != ((), ()):
raise ValueError('An input is zero-dim while axes has dimensions')
return cupy.multiply(a, b)
if isinstance(axes, collections.Sequence):
if len(axes) != 2:
raise ValueError('Axes must consist of two arrays.')
a_axes, b_axes = axes
if numpy.isscalar(a_axes):
a_axes = a_axes,
if numpy.isscalar(b_axes):
b_axes = b_axes,
else:
a_axes = tuple(six.moves.range(a_ndim - axes, a_ndim))
b_axes = tuple(six.moves.range(axes))
sum_ndim = len(a_axes)
if sum_ndim != len(b_axes):
raise ValueError('Axes length mismatch')
for a_axis, b_axis in zip(a_axes, b_axes):
if a.shape[a_axis] != b.shape[b_axis]:
raise ValueError('Axis dimension mismatch')
# Make the axes non-negative
a = _move_axes_to_head(a, [axis % a_ndim for axis in a_axes])
b = _move_axes_to_head(b, [axis % b_ndim for axis in b_axes])
ret_shape = a.shape[sum_ndim:] + b.shape[sum_ndim:]
k = internal.prod(a.shape[:sum_ndim])
n = a.size // k
m = b.size // k
return _tensordot_core(a, b, None, n, m, k, ret_shape)
def _tensordot_core(a, b, out, n, m, k, ret_shape):
ret_dtype = a.dtype.char
if ret_dtype != b.dtype.char:
ret_dtype = numpy.find_common_type((ret_dtype, b.dtype), ()).char
# Cast to float32 or float64
if ret_dtype == 'f' or ret_dtype == 'd':
dtype = ret_dtype
else:
dtype = numpy.find_common_type((ret_dtype, 'f'), ()).char
a = a.astype(dtype, copy=False)
b = b.astype(dtype, copy=False)
if not a.size or not b.size:
if a.size or b.size:
raise ValueError('cannot dot zero-sized and non-zero-sized arrays')
if out is None:
return cupy.zeros(ret_shape, dtype=ret_dtype)
else:
out.fill(0)
return out
if out is None:
out = cupy.empty(ret_shape, dtype)
if dtype == ret_dtype:
ret = out
else:
ret = cupy.empty(ret_shape, ret_dtype)
else:
ret = out
if out.dtype != dtype:
out = cupy.empty(ret_shape, dtype)
# It copies the operands if needed
if a.shape != (k, n):
a = cupy.reshape(a, (k, n))
if b.shape != (k, m):
b = cupy.reshape(b, (k, m))
c = out
if c.shape != (n, m):
c = c.view()
c.shape = (n, m)
# Be careful that cuBLAS uses the FORTRAN-order matrix representation.
if k == 1:
if n == 1:
# Scalar-vector product
cupy.multiply(a, b, c)
elif m == 1:
# Scalar-vector product
cupy.multiply(a.T, b, c)
else:
# Outer product A^T * B
# c is C-contiguous while cuBLAS requires F-contiguous arrays, so
# we compute C^T = B^T * A here.
handle = cuda.Device().cublas_handle
c.fill(0)
a, inca = _to_cublas_vector(a, 1)
b, incb = _to_cublas_vector(b, 1)
if dtype == 'f':
ger = cublas.sger
elif dtype == 'd':
ger = cublas.dger
ger(handle, m, n, 1, b.data.ptr, incb, a.data.ptr, inca,
c.data.ptr, m)
if dtype != ret_dtype:
elementwise.copy(out, ret)
return ret
handle = cuda.Device().cublas_handle
if n == 1:
if m == 1:
# Inner product
a, inca = _to_cublas_vector(a, 0)
b, incb = _to_cublas_vector(b, 0)
mode = cublas.getPointerMode(handle)
cublas.setPointerMode(handle,
cublas.CUBLAS_POINTER_MODE_DEVICE)
if dtype == 'f':
dot = cublas.sdot
elif dtype == 'd':
dot = cublas.ddot
try:
dot(handle, k, a.data.ptr, inca, b.data.ptr, incb, c.data.ptr)
finally:
cublas.setPointerMode(handle, mode)
else:
# Matrix-vector product B^T * A
a, inca = _to_cublas_vector(a, 0)
b, transb, ldb = _mat_to_cublas_contiguous(b, 1)
if transb:
# gemv requires (m, k) as the original matrix dimensions
# rather than the transposed dimensions.
m, k = k, m
if dtype == 'f':
gemv = cublas.sgemv
elif dtype == 'd':
gemv = cublas.dgemv
gemv(handle, transb, m, k, 1, b.data.ptr, ldb, a.data.ptr, inca,
0, c.data.ptr, 1)
elif m == 1:
# Matrix-vector product A^T * B
a, transa, lda = _mat_to_cublas_contiguous(a, 1)
b, incb = _to_cublas_vector(b, 1)
if not transa:
# gemv requires (n, k) as the original matrix dimensions rather
# than the transposed dimensions.
n, k = k, n
if dtype == 'f':
gemv = cublas.sgemv
elif dtype == 'd':
gemv = cublas.dgemv
gemv(handle, transa, n, k, 1, a.data.ptr, lda, b.data.ptr, incb, 0,
c.data.ptr, 1)
else:
# Matrix-Matrix product A^T * B
# c is C-contiguous while cuBLAS assumes F-contiguous inputs, so we
# compute C^T = B^T * A here.
a, transa, lda = _mat_to_cublas_contiguous(a, 0)
b, transb, ldb = _mat_to_cublas_contiguous(b, 1)
if dtype == 'f':
gemm = cublas.sgemm
elif dtype == 'd':
gemm = cublas.dgemm
gemm(handle, transb, transa, m, n, k, 1, b.data.ptr, ldb, a.data.ptr,
lda, 0, c.data.ptr, m)
if dtype != ret_dtype:
elementwise.copy(out, ret)
return ret
# TODO(okuta): Implement einsum
# TODO(okuta): Implement matrix_power
# TODO(okuta): Implement kron
def _move_axes_to_head(a, axes):
# This function moves the axes of ``s`` to the head of the shape.
for idx, axis in enumerate(axes):
if idx != axis:
break
else:
return a
return cupy.transpose(
a, axes + [i for i in six.moves.range(a.ndim) if i not in axes])
def _mat_to_cublas_contiguous(a, trans):
assert a.ndim == 2
f = a.flags
if f.f_contiguous:
return a, trans, a.strides[1] // a.itemsize
if not f.c_contiguous:
a = a.copy()
return a, 1 - trans, a.strides[0] // a.itemsize
def _to_cublas_vector(a, rundim):
if a.strides[rundim] < 0:
return a.copy(), 1
else:
return a, a.strides[rundim] // a.itemsize
|
sou81821/chainer
|
cupy/linalg/product.py
|
Python
|
mit
| 11,721
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hiren.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
|
pyprism/Hiren-Recipes
|
manage.py
|
Python
|
mit
| 803
|
# Copyright 2014 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.
"""Create / interact with Google Cloud Storage blobs."""
import copy
import datetime
from io import BytesIO
import json
import mimetypes
import os
import time
import six
from six.moves.urllib.parse import quote # pylint: disable=F0401
from apitools.base.py import http_wrapper
from apitools.base.py import transfer
from gcloud._helpers import _RFC3339_MICROS
from gcloud._helpers import UTC
from gcloud.credentials import generate_signed_url
from gcloud.exceptions import NotFound
from gcloud.storage._helpers import _PropertyMixin
from gcloud.storage._helpers import _scalar_property
from gcloud.storage.acl import ObjectACL
_API_ACCESS_ENDPOINT = 'https://storage.googleapis.com'
class Blob(_PropertyMixin):
"""A wrapper around Cloud Storage's concept of an ``Object``.
:type name: string
:param name: The name of the blob. This corresponds to the
unique path of the object in the bucket.
:type bucket: :class:`gcloud.storage.bucket.Bucket`
:param bucket: The bucket to which this blob belongs.
:type chunk_size: integer
:param chunk_size: The size of a chunk of data whenever iterating (1 MB).
This must be a multiple of 256 KB per the API
specification.
"""
_chunk_size = None # Default value for each instance.
_CHUNK_SIZE_MULTIPLE = 256 * 1024
"""Number (256 KB, in bytes) that must divide the chunk size."""
def __init__(self, name, bucket, chunk_size=None):
super(Blob, self).__init__(name=name)
self.chunk_size = chunk_size # Check that setter accepts value.
self.bucket = bucket
self._acl = ObjectACL(self)
@property
def chunk_size(self):
"""Get the blob's default chunk size.
:rtype: integer or ``NoneType``
:returns: The current blob's chunk size, if it is set.
"""
return self._chunk_size
@chunk_size.setter
def chunk_size(self, value):
"""Set the blob's default chunk size.
:type value: integer or ``NoneType``
:param value: The current blob's chunk size, if it is set.
:raises: :class:`ValueError` if ``value`` is not ``None`` and is not a
multiple of 256 KB.
"""
if value is not None and value % self._CHUNK_SIZE_MULTIPLE != 0:
raise ValueError('Chunk size must be a multiple of %d.' % (
self._CHUNK_SIZE_MULTIPLE,))
self._chunk_size = value
@staticmethod
def path_helper(bucket_path, blob_name):
"""Relative URL path for a blob.
:type bucket_path: string
:param bucket_path: The URL path for a bucket.
:type blob_name: string
:param blob_name: The name of the blob.
:rtype: string
:returns: The relative URL path for ``blob_name``.
"""
return bucket_path + '/o/' + quote(blob_name, safe='')
@property
def acl(self):
"""Create our ACL on demand."""
return self._acl
def __repr__(self):
if self.bucket:
bucket_name = self.bucket.name
else:
bucket_name = None
return '<Blob: %s, %s>' % (bucket_name, self.name)
@property
def path(self):
"""Getter property for the URL path to this Blob.
:rtype: string
:returns: The URL path to this Blob.
"""
if not self.name:
raise ValueError('Cannot determine path without a blob name.')
return self.path_helper(self.bucket.path, self.name)
@property
def client(self):
"""The client bound to this blob."""
return self.bucket.client
@property
def public_url(self):
"""The public URL for this blob's object.
:rtype: `string`
:returns: The public URL for this blob.
"""
return '{storage_base_url}/{bucket_name}/{quoted_name}'.format(
storage_base_url='https://storage.googleapis.com',
bucket_name=self.bucket.name,
quoted_name=quote(self.name, safe=''))
def generate_signed_url(self, expiration, method='GET',
client=None, credentials=None):
"""Generates a signed URL for this blob.
.. note::
If you are on Google Compute Engine, you can't generate a signed URL.
Follow
https://github.com/GoogleCloudPlatform/gcloud-python/issues/922
for updates on this. If you'd like to be able to generate a signed
URL from GCE, you can use a standard service account from a JSON
file rather than a GCE service account.
If you have a blob that you want to allow access to for a set
amount of time, you can use this method to generate a URL that
is only valid within a certain time period.
This is particularly useful if you don't want publicly
accessible blobs, but don't want to require users to explicitly
log in.
:type expiration: int, long, datetime.datetime, datetime.timedelta
:param expiration: When the signed URL should expire.
:type method: string
:param method: The HTTP verb that will be used when requesting the URL.
:type client: :class:`gcloud.storage.client.Client` or ``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:type credentials: :class:`oauth2client.client.OAuth2Credentials` or
:class:`NoneType`
:param credentials: The OAuth2 credentials to use to sign the URL.
:rtype: string
:returns: A signed URL you can use to access the resource
until expiration.
"""
resource = '/{bucket_name}/{quoted_name}'.format(
bucket_name=self.bucket.name,
quoted_name=quote(self.name, safe=''))
if credentials is None:
client = self._require_client(client)
credentials = client._connection.credentials
return generate_signed_url(
credentials, resource=resource,
api_access_endpoint=_API_ACCESS_ENDPOINT,
expiration=expiration, method=method)
def exists(self, client=None):
"""Determines whether or not this blob exists.
:type client: :class:`gcloud.storage.client.Client` or ``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:rtype: boolean
:returns: True if the blob exists in Cloud Storage.
"""
client = self._require_client(client)
try:
# We only need the status code (200 or not) so we seek to
# minimize the returned payload.
query_params = {'fields': 'name'}
# We intentionally pass `_target_object=None` since fields=name
# would limit the local properties.
client.connection.api_request(method='GET', path=self.path,
query_params=query_params,
_target_object=None)
# NOTE: This will not fail immediately in a batch. However, when
# Batch.finish() is called, the resulting `NotFound` will be
# raised.
return True
except NotFound:
return False
def delete(self, client=None):
"""Deletes a blob from Cloud Storage.
:type client: :class:`gcloud.storage.client.Client` or ``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:rtype: :class:`Blob`
:returns: The blob that was just deleted.
:raises: :class:`gcloud.exceptions.NotFound`
(propagated from
:meth:`gcloud.storage.bucket.Bucket.delete_blob`).
"""
return self.bucket.delete_blob(self.name, client=client)
def download_to_file(self, file_obj, client=None):
"""Download the contents of this blob into a file-like object.
:type file_obj: file
:param file_obj: A file handle to which to write the blob's data.
:type client: :class:`gcloud.storage.client.Client` or ``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:raises: :class:`gcloud.exceptions.NotFound`
"""
client = self._require_client(client)
download_url = self.media_link
# Use apitools 'Download' facility.
download = transfer.Download.FromStream(file_obj, auto_transfer=False)
headers = {}
if self.chunk_size is not None:
download.chunksize = self.chunk_size
headers['Range'] = 'bytes=0-%d' % (self.chunk_size - 1,)
request = http_wrapper.Request(download_url, 'GET', headers)
# Use the private ``_connection`` rather than the public
# ``.connection``, since the public connection may be a batch. A
# batch wraps a client's connection, but does not store the `http`
# object. The rest (API_BASE_URL and build_api_url) are also defined
# on the Batch class, but we just use the wrapped connection since
# it has all three (http, API_BASE_URL and build_api_url).
download.InitializeDownload(request, client._connection.http)
# Should we be passing callbacks through from caller? We can't
# pass them as None, because apitools wants to print to the console
# by default.
download.StreamInChunks(callback=lambda *args: None,
finish_callback=lambda *args: None)
def download_to_filename(self, filename, client=None):
"""Download the contents of this blob into a named file.
:type filename: string
:param filename: A filename to be passed to ``open``.
:type client: :class:`gcloud.storage.client.Client` or ``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:raises: :class:`gcloud.exceptions.NotFound`
"""
with open(filename, 'wb') as file_obj:
self.download_to_file(file_obj, client=client)
mtime = time.mktime(self.updated.timetuple())
os.utime(file_obj.name, (mtime, mtime))
def download_as_string(self, client=None):
"""Download the contents of this blob as a string.
:type client: :class:`gcloud.storage.client.Client` or ``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:rtype: bytes
:returns: The data stored in this blob.
:raises: :class:`gcloud.exceptions.NotFound`
"""
string_buffer = BytesIO()
self.download_to_file(string_buffer, client=client)
return string_buffer.getvalue()
def upload_from_file(self, file_obj, rewind=False, size=None,
content_type=None, num_retries=6, client=None):
"""Upload the contents of this blob from a file-like object.
The content type of the upload will either be
- The value passed in to the function (if any)
- The value stored on the current blob
- The default value of 'application/octet-stream'
.. note::
The effect of uploading to an existing blob depends on the
"versioning" and "lifecycle" policies defined on the blob's
bucket. In the absence of those policies, upload will
overwrite any existing contents.
See the `object versioning
<https://cloud.google.com/storage/docs/object-versioning>`_ and
`lifecycle <https://cloud.google.com/storage/docs/lifecycle>`_
API documents for details.
:type file_obj: file
:param file_obj: A file handle open for reading.
:type rewind: boolean
:param rewind: If True, seek to the beginning of the file handle before
writing the file to Cloud Storage.
:type size: int
:param size: The number of bytes to read from the file handle.
If not provided, we'll try to guess the size using
:func:`os.fstat`. (If the file handle is not from the
filesystem this won't be possible.)
:type content_type: string or ``NoneType``
:param content_type: Optional type of content being uploaded.
:type num_retries: integer
:param num_retries: Number of upload retries. Defaults to 6.
:type client: :class:`gcloud.storage.client.Client` or ``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:raises: :class:`ValueError` if size is not passed in and can not be
determined
"""
client = self._require_client(client)
# Use the private ``_connection`` rather than the public
# ``.connection``, since the public connection may be a batch. A
# batch wraps a client's connection, but does not store the `http`
# object. The rest (API_BASE_URL and build_api_url) are also defined
# on the Batch class, but we just use the wrapped connection since
# it has all three (http, API_BASE_URL and build_api_url).
connection = client._connection
content_type = (content_type or self._properties.get('contentType') or
'application/octet-stream')
# Rewind the file if desired.
if rewind:
file_obj.seek(0, os.SEEK_SET)
# Get the basic stats about the file.
total_bytes = size
if total_bytes is None:
if hasattr(file_obj, 'fileno'):
total_bytes = os.fstat(file_obj.fileno()).st_size
else:
raise ValueError('total bytes could not be determined. Please '
'pass an explicit size.')
headers = {
'Accept': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'User-Agent': connection.USER_AGENT,
}
upload = transfer.Upload(file_obj, content_type, total_bytes,
auto_transfer=False,
chunksize=self.chunk_size)
url_builder = _UrlBuilder(bucket_name=self.bucket.name,
object_name=self.name)
upload_config = _UploadConfig()
# Temporary URL, until we know simple vs. resumable.
base_url = connection.API_BASE_URL + '/upload'
upload_url = connection.build_api_url(api_base_url=base_url,
path=self.bucket.path + '/o')
# Use apitools 'Upload' facility.
request = http_wrapper.Request(upload_url, 'POST', headers)
upload.ConfigureRequest(upload_config, request, url_builder)
query_params = url_builder.query_params
base_url = connection.API_BASE_URL + '/upload'
request.url = connection.build_api_url(api_base_url=base_url,
path=self.bucket.path + '/o',
query_params=query_params)
upload.InitializeUpload(request, connection.http)
# Should we be passing callbacks through from caller? We can't
# pass them as None, because apitools wants to print to the console
# by default.
if upload.strategy == transfer.RESUMABLE_UPLOAD:
http_response = upload.StreamInChunks(
callback=lambda *args: None,
finish_callback=lambda *args: None)
else:
http_response = http_wrapper.MakeRequest(connection.http, request,
retries=num_retries)
response_content = http_response.content
if not isinstance(response_content,
six.string_types): # pragma: NO COVER Python3
response_content = response_content.decode('utf-8')
self._set_properties(json.loads(response_content))
def upload_from_filename(self, filename, content_type=None,
client=None):
"""Upload this blob's contents from the content of a named file.
The content type of the upload will either be
- The value passed in to the function (if any)
- The value stored on the current blob
- The value given by mimetypes.guess_type
.. note::
The effect of uploading to an existing blob depends on the
"versioning" and "lifecycle" policies defined on the blob's
bucket. In the absence of those policies, upload will
overwrite any existing contents.
See the `object versioning
<https://cloud.google.com/storage/docs/object-versioning>`_ and
`lifecycle <https://cloud.google.com/storage/docs/lifecycle>`_
API documents for details.
:type filename: string
:param filename: The path to the file.
:type content_type: string or ``NoneType``
:param content_type: Optional type of content being uploaded.
:type client: :class:`gcloud.storage.client.Client` or ``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
"""
content_type = content_type or self._properties.get('contentType')
if content_type is None:
content_type, _ = mimetypes.guess_type(filename)
with open(filename, 'rb') as file_obj:
self.upload_from_file(file_obj, content_type=content_type,
client=client)
def upload_from_string(self, data, content_type='text/plain',
client=None):
"""Upload contents of this blob from the provided string.
.. note::
The effect of uploading to an existing blob depends on the
"versioning" and "lifecycle" policies defined on the blob's
bucket. In the absence of those policies, upload will
overwrite any existing contents.
See the `object versioning
<https://cloud.google.com/storage/docs/object-versioning>`_ and
`lifecycle <https://cloud.google.com/storage/docs/lifecycle>`_
API documents for details.
:type data: bytes or text
:param data: The data to store in this blob. If the value is
text, it will be encoded as UTF-8.
:type content_type: string
:param content_type: Optional type of content being uploaded. Defaults
to ``'text/plain'``.
:type client: :class:`gcloud.storage.client.Client` or ``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
"""
if isinstance(data, six.text_type):
data = data.encode('utf-8')
string_buffer = BytesIO()
string_buffer.write(data)
self.upload_from_file(file_obj=string_buffer, rewind=True,
size=len(data), content_type=content_type,
client=client)
def make_public(self, client=None):
"""Make this blob public giving all users read access.
:type client: :class:`gcloud.storage.client.Client` or ``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
"""
self.acl.all().grant_read()
self.acl.save(client=client)
cache_control = _scalar_property('cacheControl')
"""HTTP 'Cache-Control' header for this object.
See: https://tools.ietf.org/html/rfc7234#section-5.2 and
https://cloud.google.com/storage/docs/json_api/v1/objects
If the property is not set locally, returns ``None``.
:rtype: string or ``NoneType``
"""
content_disposition = _scalar_property('contentDisposition')
"""HTTP 'Content-Disposition' header for this object.
See: https://tools.ietf.org/html/rfc6266 and
https://cloud.google.com/storage/docs/json_api/v1/objects
If the property is not set locally, returns ``None``.
:rtype: string or ``NoneType``
"""
content_encoding = _scalar_property('contentEncoding')
"""HTTP 'Content-Encoding' header for this object.
See: https://tools.ietf.org/html/rfc7231#section-3.1.2.2 and
https://cloud.google.com/storage/docs/json_api/v1/objects
If the property is not set locally, returns ``None``.
:rtype: string or ``NoneType``
"""
content_language = _scalar_property('contentLanguage')
"""HTTP 'Content-Language' header for this object.
See: http://tools.ietf.org/html/bcp47 and
https://cloud.google.com/storage/docs/json_api/v1/objects
If the property is not set locally, returns ``None``.
:rtype: string or ``NoneType``
"""
content_type = _scalar_property('contentType')
"""HTTP 'Content-Type' header for this object.
See: https://tools.ietf.org/html/rfc2616#section-14.17 and
https://cloud.google.com/storage/docs/json_api/v1/objects
If the property is not set locally, returns ``None``.
:rtype: string or ``NoneType``
"""
crc32c = _scalar_property('crc32c')
"""CRC32C checksum for this object.
See: http://tools.ietf.org/html/rfc4960#appendix-B and
https://cloud.google.com/storage/docs/json_api/v1/objects
If the property is not set locally, returns ``None``.
:rtype: string or ``NoneType``
"""
@property
def component_count(self):
"""Number of underlying components that make up this object.
See: https://cloud.google.com/storage/docs/json_api/v1/objects
:rtype: integer or ``NoneType``
:returns: The component count (in case of a composed object) or
``None`` if the property is not set locally. This property
will not be set on objects not created via ``compose``.
"""
component_count = self._properties.get('componentCount')
if component_count is not None:
return int(component_count)
@property
def etag(self):
"""Retrieve the ETag for the object.
See: http://tools.ietf.org/html/rfc2616#section-3.11 and
https://cloud.google.com/storage/docs/json_api/v1/objects
:rtype: string or ``NoneType``
:returns: The blob etag or ``None`` if the property is not set locally.
"""
return self._properties.get('etag')
@property
def generation(self):
"""Retrieve the generation for the object.
See: https://cloud.google.com/storage/docs/json_api/v1/objects
:rtype: integer or ``NoneType``
:returns: The generation of the blob or ``None`` if the property
is not set locally.
"""
generation = self._properties.get('generation')
if generation is not None:
return int(generation)
@property
def id(self):
"""Retrieve the ID for the object.
See: https://cloud.google.com/storage/docs/json_api/v1/objects
:rtype: string or ``NoneType``
:returns: The ID of the blob or ``None`` if the property is not
set locally.
"""
return self._properties.get('id')
md5_hash = _scalar_property('md5Hash')
"""MD5 hash for this object.
See: http://tools.ietf.org/html/rfc4960#appendix-B and
https://cloud.google.com/storage/docs/json_api/v1/objects
If the property is not set locally, returns ``None``.
:rtype: string or ``NoneType``
"""
@property
def media_link(self):
"""Retrieve the media download URI for the object.
See: https://cloud.google.com/storage/docs/json_api/v1/objects
:rtype: string or ``NoneType``
:returns: The media link for the blob or ``None`` if the property is
not set locally.
"""
return self._properties.get('mediaLink')
@property
def metadata(self):
"""Retrieve arbitrary/application specific metadata for the object.
See: https://cloud.google.com/storage/docs/json_api/v1/objects
:rtype: dict or ``NoneType``
:returns: The metadata associated with the blob or ``None`` if the
property is not set locally.
"""
return copy.deepcopy(self._properties.get('metadata'))
@metadata.setter
def metadata(self, value):
"""Update arbitrary/application specific metadata for the object.
See: https://cloud.google.com/storage/docs/json_api/v1/objects
:type value: dict or ``NoneType``
:param value: The blob metadata to set.
"""
self._patch_property('metadata', value)
@property
def metageneration(self):
"""Retrieve the metageneration for the object.
See: https://cloud.google.com/storage/docs/json_api/v1/objects
:rtype: integer or ``NoneType``
:returns: The metageneration of the blob or ``None`` if the property
is not set locally.
"""
metageneration = self._properties.get('metageneration')
if metageneration is not None:
return int(metageneration)
@property
def owner(self):
"""Retrieve info about the owner of the object.
See: https://cloud.google.com/storage/docs/json_api/v1/objects
:rtype: dict or ``NoneType``
:returns: Mapping of owner's role/ID. If the property is not set
locally, returns ``None``.
"""
return copy.deepcopy(self._properties.get('owner'))
@property
def self_link(self):
"""Retrieve the URI for the object.
See: https://cloud.google.com/storage/docs/json_api/v1/objects
:rtype: string or ``NoneType``
:returns: The self link for the blob or ``None`` if the property is
not set locally.
"""
return self._properties.get('selfLink')
@property
def size(self):
"""Size of the object, in bytes.
See: https://cloud.google.com/storage/docs/json_api/v1/objects
:rtype: integer or ``NoneType``
:returns: The size of the blob or ``None`` if the property
is not set locally.
"""
size = self._properties.get('size')
if size is not None:
return int(size)
@property
def storage_class(self):
"""Retrieve the storage class for the object.
See: https://cloud.google.com/storage/docs/storage-classes
https://cloud.google.com/storage/docs/nearline-storage
https://cloud.google.com/storage/docs/durable-reduced-availability
:rtype: string or ``NoneType``
:returns: If set, one of "STANDARD", "NEARLINE", or
"DURABLE_REDUCED_AVAILABILITY", else ``None``.
"""
return self._properties.get('storageClass')
@property
def time_deleted(self):
"""Retrieve the timestamp at which the object was deleted.
See: https://cloud.google.com/storage/docs/json_api/v1/objects
:rtype: :class:`datetime.datetime` or ``NoneType``
:returns: Datetime object parsed from RFC3339 valid timestamp, or
``None`` if the property is not set locally. If the blob has
not been deleted, this will never be set.
"""
value = self._properties.get('timeDeleted')
if value is not None:
naive = datetime.datetime.strptime(value, _RFC3339_MICROS)
return naive.replace(tzinfo=UTC)
@property
def updated(self):
"""Retrieve the timestamp at which the object was updated.
See: https://cloud.google.com/storage/docs/json_api/v1/objects
:rtype: :class:`datetime.datetime` or ``NoneType``
:returns: Datetime object parsed from RFC3339 valid timestamp, or
``None`` if the property is not set locally.
"""
value = self._properties.get('updated')
if value is not None:
naive = datetime.datetime.strptime(value, _RFC3339_MICROS)
return naive.replace(tzinfo=UTC)
class _UploadConfig(object):
"""Faux message FBO apitools' 'ConfigureRequest'.
Values extracted from apitools
'samples/storage_sample/storage/storage_v1_client.py'
"""
accept = ['*/*']
max_size = None
resumable_multipart = True
resumable_path = u'/resumable/upload/storage/v1/b/{bucket}/o'
simple_multipart = True
simple_path = u'/upload/storage/v1/b/{bucket}/o'
class _UrlBuilder(object):
"""Faux builder FBO apitools' 'ConfigureRequest'"""
def __init__(self, bucket_name, object_name):
self.query_params = {'name': object_name}
self._bucket_name = bucket_name
self._relative_path = ''
|
thonkify/thonkify
|
src/lib/gcloud/storage/blob.py
|
Python
|
mit
| 30,165
|
# -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2011 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## Invenio is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
'''
bibauthorid_module_stub
Meant for calculating probabilities of a virtual author and a real author
being the same based on their data on a particular paper.
'''
from bibauthorid_utils import get_field_values_on_condition
from bibauthorid_realauthor_utils import set_realauthor_data
from bibauthorid_realauthor_utils import get_realauthor_data
from bibauthorid_virtualauthor_utils import get_virtualauthor_records
from bibauthorid_authorname_utils import get_name_and_db_name_strings
from math import exp
import bibauthorid_config as bconfig
# NAME: Defines the name of the module for display purposes. [A-Za-z0-9 \-_]
MODULE_NAME = "Data Comparison"
# OPERATOR: Defines the operator to use for the final computation [+|*]
MODULE_OPERATOR = "+"
# WEIGHT: Defines the weight of this module for the final computation [0..1]
MODULE_WEIGHT = 1.0
def get_information_from_dataset(va_id, ra_id= -1):
'''
Retrieves information about the data
of a virtual author from the data set.
In dependency of the real author ID, the information will be written to the
real author holding this ID. If the real author ID should be the default
'-1', a list with all the data will be returned.
@param va_id: Virtual author ID to get the information from
@type va_id: int
@param ra_id: Real author ID to set information for.
@type ra_id: int
@return: True, if ra_id is set OR A list of the data
@rtype: True if ra_id > -1 or list of strings
'''
va_data = get_virtualauthor_records(va_id)
bibrec_id = ""
for va_data_item in va_data:
if va_data_item['tag'] == "bibrec_id":
bibrec_id = va_data_item['value']
elif va_data_item['tag'] == "orig_authorname_id":
authorname_id = va_data_item['value']
authorname_strings = get_name_and_db_name_strings(authorname_id)
bconfig.LOGGER.info("| Reading info for va %s: %s recid %s"
% (va_id, authorname_strings["name"], bibrec_id))
data = get_field_values_on_condition(
bibrec_id, ['100', '700'], 'a', 'a',
authorname_strings["db_name"], "!=")
if ra_id > -1:
formatted = "something"
set_realauthor_data(ra_id, "module_tag", "module_value %s"
% (formatted))
return True
else:
return data
def compare_va_to_ra(va_id, ra_id):
'''
Compares the data of a virtual author with all the data of
a real author.
@param va_id: Virtual author ID
@type va_id: int
@param ra_id: Real author ID
@type ra_id: int
@return: the probability of the virtual author belonging to the real author
@rtype: float
'''
bconfig.LOGGER.info("|-> Start of data comparison (va %s : ra %s)"
% (va_id, ra_id))
ra_data = get_realauthor_data(ra_id, "module_tag")
va_data_set = get_information_from_dataset(va_id)
if (len(ra_data) == 0) and (len(va_data_set) == 0):
bconfig.LOGGER.info("|-> End of data comparison (Sets empty)")
return 0
parity = len(ra_data)
# Your probability assessment function here:
certainty = 1 - exp(-.8 * pow(len(parity), .7))
bconfig.LOGGER.info("|--> Found %s matching information out of %s "
"on the paper. Result: %s%% similarity"
% (len(parity), len(va_data_set), certainty))
return certainty
|
Markus-Goetz/CDS-Invenio-Authorlist
|
modules/bibauthorid/lib/bibauthorid_comparison_functions/stub.py
|
Python
|
gpl-2.0
| 4,196
|
from mock import patch, Mock, call
from pulp.agent.lib.report import ContentReport
from pulp.common.constants import PRIMARY_ID
from pulp.server.content.sources.model import DownloadReport, DownloadDetails
from base import ClientTests, Response
from pulp_node.extensions.admin.commands import *
from pulp_node.extensions.admin.rendering import ProgressTracker
from pulp_node.error import *
from pulp_node.reports import RepositoryReport
from pulp_node.handlers.reports import SummaryReport
NODE_ID = 'test.redhat.com'
REPOSITORY_ID = 'test_repository'
MAX_BANDWIDTH = 12345
MAX_CONCURRENCY = 54321
REPO_ENABLED_CHECK = 'pulp_node.extensions.admin.commands.repository_enabled'
NODE_ACTIVATED_CHECK = 'pulp_node.extensions.admin.commands.node_activated'
CONSUMER_LIST_API = 'pulp.bindings.consumer.ConsumerAPI.consumers'
NODE_ACTIVATE_API = 'pulp.bindings.consumer.ConsumerAPI.update'
NODE_UPDATE_API = 'pulp.bindings.consumer.ConsumerContentAPI.update'
REPO_LIST_API = 'pulp.bindings.repository.RepositoryAPI.repositories'
DISTRIBUTORS_API = 'pulp.bindings.repository.RepositoryDistributorAPI.distributors'
PUBLISH_API = 'pulp.bindings.repository.RepositoryActionsAPI.publish'
REPO_ENABLE_API = 'pulp.bindings.repository.RepositoryDistributorAPI.create'
REPO_DISABLE_API = 'pulp.bindings.repository.RepositoryDistributorAPI.delete'
BIND_API = 'pulp.bindings.consumer.BindingsAPI.bind'
UNBIND_API = 'pulp.bindings.consumer.BindingsAPI.unbind'
POLLING_API = 'pulp.client.commands.polling.PollingCommand.poll'
CONSUMERS_ONLY = [
{'notes': {}}
]
CONSUMERS_AND_NODES = [
{'notes': {}},
{'notes': {constants.NODE_NOTE_KEY: True}}
]
NODES_WITH_BINDINGS = [
{
'notes': {constants.NODE_NOTE_KEY: True},
'bindings': [
{
'repo_id': 'r1',
'type_id': constants.HTTP_DISTRIBUTOR,
'binding_config': {constants.STRATEGY_KEYWORD: constants.DEFAULT_STRATEGY}
}
]
},
{
'notes': {constants.NODE_NOTE_KEY: True},
'bindings': [
{
'repo_id': 'r2',
'type_id': constants.HTTP_DISTRIBUTOR,
'binding_config': {constants.STRATEGY_KEYWORD: constants.DEFAULT_STRATEGY},
},
{
'repo_id': 'r3',
'type_id': 'other',
'binding_config': {}, # not node binding
},
{
'repo_id': 'r4',
'type_id': 'other',
'binding_config': {}, # not node binding
},
]
},
]
ALL_REPOSITORIES = [{'id': REPOSITORY_ID}, ]
NON_NODES_DISTRIBUTORS_ONLY = [
{'id': 1, 'distributor_type_id': 1},
{'id': 2, 'distributor_type_id': 2},
]
MIXED_DISTRIBUTORS = [
{'id': 1, 'distributor_type_id': 1},
{'id': 2, 'distributor_type_id': 2},
{'id': 3, 'distributor_type_id': constants.HTTP_DISTRIBUTOR},
{'id': 4, 'distributor_type_id': constants.HTTP_DISTRIBUTOR},
]
UPDATE_REPORT = {
'succeeded': True,
'details': {
'errors':[],
'repositories': [
RepositoryReport('repo_1', RepositoryReport.ADDED)
]
}
}
class TestListCommands(ClientTests):
@patch(CONSUMER_LIST_API, return_value=Response(200, CONSUMERS_ONLY))
def test_list_nodes_no_nodes(self, mock_binding):
# Test
command = NodeListCommand(self.context)
command.run(fields=None)
# Verify
mock_binding.assert_called_with(bindings=False, details=False)
lines = self.recorder.lines
self.assertEqual(len(lines), 4)
self.assertTrue('Child Nodes' in lines[1])
@patch(CONSUMER_LIST_API, return_value=Response(200, CONSUMERS_AND_NODES))
def test_list_nodes(self, mock_binding):
# Test
command = NodeListCommand(self.context)
command.run(fields=None)
# Verify
mock_binding.assert_called_with(bindings=False, details=False)
lines = self.recorder.lines
self.assertEqual(len(lines), 9)
self.assertTrue(NODE_LIST_TITLE in lines[1])
@patch(CONSUMER_LIST_API, return_value=Response(200, NODES_WITH_BINDINGS))
def test_list_nodes_with_bindings(self, mock_binding):
# Test
command = NodeListCommand(self.context)
command.run(fields=None)
# Verify
mock_binding.assert_called_with(bindings=False, details=False)
lines = self.recorder.lines
self.assertEqual(len(lines), 16)
self.assertTrue(NODE_LIST_TITLE in lines[1])
@patch(REPO_LIST_API, return_value=Response(200, ALL_REPOSITORIES))
@patch(DISTRIBUTORS_API, return_value=Response(200, NON_NODES_DISTRIBUTORS_ONLY))
def test_list_repos_disabled_only(self, mock_binding, *unused):
# Test
command = NodeListRepositoriesCommand(self.context)
command.run(details=True, summary=False)
# Verify
mock_binding.assert_called_with(REPOSITORY_ID)
lines = self.recorder.lines
self.assertEqual(len(lines), 4)
self.assertTrue(REPO_LIST_TITLE in lines[1])
@patch(REPO_LIST_API, return_value=Response(200, ALL_REPOSITORIES))
@patch(DISTRIBUTORS_API, return_value=Response(200, MIXED_DISTRIBUTORS))
def test_list_repos_with_enabled(self, mock_binding, *unused):
# Test
command = NodeListRepositoriesCommand(self.context)
command.run(details=True, summary=False)
# Verify
mock_binding.assert_called_with(REPOSITORY_ID)
lines = self.recorder.lines
self.assertEqual(len(lines), 9)
self.assertTrue(REPO_LIST_TITLE in lines[1])
class TestPublishCommand(ClientTests):
@patch(REPO_ENABLED_CHECK, return_value=True)
@patch('pulp.client.commands.polling.PollingCommand.rejected')
@patch('pulp.client.commands.polling.PollingCommand.poll')
@patch(PUBLISH_API, return_value=Response(200, {}))
def test_publish(self, mock_binding, *unused):
# Test
command = NodeRepoPublishCommand(self.context)
keywords = {OPTION_REPO_ID.keyword: REPOSITORY_ID}
command.run(**keywords)
# Verify
self.assertTrue(OPTION_REPO_ID in command.options)
mock_binding.assert_called_with(REPOSITORY_ID, constants.HTTP_DISTRIBUTOR, {})
@patch(REPO_ENABLED_CHECK, return_value=False)
@patch('pulp.client.commands.polling.PollingCommand.rejected')
@patch('pulp.client.commands.polling.PollingCommand.poll')
@patch(PUBLISH_API, return_value=Response(200, {}))
def test_publish_not_enabled(self, mock_binding, *unused):
# Test
command = NodeRepoPublishCommand(self.context)
keywords = {OPTION_REPO_ID.keyword: REPOSITORY_ID}
command.run(**keywords)
# Verify
self.assertTrue(OPTION_REPO_ID in command.options)
self.assertFalse(mock_binding.called)
class TestActivationCommands(ClientTests):
@patch(NODE_ACTIVATED_CHECK, return_value=False)
@patch(NODE_ACTIVATE_API, return_value=Response(200, {}))
def test_activate(self, mock_binding, *unused):
# Test
command = NodeActivateCommand(self.context)
keywords = {
OPTION_CONSUMER_ID.keyword: NODE_ID,
STRATEGY_OPTION.keyword: constants.DEFAULT_STRATEGY
}
command.run(**keywords)
# Verify
delta = {
'notes': {
constants.NODE_NOTE_KEY: True,
constants.STRATEGY_NOTE_KEY: constants.DEFAULT_STRATEGY
}
}
self.assertTrue(OPTION_CONSUMER_ID in command.options)
mock_binding.assert_called_with(NODE_ID, delta)
@patch(NODE_ACTIVATED_CHECK, return_value=True)
@patch(NODE_ACTIVATE_API, return_value=Response(200, {}))
def test_activate_already_activated(self, mock_binding, *unused):
# Setup
command = NodeActivateCommand(self.context)
keywords = {
OPTION_CONSUMER_ID.keyword: NODE_ID,
STRATEGY_OPTION.keyword: constants.DEFAULT_STRATEGY
}
command.run(**keywords)
# Verify
self.assertFalse(mock_binding.called)
@patch(NODE_ACTIVATED_CHECK, return_value=True)
@patch(NODE_ACTIVATE_API, return_value=Response(200, {}))
def test_deactivate(self, mock_binding, mock_activated):
# Test
command = NodeDeactivateCommand(self.context)
keywords = {NODE_ID_OPTION.keyword: NODE_ID}
command.run(**keywords)
# Verify
delta = {'notes': {constants.NODE_NOTE_KEY: None, constants.STRATEGY_NOTE_KEY: None}}
self.assertTrue(NODE_ID_OPTION in command.options)
mock_activated.assert_called_with(self.context, NODE_ID)
mock_binding.assert_called_with(NODE_ID, delta)
@patch(NODE_ACTIVATED_CHECK, return_value=False)
@patch(NODE_ACTIVATE_API, return_value=Response(200, {}))
def test_deactivate_not_activated(self, mock_binding, mock_activated):
# Test
command = NodeDeactivateCommand(self.context)
keywords = {NODE_ID_OPTION.keyword: NODE_ID}
command.run(**keywords)
# Verify
self.assertTrue(NODE_ID_OPTION in command.options)
mock_activated.assert_called_with(self.context, NODE_ID)
self.assertFalse(mock_binding.called)
class TestEnableCommands(ClientTests):
@patch(REPO_ENABLED_CHECK, return_value=False)
@patch(REPO_ENABLE_API, return_value=(200, {}))
def test_enable(self, mock_binding, *unused):
# Test
command = NodeRepoEnableCommand(self.context)
keywords = {
OPTION_REPO_ID.keyword: REPOSITORY_ID,
AUTO_PUBLISH_OPTION.keyword: 'true',
}
command.run(**keywords)
# Verify
self.assertTrue(OPTION_REPO_ID in command.options)
self.assertTrue(AUTO_PUBLISH_OPTION in command.options)
mock_binding.assert_called_with(REPOSITORY_ID, constants.HTTP_DISTRIBUTOR, {},
True, constants.HTTP_DISTRIBUTOR)
@patch(REPO_ENABLED_CHECK, return_value=False)
@patch(REPO_ENABLE_API, return_value=(200, {}))
def test_enable_no_auto_publish(self, mock_binding, *unused):
# Test
command = NodeRepoEnableCommand(self.context)
keywords = {
OPTION_REPO_ID.keyword: REPOSITORY_ID,
AUTO_PUBLISH_OPTION.keyword: 'false',
}
command.run(**keywords)
# Verify
self.assertTrue(OPTION_REPO_ID in command.options)
self.assertTrue(AUTO_PUBLISH_OPTION in command.options)
mock_binding.assert_called_with(REPOSITORY_ID, constants.HTTP_DISTRIBUTOR, {},
False, constants.HTTP_DISTRIBUTOR)
@patch(REPO_ENABLED_CHECK, return_value=True)
@patch(REPO_ENABLE_API, return_value=(200, {}))
def test_enable(self, mock_binding, *unused):
# Test
command = NodeRepoEnableCommand(self.context)
keywords = {
OPTION_REPO_ID.keyword: REPOSITORY_ID,
AUTO_PUBLISH_OPTION.keyword: 'true',
}
command.run(**keywords)
# Verify
self.assertTrue(OPTION_REPO_ID in command.options)
self.assertTrue(AUTO_PUBLISH_OPTION in command.options)
self.assertFalse(mock_binding.called)
@patch(REPO_ENABLED_CHECK, return_value=True)
@patch(REPO_DISABLE_API, return_value=(200, {}))
def test_disable(self, mock_binding, *unused):
# Test
command = NodeRepoDisableCommand(self.context)
keywords = {OPTION_REPO_ID.keyword: REPOSITORY_ID}
command.run(**keywords)
# Verify
self.assertTrue(OPTION_REPO_ID in command.options)
mock_binding.assert_called_with(REPOSITORY_ID, constants.HTTP_DISTRIBUTOR)
class TestBindCommands(ClientTests):
@patch(NODE_ACTIVATED_CHECK, return_value=True)
@patch(BIND_API, return_value=Response(200, {}))
def test_bind(self, mock_binding, *unused):
# Test
command = NodeBindCommand(self.context)
keywords = {
OPTION_REPO_ID.keyword: REPOSITORY_ID,
NODE_ID_OPTION.keyword: NODE_ID,
STRATEGY_OPTION.keyword: constants.DEFAULT_STRATEGY,
}
command.run(**keywords)
# Verify
self.assertTrue(OPTION_REPO_ID in command.options)
self.assertTrue(NODE_ID_OPTION in command.options)
self.assertTrue(STRATEGY_OPTION in command.options)
mock_binding.assert_called_with(
NODE_ID,
REPOSITORY_ID,
constants.HTTP_DISTRIBUTOR,
notify_agent=False,
binding_config={constants.STRATEGY_KEYWORD: constants.DEFAULT_STRATEGY})
@patch(NODE_ACTIVATED_CHECK, return_value=True)
@patch(BIND_API, return_value=Response(200, {}))
def test_bind_with_strategy(self, mock_binding, *unused):
# Test
command = NodeBindCommand(self.context)
keywords = {
OPTION_REPO_ID.keyword: REPOSITORY_ID,
NODE_ID_OPTION.keyword: NODE_ID,
STRATEGY_OPTION.keyword: constants.MIRROR_STRATEGY,
}
command.run(**keywords)
# Verify
self.assertTrue(OPTION_REPO_ID in command.options)
self.assertTrue(NODE_ID_OPTION in command.options)
self.assertTrue(STRATEGY_OPTION in command.options)
mock_binding.assert_called_with(
NODE_ID,
REPOSITORY_ID,
constants.HTTP_DISTRIBUTOR,
notify_agent=False,
binding_config={constants.STRATEGY_KEYWORD: constants.MIRROR_STRATEGY})
@patch(NODE_ACTIVATED_CHECK, return_value=False)
@patch(BIND_API, return_value=Response(200, {}))
def test_bind_not_activated(self, mock_binding, *unused):
# Test
command = NodeBindCommand(self.context)
keywords = {
OPTION_REPO_ID.keyword: REPOSITORY_ID,
NODE_ID_OPTION.keyword: NODE_ID,
STRATEGY_OPTION.keyword: constants.MIRROR_STRATEGY,
}
command.run(**keywords)
# Verify
self.assertTrue(OPTION_REPO_ID in command.options)
self.assertTrue(NODE_ID_OPTION in command.options)
self.assertTrue(STRATEGY_OPTION in command.options)
self.assertFalse(mock_binding.called)
@patch(NODE_ACTIVATED_CHECK, return_value=True)
@patch(UNBIND_API, return_value=Response(200, {}))
def test_unbind(self, mock_binding, *unused):
# Test
command = NodeUnbindCommand(self.context)
keywords = {
OPTION_REPO_ID.keyword: REPOSITORY_ID,
NODE_ID_OPTION.keyword: NODE_ID,
}
command.run(**keywords)
# Verify
self.assertTrue(OPTION_REPO_ID in command.options)
self.assertTrue(NODE_ID_OPTION in command.options)
mock_binding.assert_called_with(NODE_ID, REPOSITORY_ID, constants.HTTP_DISTRIBUTOR)
class TestUpdateCommands(ClientTests):
@patch(POLLING_API)
@patch(NODE_ACTIVATED_CHECK, return_value=True)
@patch(NODE_UPDATE_API, return_value=Response(202, {}))
def test_update(self, mock_update, mock_activated, *unused):
# Test
command = NodeUpdateCommand(self.context)
keywords = {
NODE_ID_OPTION.keyword: NODE_ID,
MAX_BANDWIDTH_OPTION.keyword: MAX_BANDWIDTH,
MAX_CONCURRENCY_OPTION.keyword: MAX_CONCURRENCY
}
command.run(**keywords)
# Verify
units = [dict(type_id='node', unit_key=None)]
options = {
constants.MAX_DOWNLOAD_BANDWIDTH_KEYWORD: MAX_BANDWIDTH,
constants.MAX_DOWNLOAD_CONCURRENCY_KEYWORD: MAX_CONCURRENCY,
}
self.assertTrue(NODE_ID_OPTION in command.options)
self.assertTrue(MAX_BANDWIDTH_OPTION in command.options)
self.assertTrue(MAX_CONCURRENCY_OPTION in command.options)
mock_update.assert_called_with(NODE_ID, units=units, options=options)
mock_activated.assert_called_with(self.context, NODE_ID)
class TestRenderers(ClientTests):
def test_update_rendering(self):
repo_ids = ['repo_%d' % n for n in range(0, 3)]
handler_report = ContentReport()
summary_report = SummaryReport()
summary_report.setup([{'repo_id': r} for r in repo_ids])
for r in summary_report.repository.values():
r.action = RepositoryReport.ADDED
download_report = DownloadReport()
download_report.downloads[PRIMARY_ID] = DownloadDetails()
download_report.downloads['content-world'] = DownloadDetails()
r.sources = download_report.dict()
handler_report.set_succeeded(details=summary_report.dict())
renderer = UpdateRenderer(self.context.prompt, handler_report.dict())
renderer.render()
self.assertEqual(len(self.recorder.lines), 59)
def test_update_rendering_with_errors(self):
repo_ids = ['repo_%d' % n for n in range(0, 3)]
handler_report = ContentReport()
summary_report = SummaryReport()
summary_report.setup([{'repo_id': r} for r in repo_ids])
for r in summary_report.repository.values():
r.action = RepositoryReport.ADDED
summary_report.errors.append(
UnitDownloadError('http://abc/x.rpm', repo_ids[0], dict(response_code=401)))
handler_report.set_failed(details=summary_report.dict())
renderer = UpdateRenderer(self.context.prompt, handler_report.dict())
renderer.render()
self.assertEqual(len(self.recorder.lines), 48)
def test_update_rendering_with_message(self):
handler_report = ContentReport()
handler_report.set_failed(details=dict(message='Authorization Failed'))
renderer = UpdateRenderer(self.context.prompt, handler_report.dict())
renderer.render()
self.assertEqual(len(self.recorder.lines), 4)
class TestProgressTracking(ClientTests):
def test_display_none(self):
fake_prompt = Mock()
tracker = ProgressTracker(fake_prompt)
tracker.display(None)
def test_display_no_report(self):
fake_prompt = Mock()
tracker = ProgressTracker(fake_prompt)
tracker.display({})
def test_display_no_snapshot(self):
reports = [
{'repo_id': 1, 'state': 'merging'},
{'repo_id': 2, 'state': 'merging'},
{'repo_id': 3, 'state': 'merging'},
]
report = {
'progress': reports
}
mock_prompt = Mock()
snapshot = [(r, Mock()) for r in reports]
mock_prompt.create_progress_bar.side_effect = [s[1] for s in snapshot]
tracker = ProgressTracker(mock_prompt)
tracker._render = Mock()
tracker.display(report)
self.assertEqual(tracker.snapshot, snapshot)
tracker._render.assert_has_calls([call(r, pb) for r, pb in snapshot])
mock_prompt.write.assert_has_calls(
[
call('\n'),
call('(1/3) Repository: 1'),
call('\n'),
call('(2/3) Repository: 2'),
call('\n'),
call('(3/3) Repository: 3')
]
)
def test_display_with_snapshot(self):
reports = [
{'repo_id': 1, 'state': 'import_finished'},
{'repo_id': 2, 'state': 'import_finished'},
{'repo_id': 3, 'state': 'import_finished'},
{'repo_id': 4, 'state': 'import_finished'},
{'repo_id': 5, 'state': 'import_finished'},
{'repo_id': 6, 'state': 'merging'},
]
report = {
'progress': reports
}
mock_prompt = Mock()
snapshot = [(r, Mock()) for r in reports]
mock_prompt.create_progress_bar.side_effect = [s[1] for s in snapshot[3:]]
tracker = ProgressTracker(mock_prompt)
tracker.snapshot = snapshot[:3]
tracker._render = Mock()
tracker.display(report)
self.assertEqual(tracker.snapshot, snapshot)
tracker._render.assert_has_calls([call(r, pb) for r, pb in snapshot[3:]])
mock_prompt.write.assert_has_calls(
[
call('\n'),
call('(4/6) Repository: 4'),
call('\n'),
call('(5/6) Repository: 5'),
call('\n'),
call('(6/6) Repository: 6')
]
)
def test_find(self):
reports = [
{'repo_id': 1, 'state': 'merging'},
{'repo_id': 2, 'state': 'merging'},
{'repo_id': 3, 'state': 'merging'},
]
self.assertEqual(ProgressTracker._find(2, reports), reports[1])
def test_render(self):
report = {
'repo_id': 1,
'state': 'adding_units',
'unit_add': {
'total': 10,
'completed': 5,
'details': 'http://redhat.com/foo/bar.unit'
}
}
progress_bar = Mock()
ProgressTracker._render(report, progress_bar)
progress_bar.render.assert_called_with(5, 10, 'Step: Adding Units\n(5/10) Add unit: bar.unit')
def test_render_not_adding_units(self):
report = {
'repo_id': 1,
'state': 'merging',
'unit_add': {
'total': 10,
'completed': 5,
'details': ''
}
}
progress_bar = Mock()
ProgressTracker._render(report, progress_bar)
progress_bar.render.assert_called_with(5, 10, None)
def test_render_zero_total_and_finished(self):
report = {
'repo_id': 1,
'state': 'import_finished',
'unit_add': {
'total': 0,
'completed': 0,
'details': ''
}
}
progress_bar = Mock()
ProgressTracker._render(report, progress_bar)
progress_bar.render.assert_called_with(1, 1)
def test_render_zero_total_and_not_finished(self):
report = {
'repo_id': 1,
'state': 'merging',
'unit_add': {
'total': 0,
'completed': 0,
'details': ''
}
}
progress_bar = Mock()
ProgressTracker._render(report, progress_bar)
progress_bar.render.assert_called_with(0.01, 1)
|
credativ/pulp
|
nodes/test/nodes_tests/test_admin_extensions.py
|
Python
|
gpl-2.0
| 22,381
|
# encoding: utf-8
"""General utilities for kernel related things."""
__docformat__ = "restructuredtext en"
#-------------------------------------------------------------------------------
# Copyright (C) 2008 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# Imports
#-------------------------------------------------------------------------------
import os, types
#-------------------------------------------------------------------------------
# Code
#-------------------------------------------------------------------------------
def tarModule(mod):
"""Makes a tarball (as a string) of a locally imported module.
This method looks at the __file__ attribute of an imported module
and makes a tarball of the top level of the module. It then
reads the tarball into a binary string.
The method returns the tarball's name and the binary string
representing the tarball.
Notes:
- It will handle both single module files, as well as packages.
- The byte code files (\*.pyc) are not deleted.
- It has not been tested with modules containing extension code, but
it should work in most cases.
- There are cross platform issues.
"""
if not isinstance(mod, types.ModuleType):
raise TypeError, "Pass an imported module to push_module"
module_dir, module_file = os.path.split(mod.__file__)
# Figure out what the module is called and where it is
print "Locating the module..."
if "__init__.py" in module_file: # package
module_name = module_dir.split("/")[-1]
module_dir = "/".join(module_dir.split("/")[:-1])
module_file = module_name
else: # Simple module
module_name = module_file.split(".")[0]
module_dir = module_dir
print "Module (%s) found in:\n%s" % (module_name, module_dir)
# Make a tarball of the module in the cwd
if module_dir:
os.system('tar -cf %s.tar -C %s %s' % \
(module_name, module_dir, module_file))
else: # must be the cwd
os.system('tar -cf %s.tar %s' % \
(module_name, module_file))
# Read the tarball into a binary string
tarball_name = module_name + ".tar"
tar_file = open(tarball_name,'rb')
fileString = tar_file.read()
tar_file.close()
# Remove the local copy of the tarball
#os.system("rm %s" % tarball_name)
return tarball_name, fileString
#from the Python Cookbook:
def curry(f, *curryArgs, **curryKWargs):
"""Curry the function f with curryArgs and curryKWargs."""
def curried(*args, **kwargs):
dikt = dict(kwargs)
dikt.update(curryKWargs)
return f(*(curryArgs+args), **dikt)
return curried
#useful callbacks
def catcher(r):
pass
def printer(r, msg=''):
print "%s\n%r" % (msg, r)
return r
|
mastizada/kuma
|
vendor/packages/ipython/IPython/kernel/util.py
|
Python
|
mpl-2.0
| 3,193
|
# -*- 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 logging
import time
from openerp import tools
from openerp.osv import fields, osv
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
import openerp.addons.product.product
_logger = logging.getLogger(__name__)
class pos_config(osv.osv):
_name = 'pos.config'
POS_CONFIG_STATE = [
('active', 'Active'),
('inactive', 'Inactive'),
('deprecated', 'Deprecated')
]
def _get_currency(self, cr, uid, ids, fieldnames, args, context=None):
result = dict.fromkeys(ids, False)
for pos_config in self.browse(cr, uid, ids, context=context):
if pos_config.journal_id:
currency_id = pos_config.journal_id.currency.id or pos_config.journal_id.company_id.currency_id.id
else:
currency_id = self.pool['res.users'].browse(cr, uid, uid, context=context).company_id.currency_id.id
result[pos_config.id] = currency_id
return result
_columns = {
'name' : fields.char('Point of Sale Name', select=1,
required=True, help="An internal identification of the point of sale"),
'journal_ids' : fields.many2many('account.journal', 'pos_config_journal_rel',
'pos_config_id', 'journal_id', 'Available Payment Methods',
domain="[('journal_user', '=', True ), ('type', 'in', ['bank', 'cash'])]",),
'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type'),
'stock_location_id': fields.many2one('stock.location', 'Stock Location', domain=[('usage', '=', 'internal')], required=True),
'journal_id' : fields.many2one('account.journal', 'Sale Journal',
domain=[('type', '=', 'sale')],
help="Accounting journal used to post sales entries."),
'currency_id' : fields.function(_get_currency, type="many2one", string="Currency", relation="res.currency"),
'iface_self_checkout' : fields.boolean('Self Checkout Mode', # FIXME : this field is obsolete
help="Check this if this point of sale should open by default in a self checkout mode. If unchecked, Odoo uses the normal cashier mode by default."),
'iface_cashdrawer' : fields.boolean('Cashdrawer', help="Automatically open the cashdrawer"),
'iface_payment_terminal' : fields.boolean('Payment Terminal', help="Enables Payment Terminal integration"),
'iface_electronic_scale' : fields.boolean('Electronic Scale', help="Enables Electronic Scale integration"),
'iface_vkeyboard' : fields.boolean('Virtual KeyBoard', help="Enables an integrated Virtual Keyboard"),
'iface_print_via_proxy' : fields.boolean('Print via Proxy', help="Bypass browser printing and prints via the hardware proxy"),
'iface_scan_via_proxy' : fields.boolean('Scan via Proxy', help="Enable barcode scanning with a remotely connected barcode scanner"),
'iface_invoicing': fields.boolean('Invoicing',help='Enables invoice generation from the Point of Sale'),
'iface_big_scrollbars': fields.boolean('Large Scrollbars',help='For imprecise industrial touchscreens'),
'receipt_header': fields.text('Receipt Header',help="A short text that will be inserted as a header in the printed receipt"),
'receipt_footer': fields.text('Receipt Footer',help="A short text that will be inserted as a footer in the printed receipt"),
'proxy_ip': fields.char('IP Address', help='The hostname or ip address of the hardware proxy, Will be autodetected if left empty', size=45),
'state' : fields.selection(POS_CONFIG_STATE, 'Status', required=True, readonly=True, copy=False),
'sequence_id' : fields.many2one('ir.sequence', 'Order IDs Sequence', readonly=True,
help="This sequence is automatically created by Odoo but you can change it "\
"to customize the reference numbers of your orders.", copy=False),
'session_ids': fields.one2many('pos.session', 'config_id', 'Sessions'),
'group_by' : fields.boolean('Group Journal Items', help="Check this if you want to group the Journal Items by Product while closing a Session"),
'pricelist_id': fields.many2one('product.pricelist','Pricelist', required=True),
'company_id': fields.many2one('res.company', 'Company', required=True),
'barcode_product': fields.char('Product Barcodes', size=64, help='The pattern that identifies product barcodes'),
'barcode_cashier': fields.char('Cashier Barcodes', size=64, help='The pattern that identifies cashier login barcodes'),
'barcode_customer': fields.char('Customer Barcodes',size=64, help='The pattern that identifies customer\'s client card barcodes'),
'barcode_price': fields.char('Price Barcodes', size=64, help='The pattern that identifies a product with a barcode encoded price'),
'barcode_weight': fields.char('Weight Barcodes', size=64, help='The pattern that identifies a product with a barcode encoded weight'),
'barcode_discount': fields.char('Discount Barcodes', size=64, help='The pattern that identifies a product with a barcode encoded discount'),
}
def _check_cash_control(self, cr, uid, ids, context=None):
return all(
(sum(int(journal.cash_control) for journal in record.journal_ids) <= 1)
for record in self.browse(cr, uid, ids, context=context)
)
def _check_company_location(self, cr, uid, ids, context=None):
for config in self.browse(cr, uid, ids, context=context):
if config.stock_location_id.company_id and config.stock_location_id.company_id.id != config.company_id.id:
return False
return True
def _check_company_journal(self, cr, uid, ids, context=None):
for config in self.browse(cr, uid, ids, context=context):
if config.journal_id and config.journal_id.company_id.id != config.company_id.id:
return False
return True
def _check_company_payment(self, cr, uid, ids, context=None):
for config in self.browse(cr, uid, ids, context=context):
journal_ids = [j.id for j in config.journal_ids]
if self.pool['account.journal'].search(cr, uid, [
('id', 'in', journal_ids),
('company_id', '!=', config.company_id.id)
], count=True, context=context):
return False
return True
_constraints = [
(_check_cash_control, "You cannot have two cash controls in one Point Of Sale !", ['journal_ids']),
(_check_company_location, "The company of the stock location is different than the one of point of sale", ['company_id', 'stock_location_id']),
(_check_company_journal, "The company of the sale journal is different than the one of point of sale", ['company_id', 'journal_id']),
(_check_company_payment, "The company of a payment method is different than the one of point of sale", ['company_id', 'journal_ids']),
]
def name_get(self, cr, uid, ids, context=None):
result = []
states = {
'opening_control': _('Opening Control'),
'opened': _('In Progress'),
'closing_control': _('Closing Control'),
'closed': _('Closed & Posted'),
}
for record in self.browse(cr, uid, ids, context=context):
if (not record.session_ids) or (record.session_ids[0].state=='closed'):
result.append((record.id, record.name+' ('+_('not used')+')'))
continue
session = record.session_ids[0]
result.append((record.id, record.name + ' ('+session.user_id.name+')')) #, '+states[session.state]+')'))
return result
def _default_sale_journal(self, cr, uid, context=None):
company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
res = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'sale'), ('company_id', '=', company_id)], limit=1, context=context)
return res and res[0] or False
def _default_pricelist(self, cr, uid, context=None):
res = self.pool.get('product.pricelist').search(cr, uid, [('type', '=', 'sale')], limit=1, context=context)
return res and res[0] or False
def _get_default_location(self, cr, uid, context=None):
wh_obj = self.pool.get('stock.warehouse')
user = self.pool.get('res.users').browse(cr, uid, uid, context)
res = wh_obj.search(cr, uid, [('company_id', '=', user.company_id.id)], limit=1, context=context)
if res and res[0]:
return wh_obj.browse(cr, uid, res[0], context=context).lot_stock_id.id
return False
def _get_default_company(self, cr, uid, context=None):
company_id = self.pool.get('res.users')._get_company(cr, uid, context=context)
return company_id
_defaults = {
'state' : POS_CONFIG_STATE[0][0],
'journal_id': _default_sale_journal,
'group_by' : True,
'pricelist_id': _default_pricelist,
'iface_invoicing': True,
'stock_location_id': _get_default_location,
'company_id': _get_default_company,
'barcode_product': '*',
'barcode_cashier': '041*',
'barcode_customer':'042*',
'barcode_weight': '21xxxxxNNDDD',
'barcode_discount':'22xxxxxxxxNN',
'barcode_price': '23xxxxxNNNDD',
}
def onchange_picking_type_id(self, cr, uid, ids, picking_type_id, context=None):
p_type_obj = self.pool.get("stock.picking.type")
p_type = p_type_obj.browse(cr, uid, picking_type_id, context=context)
if p_type.default_location_src_id and p_type.default_location_src_id.usage == 'internal' and p_type.default_location_dest_id and p_type.default_location_dest_id.usage == 'customer':
return {'value': {'stock_location_id': p_type.default_location_src_id.id}}
return False
def set_active(self, cr, uid, ids, context=None):
return self.write(cr, uid, ids, {'state' : 'active'}, context=context)
def set_inactive(self, cr, uid, ids, context=None):
return self.write(cr, uid, ids, {'state' : 'inactive'}, context=context)
def set_deprecate(self, cr, uid, ids, context=None):
return self.write(cr, uid, ids, {'state' : 'deprecated'}, context=context)
def create(self, cr, uid, values, context=None):
ir_sequence = self.pool.get('ir.sequence')
# force sequence_id field to new pos.order sequence
values['sequence_id'] = ir_sequence.create(cr, uid, {
'name': 'POS Order %s' % values['name'],
'padding': 4,
'prefix': "%s/" % values['name'],
'code': "pos.order",
'company_id': values.get('company_id', False),
}, context=context)
# TODO master: add field sequence_line_id on model
# this make sure we always have one available per company
ir_sequence.create(cr, uid, {
'name': 'POS order line %s' % values['name'],
'padding': 4,
'prefix': "%s/" % values['name'],
'code': "pos.order.line",
'company_id': values.get('company_id', False),
}, context=context)
return super(pos_config, self).create(cr, uid, values, context=context)
def unlink(self, cr, uid, ids, context=None):
for obj in self.browse(cr, uid, ids, context=context):
if obj.sequence_id:
obj.sequence_id.unlink()
return super(pos_config, self).unlink(cr, uid, ids, context=context)
class pos_session(osv.osv):
_name = 'pos.session'
_order = 'id desc'
POS_SESSION_STATE = [
('opening_control', 'Opening Control'), # Signal open
('opened', 'In Progress'), # Signal closing
('closing_control', 'Closing Control'), # Signal close
('closed', 'Closed & Posted'),
]
def _compute_cash_all(self, cr, uid, ids, fieldnames, args, context=None):
result = dict()
for record in self.browse(cr, uid, ids, context=context):
result[record.id] = {
'cash_journal_id' : False,
'cash_register_id' : False,
'cash_control' : False,
}
for st in record.statement_ids:
if st.journal_id.cash_control == True:
result[record.id]['cash_control'] = True
result[record.id]['cash_journal_id'] = st.journal_id.id
result[record.id]['cash_register_id'] = st.id
return result
_columns = {
'config_id' : fields.many2one('pos.config', 'Point of Sale',
help="The physical point of sale you will use.",
required=True,
select=1,
domain="[('state', '=', 'active')]",
),
'name' : fields.char('Session ID', required=True, readonly=True),
'user_id' : fields.many2one('res.users', 'Responsible',
required=True,
select=1,
readonly=True,
states={'opening_control' : [('readonly', False)]}
),
'currency_id' : fields.related('config_id', 'currency_id', type="many2one", relation='res.currency', string="Currnecy"),
'start_at' : fields.datetime('Opening Date', readonly=True),
'stop_at' : fields.datetime('Closing Date', readonly=True),
'state' : fields.selection(POS_SESSION_STATE, 'Status',
required=True, readonly=True,
select=1, copy=False),
'sequence_number': fields.integer('Order Sequence Number', help='A sequence number that is incremented with each order'),
'login_number': fields.integer('Login Sequence Number', help='A sequence number that is incremented each time a user resumes the pos session'),
'cash_control' : fields.function(_compute_cash_all,
multi='cash',
type='boolean', string='Has Cash Control'),
'cash_journal_id' : fields.function(_compute_cash_all,
multi='cash',
type='many2one', relation='account.journal',
string='Cash Journal', store=True),
'cash_register_id' : fields.function(_compute_cash_all,
multi='cash',
type='many2one', relation='account.bank.statement',
string='Cash Register', store=True),
'opening_details_ids' : fields.related('cash_register_id', 'opening_details_ids',
type='one2many', relation='account.cashbox.line',
string='Opening Cash Control'),
'details_ids' : fields.related('cash_register_id', 'details_ids',
type='one2many', relation='account.cashbox.line',
string='Cash Control'),
'cash_register_balance_end_real' : fields.related('cash_register_id', 'balance_end_real',
type='float',
digits_compute=dp.get_precision('Account'),
string="Ending Balance",
help="Total of closing cash control lines.",
readonly=True),
'cash_register_balance_start' : fields.related('cash_register_id', 'balance_start',
type='float',
digits_compute=dp.get_precision('Account'),
string="Starting Balance",
help="Total of opening cash control lines.",
readonly=True),
'cash_register_total_entry_encoding' : fields.related('cash_register_id', 'total_entry_encoding',
string='Total Cash Transaction',
readonly=True,
help="Total of all paid sale orders"),
'cash_register_balance_end' : fields.related('cash_register_id', 'balance_end',
type='float',
digits_compute=dp.get_precision('Account'),
string="Theoretical Closing Balance",
help="Sum of opening balance and transactions.",
readonly=True),
'cash_register_difference' : fields.related('cash_register_id', 'difference',
type='float',
string='Difference',
help="Difference between the theoretical closing balance and the real closing balance.",
readonly=True),
'journal_ids' : fields.related('config_id', 'journal_ids',
type='many2many',
readonly=True,
relation='account.journal',
string='Available Payment Methods'),
'order_ids' : fields.one2many('pos.order', 'session_id', 'Orders'),
'statement_ids' : fields.one2many('account.bank.statement', 'pos_session_id', 'Bank Statement', readonly=True),
}
_defaults = {
'name' : '/',
'user_id' : lambda obj, cr, uid, context: uid,
'state' : 'opening_control',
'sequence_number': 1,
'login_number': 0,
}
_sql_constraints = [
('uniq_name', 'unique(name)', "The name of this POS Session must be unique !"),
]
def _check_unicity(self, cr, uid, ids, context=None):
for session in self.browse(cr, uid, ids, context=None):
# open if there is no session in 'opening_control', 'opened', 'closing_control' for one user
domain = [
('state', 'not in', ('closed','closing_control')),
('user_id', '=', session.user_id.id)
]
count = self.search_count(cr, uid, domain, context=context)
if count>1:
return False
return True
def _check_pos_config(self, cr, uid, ids, context=None):
for session in self.browse(cr, uid, ids, context=None):
domain = [
('state', '!=', 'closed'),
('config_id', '=', session.config_id.id)
]
count = self.search_count(cr, uid, domain, context=context)
if count>1:
return False
return True
_constraints = [
(_check_unicity, "You cannot create two active sessions with the same responsible!", ['user_id', 'state']),
(_check_pos_config, "You cannot create two active sessions related to the same point of sale!", ['config_id']),
]
def create(self, cr, uid, values, context=None):
context = dict(context or {})
config_id = values.get('config_id', False) or context.get('default_config_id', False)
if not config_id:
raise osv.except_osv( _('Error!'),
_("You should assign a Point of Sale to your session."))
# journal_id is not required on the pos_config because it does not
# exists at the installation. If nothing is configured at the
# installation we do the minimal configuration. Impossible to do in
# the .xml files as the CoA is not yet installed.
jobj = self.pool.get('pos.config')
pos_config = jobj.browse(cr, uid, config_id, context=context)
context.update({'company_id': pos_config.company_id.id})
if not pos_config.journal_id:
jid = jobj.default_get(cr, uid, ['journal_id'], context=context)['journal_id']
if jid:
jobj.write(cr, openerp.SUPERUSER_ID, [pos_config.id], {'journal_id': jid}, context=context)
else:
raise osv.except_osv( _('error!'),
_("Unable to open the session. You have to assign a sale journal to your point of sale."))
# define some cash journal if no payment method exists
if not pos_config.journal_ids:
journal_proxy = self.pool.get('account.journal')
cashids = journal_proxy.search(cr, uid, [('journal_user', '=', True), ('type','=','cash')], context=context)
if not cashids:
cashids = journal_proxy.search(cr, uid, [('type', '=', 'cash')], context=context)
if not cashids:
cashids = journal_proxy.search(cr, uid, [('journal_user','=',True)], context=context)
journal_proxy.write(cr, openerp.SUPERUSER_ID, cashids, {'journal_user': True})
jobj.write(cr, openerp.SUPERUSER_ID, [pos_config.id], {'journal_ids': [(6,0, cashids)]})
pos_config = jobj.browse(cr, uid, config_id, context=context)
bank_statement_ids = []
for journal in pos_config.journal_ids:
bank_values = {
'journal_id' : journal.id,
'user_id' : uid,
'company_id' : pos_config.company_id.id
}
statement_id = self.pool.get('account.bank.statement').create(cr, uid, bank_values, context=context)
bank_statement_ids.append(statement_id)
values.update({
'name': self.pool['ir.sequence'].get(cr, uid, 'pos.session'),
'statement_ids' : [(6, 0, bank_statement_ids)],
'config_id': config_id
})
return super(pos_session, self).create(cr, uid, values, context=context)
def unlink(self, cr, uid, ids, context=None):
for obj in self.browse(cr, uid, ids, context=context):
for statement in obj.statement_ids:
statement.unlink(context=context)
return super(pos_session, self).unlink(cr, uid, ids, context=context)
def open_cb(self, cr, uid, ids, context=None):
"""
call the Point Of Sale interface and set the pos.session to 'opened' (in progress)
"""
if context is None:
context = dict()
if isinstance(ids, (int, long)):
ids = [ids]
this_record = self.browse(cr, uid, ids[0], context=context)
this_record.signal_workflow('open')
context.update(active_id=this_record.id)
return {
'type' : 'ir.actions.act_url',
'url' : '/pos/web/',
'target': 'self',
}
def login(self, cr, uid, ids, context=None):
this_record = self.browse(cr, uid, ids[0], context=context)
this_record.write({
'login_number': this_record.login_number+1,
})
def wkf_action_open(self, cr, uid, ids, context=None):
# second browse because we need to refetch the data from the DB for cash_register_id
for record in self.browse(cr, uid, ids, context=context):
values = {}
if not record.start_at:
values['start_at'] = time.strftime('%Y-%m-%d %H:%M:%S')
values['state'] = 'opened'
record.write(values)
for st in record.statement_ids:
st.button_open()
return self.open_frontend_cb(cr, uid, ids, context=context)
def wkf_action_opening_control(self, cr, uid, ids, context=None):
return self.write(cr, uid, ids, {'state' : 'opening_control'}, context=context)
def wkf_action_closing_control(self, cr, uid, ids, context=None):
for session in self.browse(cr, uid, ids, context=context):
for statement in session.statement_ids:
if (statement != session.cash_register_id) and (statement.balance_end != statement.balance_end_real):
self.pool.get('account.bank.statement').write(cr, uid, [statement.id], {'balance_end_real': statement.balance_end})
return self.write(cr, uid, ids, {'state' : 'closing_control', 'stop_at' : time.strftime('%Y-%m-%d %H:%M:%S')}, context=context)
def wkf_action_close(self, cr, uid, ids, context=None):
# Close CashBox
for record in self.browse(cr, uid, ids, context=context):
for st in record.statement_ids:
if abs(st.difference) > st.journal_id.amount_authorized_diff:
# The pos manager can close statements with maximums.
if not self.pool.get('ir.model.access').check_groups(cr, uid, "point_of_sale.group_pos_manager"):
raise osv.except_osv( _('Error!'),
_("Your ending balance is too different from the theoretical cash closing (%.2f), the maximum allowed is: %.2f. You can contact your manager to force it.") % (st.difference, st.journal_id.amount_authorized_diff))
if (st.journal_id.type not in ['bank', 'cash']):
raise osv.except_osv(_('Error!'),
_("The type of the journal for your payment method should be bank or cash "))
getattr(st, 'button_confirm_%s' % st.journal_id.type)(context=context)
self._confirm_orders(cr, uid, ids, context=context)
self.write(cr, uid, ids, {'state' : 'closed'}, context=context)
obj = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'point_of_sale', 'menu_point_root')[1]
return {
'type' : 'ir.actions.client',
'name' : 'Point of Sale Menu',
'tag' : 'reload',
'params' : {'menu_id': obj},
}
def _confirm_orders(self, cr, uid, ids, context=None):
account_move_obj = self.pool.get('account.move')
pos_order_obj = self.pool.get('pos.order')
for session in self.browse(cr, uid, ids, context=context):
local_context = dict(context or {}, force_company=session.config_id.journal_id.company_id.id)
order_ids = [order.id for order in session.order_ids if order.state == 'paid']
move_id = account_move_obj.create(cr, uid, {'ref' : session.name, 'journal_id' : session.config_id.journal_id.id, }, context=local_context)
pos_order_obj._create_account_move_line(cr, uid, order_ids, session, move_id, context=local_context)
for order in session.order_ids:
if order.state == 'done':
continue
if order.state not in ('paid', 'invoiced'):
raise osv.except_osv(
_('Error!'),
_("You cannot confirm all orders of this session, because they have not the 'paid' status"))
else:
pos_order_obj.signal_workflow(cr, uid, [order.id], 'done')
return True
def open_frontend_cb(self, cr, uid, ids, context=None):
if not context:
context = {}
if not ids:
return {}
for session in self.browse(cr, uid, ids, context=context):
if session.user_id.id != uid:
raise osv.except_osv(
_('Error!'),
_("You cannot use the session of another users. This session is owned by %s. Please first close this one to use this point of sale." % session.user_id.name))
context.update({'active_id': ids[0]})
return {
'type' : 'ir.actions.act_url',
'target': 'self',
'url': '/pos/web/',
}
class pos_order(osv.osv):
_name = "pos.order"
_description = "Point of Sale"
_order = "id desc"
def _order_fields(self, cr, uid, ui_order, context=None):
return {
'name': ui_order['name'],
'user_id': ui_order['user_id'] or False,
'session_id': ui_order['pos_session_id'],
'lines': ui_order['lines'],
'pos_reference':ui_order['name'],
'partner_id': ui_order['partner_id'] or False,
}
def _payment_fields(self, cr, uid, ui_paymentline, context=None):
return {
'amount': ui_paymentline['amount'] or 0.0,
'payment_date': ui_paymentline['name'],
'statement_id': ui_paymentline['statement_id'],
'payment_name': ui_paymentline.get('note',False),
'journal': ui_paymentline['journal_id'],
}
def _process_order(self, cr, uid, order, context=None):
order_id = self.create(cr, uid, self._order_fields(cr, uid, order, context=context),context)
for payments in order['statement_ids']:
self.add_payment(cr, uid, order_id, self._payment_fields(cr, uid, payments[2], context=context), context=context)
session = self.pool.get('pos.session').browse(cr, uid, order['pos_session_id'], context=context)
if session.sequence_number <= order['sequence_number']:
session.write({'sequence_number': order['sequence_number'] + 1})
session.refresh()
if order['amount_return']:
cash_journal = session.cash_journal_id
if not cash_journal:
cash_journal_ids = filter(lambda st: st.journal_id.type=='cash', session.statement_ids)
if not len(cash_journal_ids):
raise osv.except_osv( _('error!'),
_("No cash statement found for this session. Unable to record returned cash."))
cash_journal = cash_journal_ids[0].journal_id
self.add_payment(cr, uid, order_id, {
'amount': -order['amount_return'],
'payment_date': time.strftime('%Y-%m-%d %H:%M:%S'),
'payment_name': _('return'),
'journal': cash_journal.id,
}, context=context)
return order_id
def create_from_ui(self, cr, uid, orders, context=None):
# Keep only new orders
submitted_references = [o['data']['name'] for o in orders]
existing_order_ids = self.search(cr, uid, [('pos_reference', 'in', submitted_references)], context=context)
existing_orders = self.read(cr, uid, existing_order_ids, ['pos_reference'], context=context)
existing_references = set([o['pos_reference'] for o in existing_orders])
orders_to_save = [o for o in orders if o['data']['name'] not in existing_references]
order_ids = []
for tmp_order in orders_to_save:
to_invoice = tmp_order['to_invoice']
order = tmp_order['data']
order_id = self._process_order(cr, uid, order, context=context)
order_ids.append(order_id)
try:
self.signal_workflow(cr, uid, [order_id], 'paid')
except Exception as e:
_logger.error('Could not fully process the POS Order: %s', tools.ustr(e))
if to_invoice:
self.action_invoice(cr, uid, [order_id], context)
order_obj = self.browse(cr, uid, order_id, context)
self.pool['account.invoice'].signal_workflow(cr, uid, [order_obj.invoice_id.id], 'invoice_open')
return order_ids
def write(self, cr, uid, ids, vals, context=None):
res = super(pos_order, self).write(cr, uid, ids, vals, context=context)
#If you change the partner of the PoS order, change also the partner of the associated bank statement lines
partner_obj = self.pool.get('res.partner')
bsl_obj = self.pool.get("account.bank.statement.line")
if 'partner_id' in vals:
for posorder in self.browse(cr, uid, ids, context=context):
if posorder.invoice_id:
raise osv.except_osv( _('Error!'), _("You cannot change the partner of a POS order for which an invoice has already been issued."))
if vals['partner_id']:
p_id = partner_obj.browse(cr, uid, vals['partner_id'], context=context)
part_id = partner_obj._find_accounting_partner(p_id).id
else:
part_id = False
bsl_ids = [x.id for x in posorder.statement_ids]
bsl_obj.write(cr, uid, bsl_ids, {'partner_id': part_id}, context=context)
return res
def unlink(self, cr, uid, ids, context=None):
for rec in self.browse(cr, uid, ids, context=context):
if rec.state not in ('draft','cancel'):
raise osv.except_osv(_('Unable to Delete!'), _('In order to delete a sale, it must be new or cancelled.'))
return super(pos_order, self).unlink(cr, uid, ids, context=context)
def onchange_partner_id(self, cr, uid, ids, part=False, context=None):
if not part:
return {'value': {}}
pricelist = self.pool.get('res.partner').browse(cr, uid, part, context=context).property_product_pricelist.id
return {'value': {'pricelist_id': pricelist}}
def _amount_all(self, cr, uid, ids, name, args, context=None):
cur_obj = self.pool.get('res.currency')
res = {}
for order in self.browse(cr, uid, ids, context=context):
res[order.id] = {
'amount_paid': 0.0,
'amount_return':0.0,
'amount_tax':0.0,
}
val1 = val2 = 0.0
cur = order.pricelist_id.currency_id
for payment in order.statement_ids:
res[order.id]['amount_paid'] += payment.amount
res[order.id]['amount_return'] += (payment.amount < 0 and payment.amount or 0)
for line in order.lines:
val1 += line.price_subtotal_incl
val2 += line.price_subtotal
res[order.id]['amount_tax'] = cur_obj.round(cr, uid, cur, val1-val2)
res[order.id]['amount_total'] = cur_obj.round(cr, uid, cur, val1)
return res
_columns = {
'name': fields.char('Order Ref', required=True, readonly=True, copy=False),
'company_id':fields.many2one('res.company', 'Company', required=True, readonly=True),
'date_order': fields.datetime('Order Date', readonly=True, select=True),
'user_id': fields.many2one('res.users', 'Salesman', help="Person who uses the the cash register. It can be a reliever, a student or an interim employee."),
'amount_tax': fields.function(_amount_all, string='Taxes', digits_compute=dp.get_precision('Account'), multi='all'),
'amount_total': fields.function(_amount_all, string='Total', digits_compute=dp.get_precision('Account'), multi='all'),
'amount_paid': fields.function(_amount_all, string='Paid', states={'draft': [('readonly', False)]}, readonly=True, digits_compute=dp.get_precision('Account'), multi='all'),
'amount_return': fields.function(_amount_all, 'Returned', digits_compute=dp.get_precision('Account'), multi='all'),
'lines': fields.one2many('pos.order.line', 'order_id', 'Order Lines', states={'draft': [('readonly', False)]}, readonly=True, copy=True),
'statement_ids': fields.one2many('account.bank.statement.line', 'pos_statement_id', 'Payments', states={'draft': [('readonly', False)]}, readonly=True),
'pricelist_id': fields.many2one('product.pricelist', 'Pricelist', required=True, states={'draft': [('readonly', False)]}, readonly=True),
'partner_id': fields.many2one('res.partner', 'Customer', change_default=True, select=1, states={'draft': [('readonly', False)], 'paid': [('readonly', False)]}),
'sequence_number': fields.integer('Sequence Number', help='A session-unique sequence number for the order'),
'session_id' : fields.many2one('pos.session', 'Session',
#required=True,
select=1,
domain="[('state', '=', 'opened')]",
states={'draft' : [('readonly', False)]},
readonly=True),
'state': fields.selection([('draft', 'New'),
('cancel', 'Cancelled'),
('paid', 'Paid'),
('done', 'Posted'),
('invoiced', 'Invoiced')],
'Status', readonly=True, copy=False),
'invoice_id': fields.many2one('account.invoice', 'Invoice', copy=False),
'account_move': fields.many2one('account.move', 'Journal Entry', readonly=True, copy=False),
'picking_id': fields.many2one('stock.picking', 'Picking', readonly=True, copy=False),
'picking_type_id': fields.related('session_id', 'config_id', 'picking_type_id', string="Picking Type", type='many2one', relation='stock.picking.type'),
'location_id': fields.related('session_id', 'config_id', 'stock_location_id', string="Location", type='many2one', store=True, relation='stock.location'),
'note': fields.text('Internal Notes'),
'nb_print': fields.integer('Number of Print', readonly=True, copy=False),
'pos_reference': fields.char('Receipt Ref', readonly=True, copy=False),
'sale_journal': fields.related('session_id', 'config_id', 'journal_id', relation='account.journal', type='many2one', string='Sale Journal', store=True, readonly=True),
}
def _default_session(self, cr, uid, context=None):
so = self.pool.get('pos.session')
session_ids = so.search(cr, uid, [('state','=', 'opened'), ('user_id','=',uid)], context=context)
return session_ids and session_ids[0] or False
def _default_pricelist(self, cr, uid, context=None):
session_ids = self._default_session(cr, uid, context)
if session_ids:
session_record = self.pool.get('pos.session').browse(cr, uid, session_ids, context=context)
return session_record.config_id.pricelist_id and session_record.config_id.pricelist_id.id or False
return False
def _get_out_picking_type(self, cr, uid, context=None):
return self.pool.get('ir.model.data').xmlid_to_res_id(
cr, uid, 'point_of_sale.picking_type_posout', context=context)
_defaults = {
'user_id': lambda self, cr, uid, context: uid,
'state': 'draft',
'name': '/',
'date_order': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
'nb_print': 0,
'sequence_number': 1,
'session_id': _default_session,
'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
'pricelist_id': _default_pricelist,
}
def create(self, cr, uid, values, context=None):
if values.get('session_id'):
# set name based on the sequence specified on the config
session = self.pool['pos.session'].browse(cr, uid, values['session_id'], context=context)
values['name'] = session.config_id.sequence_id._next()
else:
# fallback on any pos.order sequence
values['name'] = self.pool.get('ir.sequence').get_id(cr, uid, 'pos.order', 'code', context=context)
return super(pos_order, self).create(cr, uid, values, context=context)
def test_paid(self, cr, uid, ids, context=None):
"""A Point of Sale is paid when the sum
@return: True
"""
for order in self.browse(cr, uid, ids, context=context):
if order.lines and not order.amount_total:
return True
if (not order.lines) or (not order.statement_ids) or \
(abs(order.amount_total-order.amount_paid) > 0.00001):
return False
return True
def create_picking(self, cr, uid, ids, context=None):
"""Create a picking for each order and validate it."""
picking_obj = self.pool.get('stock.picking')
partner_obj = self.pool.get('res.partner')
move_obj = self.pool.get('stock.move')
for order in self.browse(cr, uid, ids, context=context):
addr = order.partner_id and partner_obj.address_get(cr, uid, [order.partner_id.id], ['delivery']) or {}
picking_type = order.picking_type_id
picking_id = False
if picking_type:
picking_id = picking_obj.create(cr, uid, {
'origin': order.name,
'partner_id': addr.get('delivery',False),
'picking_type_id': picking_type.id,
'company_id': order.company_id.id,
'move_type': 'direct',
'note': order.note or "",
'invoice_state': 'none',
}, context=context)
self.write(cr, uid, [order.id], {'picking_id': picking_id}, context=context)
location_id = order.location_id.id
if order.partner_id:
destination_id = order.partner_id.property_stock_customer.id
elif picking_type:
if not picking_type.default_location_dest_id:
raise osv.except_osv(_('Error!'), _('Missing source or destination location for picking type %s. Please configure those fields and try again.' % (picking_type.name,)))
destination_id = picking_type.default_location_dest_id.id
else:
destination_id = partner_obj.default_get(cr, uid, ['property_stock_customer'], context=context)['property_stock_customer']
move_list = []
for line in order.lines:
if line.product_id and line.product_id.type == 'service':
continue
move_list.append(move_obj.create(cr, uid, {
'name': line.name,
'product_uom': line.product_id.uom_id.id,
'product_uos': line.product_id.uom_id.id,
'picking_id': picking_id,
'picking_type_id': picking_type.id,
'product_id': line.product_id.id,
'product_uos_qty': abs(line.qty),
'product_uom_qty': abs(line.qty),
'state': 'draft',
'location_id': location_id if line.qty >= 0 else destination_id,
'location_dest_id': destination_id if line.qty >= 0 else location_id,
}, context=context))
if picking_id:
picking_obj.action_confirm(cr, uid, [picking_id], context=context)
picking_obj.force_assign(cr, uid, [picking_id], context=context)
picking_obj.action_done(cr, uid, [picking_id], context=context)
elif move_list:
move_obj.action_confirm(cr, uid, move_list, context=context)
move_obj.force_assign(cr, uid, move_list, context=context)
move_obj.action_done(cr, uid, move_list, context=context)
return True
def cancel_order(self, cr, uid, ids, context=None):
""" Changes order state to cancel
@return: True
"""
stock_picking_obj = self.pool.get('stock.picking')
for order in self.browse(cr, uid, ids, context=context):
stock_picking_obj.action_cancel(cr, uid, [order.picking_id.id])
if stock_picking_obj.browse(cr, uid, order.picking_id.id, context=context).state <> 'cancel':
raise osv.except_osv(_('Error!'), _('Unable to cancel the picking.'))
self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
return True
def add_payment(self, cr, uid, order_id, data, context=None):
"""Create a new payment for the order"""
context = dict(context or {})
statement_line_obj = self.pool.get('account.bank.statement.line')
property_obj = self.pool.get('ir.property')
order = self.browse(cr, uid, order_id, context=context)
args = {
'amount': data['amount'],
'date': data.get('payment_date', time.strftime('%Y-%m-%d')),
'name': order.name + ': ' + (data.get('payment_name', '') or ''),
'partner_id': order.partner_id and self.pool.get("res.partner")._find_accounting_partner(order.partner_id).id or False,
}
journal_id = data.get('journal', False)
statement_id = data.get('statement_id', False)
assert journal_id or statement_id, "No statement_id or journal_id passed to the method!"
journal = self.pool['account.journal'].browse(cr, uid, journal_id, context=context)
# use the company of the journal and not of the current user
company_cxt = dict(context, force_company=journal.company_id.id)
account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=company_cxt)
args['account_id'] = (order.partner_id and order.partner_id.property_account_receivable \
and order.partner_id.property_account_receivable.id) or (account_def and account_def.id) or False
if not args['account_id']:
if not args['partner_id']:
msg = _('There is no receivable account defined to make payment.')
else:
msg = _('There is no receivable account defined to make payment for the partner: "%s" (id:%d).') % (order.partner_id.name, order.partner_id.id,)
raise osv.except_osv(_('Configuration Error!'), msg)
context.pop('pos_session_id', False)
for statement in order.session_id.statement_ids:
if statement.id == statement_id:
journal_id = statement.journal_id.id
break
elif statement.journal_id.id == journal_id:
statement_id = statement.id
break
if not statement_id:
raise osv.except_osv(_('Error!'), _('You have to open at least one cashbox.'))
args.update({
'statement_id': statement_id,
'pos_statement_id': order_id,
'journal_id': journal_id,
'ref': order.session_id.name,
})
statement_line_obj.create(cr, uid, args, context=context)
return statement_id
def refund(self, cr, uid, ids, context=None):
"""Create a copy of order for refund order"""
clone_list = []
line_obj = self.pool.get('pos.order.line')
for order in self.browse(cr, uid, ids, context=context):
current_session_ids = self.pool.get('pos.session').search(cr, uid, [
('state', '!=', 'closed'),
('user_id', '=', uid)], context=context)
if not current_session_ids:
raise osv.except_osv(_('Error!'), _('To return product(s), you need to open a session that will be used to register the refund.'))
clone_id = self.copy(cr, uid, order.id, {
'name': order.name + ' REFUND', # not used, name forced by create
'session_id': current_session_ids[0],
'date_order': time.strftime('%Y-%m-%d %H:%M:%S'),
}, context=context)
clone_list.append(clone_id)
for clone in self.browse(cr, uid, clone_list, context=context):
for order_line in clone.lines:
line_obj.write(cr, uid, [order_line.id], {
'qty': -order_line.qty
}, context=context)
abs = {
'name': _('Return Products'),
'view_type': 'form',
'view_mode': 'form',
'res_model': 'pos.order',
'res_id':clone_list[0],
'view_id': False,
'context':context,
'type': 'ir.actions.act_window',
'nodestroy': True,
'target': 'current',
}
return abs
def action_invoice_state(self, cr, uid, ids, context=None):
return self.write(cr, uid, ids, {'state':'invoiced'}, context=context)
def action_invoice(self, cr, uid, ids, context=None):
inv_ref = self.pool.get('account.invoice')
inv_line_ref = self.pool.get('account.invoice.line')
product_obj = self.pool.get('product.product')
inv_ids = []
for order in self.pool.get('pos.order').browse(cr, uid, ids, context=context):
if order.invoice_id:
inv_ids.append(order.invoice_id.id)
continue
if not order.partner_id:
raise osv.except_osv(_('Error!'), _('Please provide a partner for the sale.'))
acc = order.partner_id.property_account_receivable.id
inv = {
'name': order.name,
'origin': order.name,
'account_id': acc,
'journal_id': order.sale_journal.id or None,
'type': 'out_invoice',
'reference': order.name,
'partner_id': order.partner_id.id,
'comment': order.note or '',
'currency_id': order.pricelist_id.currency_id.id, # considering partner's sale pricelist's currency
}
inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
if not inv.get('account_id', None):
inv['account_id'] = acc
inv_id = inv_ref.create(cr, uid, inv, context=context)
self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'}, context=context)
inv_ids.append(inv_id)
for line in order.lines:
inv_line = {
'invoice_id': inv_id,
'product_id': line.product_id.id,
'quantity': line.qty,
}
inv_name = product_obj.name_get(cr, uid, [line.product_id.id], context=context)[0][1]
inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
line.product_id.id,
line.product_id.uom_id.id,
line.qty, partner_id = order.partner_id.id,
fposition_id=order.partner_id.property_account_position.id)['value'])
inv_line['price_unit'] = line.price_unit
inv_line['discount'] = line.discount
inv_line['name'] = inv_name
inv_line['invoice_line_tax_id'] = [(6, 0, [x.id for x in line.product_id.taxes_id] )]
inv_line_ref.create(cr, uid, inv_line, context=context)
inv_ref.button_reset_taxes(cr, uid, [inv_id], context=context)
self.signal_workflow(cr, uid, [order.id], 'invoice')
inv_ref.signal_workflow(cr, uid, [inv_id], 'validate')
if not inv_ids: return {}
mod_obj = self.pool.get('ir.model.data')
res = mod_obj.get_object_reference(cr, uid, 'account', 'invoice_form')
res_id = res and res[1] or False
return {
'name': _('Customer Invoice'),
'view_type': 'form',
'view_mode': 'form',
'view_id': [res_id],
'res_model': 'account.invoice',
'context': "{'type':'out_invoice'}",
'type': 'ir.actions.act_window',
'nodestroy': True,
'target': 'current',
'res_id': inv_ids and inv_ids[0] or False,
}
def create_account_move(self, cr, uid, ids, context=None):
return self._create_account_move_line(cr, uid, ids, None, None, context=context)
def _prepare_analytic_account(self, cr, uid, line, context=None):
'''This method is designed to be inherited in a custom module'''
return False
def _create_account_move_line(self, cr, uid, ids, session=None, move_id=None, context=None):
# Tricky, via the workflow, we only have one id in the ids variable
"""Create a account move line of order grouped by products or not."""
account_move_obj = self.pool.get('account.move')
account_period_obj = self.pool.get('account.period')
account_tax_obj = self.pool.get('account.tax')
property_obj = self.pool.get('ir.property')
cur_obj = self.pool.get('res.currency')
#session_ids = set(order.session_id for order in self.browse(cr, uid, ids, context=context))
if session and not all(session.id == order.session_id.id for order in self.browse(cr, uid, ids, context=context)):
raise osv.except_osv(_('Error!'), _('Selected orders do not have the same session!'))
grouped_data = {}
have_to_group_by = session and session.config_id.group_by or False
def compute_tax(amount, tax, line):
if amount > 0:
tax_code_id = tax['base_code_id']
tax_amount = line.price_subtotal * tax['base_sign']
else:
tax_code_id = tax['ref_base_code_id']
tax_amount = line.price_subtotal * tax['ref_base_sign']
return (tax_code_id, tax_amount,)
for order in self.browse(cr, uid, ids, context=context):
if order.account_move:
continue
if order.state != 'paid':
continue
current_company = order.sale_journal.company_id
group_tax = {}
account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context)
order_account = order.partner_id and \
order.partner_id.property_account_receivable and \
order.partner_id.property_account_receivable.id or \
account_def and account_def.id or current_company.account_receivable.id
if move_id is None:
# Create an entry for the sale
move_id = account_move_obj.create(cr, uid, {
'ref' : order.name,
'journal_id': order.sale_journal.id,
}, context=context)
def insert_data(data_type, values):
# if have_to_group_by:
sale_journal_id = order.sale_journal.id
period = account_period_obj.find(cr, uid, context=dict(context or {}, company_id=current_company.id))[0]
# 'quantity': line.qty,
# 'product_id': line.product_id.id,
values.update({
'date': order.date_order[:10],
'ref': order.name,
'partner_id': order.partner_id and self.pool.get("res.partner")._find_accounting_partner(order.partner_id).id or False,
'journal_id' : sale_journal_id,
'period_id' : period,
'move_id' : move_id,
'company_id': current_company.id,
})
if data_type == 'product':
key = ('product', values['partner_id'], values['product_id'], values['analytic_account_id'], values['debit'] > 0)
elif data_type == 'tax':
key = ('tax', values['partner_id'], values['tax_code_id'], values['debit'] > 0)
elif data_type == 'counter_part':
key = ('counter_part', values['partner_id'], values['account_id'], values['debit'] > 0)
else:
return
grouped_data.setdefault(key, [])
# if not have_to_group_by or (not grouped_data[key]):
# grouped_data[key].append(values)
# else:
# pass
if have_to_group_by:
if not grouped_data[key]:
grouped_data[key].append(values)
else:
current_value = grouped_data[key][0]
current_value['quantity'] = current_value.get('quantity', 0.0) + values.get('quantity', 0.0)
current_value['credit'] = current_value.get('credit', 0.0) + values.get('credit', 0.0)
current_value['debit'] = current_value.get('debit', 0.0) + values.get('debit', 0.0)
current_value['tax_amount'] = current_value.get('tax_amount', 0.0) + values.get('tax_amount', 0.0)
else:
grouped_data[key].append(values)
#because of the weird way the pos order is written, we need to make sure there is at least one line,
#because just after the 'for' loop there are references to 'line' and 'income_account' variables (that
#are set inside the for loop)
#TOFIX: a deep refactoring of this method (and class!) is needed in order to get rid of this stupid hack
assert order.lines, _('The POS order must have lines when calling this method')
# Create an move for each order line
cur = order.pricelist_id.currency_id
for line in order.lines:
tax_amount = 0
taxes = []
for t in line.product_id.taxes_id:
if t.company_id.id == current_company.id:
taxes.append(t)
computed_taxes = account_tax_obj.compute_all(cr, uid, taxes, line.price_unit * (100.0-line.discount) / 100.0, line.qty)['taxes']
for tax in computed_taxes:
tax_amount += cur_obj.round(cr, uid, cur, tax['amount'])
group_key = (tax['tax_code_id'], tax['base_code_id'], tax['account_collected_id'], tax['id'])
group_tax.setdefault(group_key, 0)
group_tax[group_key] += cur_obj.round(cr, uid, cur, tax['amount'])
amount = line.price_subtotal
# Search for the income account
if line.product_id.property_account_income.id:
income_account = line.product_id.property_account_income.id
elif line.product_id.categ_id.property_account_income_categ.id:
income_account = line.product_id.categ_id.property_account_income_categ.id
else:
raise osv.except_osv(_('Error!'), _('Please define income '\
'account for this product: "%s" (id:%d).') \
% (line.product_id.name, line.product_id.id, ))
# Empty the tax list as long as there is no tax code:
tax_code_id = False
tax_amount = 0
while computed_taxes:
tax = computed_taxes.pop(0)
tax_code_id, tax_amount = compute_tax(amount, tax, line)
# If there is one we stop
if tax_code_id:
break
# Create a move for the line
insert_data('product', {
'name': line.product_id.name,
'quantity': line.qty,
'product_id': line.product_id.id,
'account_id': income_account,
'analytic_account_id': self._prepare_analytic_account(cr, uid, line, context=context),
'credit': ((amount>0) and amount) or 0.0,
'debit': ((amount<0) and -amount) or 0.0,
'tax_code_id': tax_code_id,
'tax_amount': tax_amount,
'partner_id': order.partner_id and self.pool.get("res.partner")._find_accounting_partner(order.partner_id).id or False
})
# For each remaining tax with a code, whe create a move line
for tax in computed_taxes:
tax_code_id, tax_amount = compute_tax(amount, tax, line)
if not tax_code_id:
continue
insert_data('tax', {
'name': _('Tax'),
'product_id':line.product_id.id,
'quantity': line.qty,
'account_id': income_account,
'credit': 0.0,
'debit': 0.0,
'tax_code_id': tax_code_id,
'tax_amount': tax_amount,
'partner_id': order.partner_id and self.pool.get("res.partner")._find_accounting_partner(order.partner_id).id or False
})
# Create a move for each tax group
(tax_code_pos, base_code_pos, account_pos, tax_id)= (0, 1, 2, 3)
for key, tax_amount in group_tax.items():
tax = self.pool.get('account.tax').browse(cr, uid, key[tax_id], context=context)
insert_data('tax', {
'name': _('Tax') + ' ' + tax.name,
'quantity': line.qty,
'product_id': line.product_id.id,
'account_id': key[account_pos] or income_account,
'credit': ((tax_amount>0) and tax_amount) or 0.0,
'debit': ((tax_amount<0) and -tax_amount) or 0.0,
'tax_code_id': key[tax_code_pos],
'tax_amount': tax_amount,
'partner_id': order.partner_id and self.pool.get("res.partner")._find_accounting_partner(order.partner_id).id or False
})
# counterpart
insert_data('counter_part', {
'name': _("Trade Receivables"), #order.name,
'account_id': order_account,
'credit': ((order.amount_total < 0) and -order.amount_total) or 0.0,
'debit': ((order.amount_total > 0) and order.amount_total) or 0.0,
'partner_id': order.partner_id and self.pool.get("res.partner")._find_accounting_partner(order.partner_id).id or False
})
order.write({'state':'done', 'account_move': move_id})
all_lines = []
for group_key, group_data in grouped_data.iteritems():
for value in group_data:
all_lines.append((0, 0, value),)
if move_id: #In case no order was changed
self.pool.get("account.move").write(cr, uid, [move_id], {'line_id':all_lines}, context=context)
return True
def action_payment(self, cr, uid, ids, context=None):
return self.write(cr, uid, ids, {'state': 'payment'}, context=context)
def action_paid(self, cr, uid, ids, context=None):
self.write(cr, uid, ids, {'state': 'paid'}, context=context)
self.create_picking(cr, uid, ids, context=context)
return True
def action_cancel(self, cr, uid, ids, context=None):
self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
return True
def action_done(self, cr, uid, ids, context=None):
self.create_account_move(cr, uid, ids, context=context)
return True
class account_bank_statement(osv.osv):
_inherit = 'account.bank.statement'
_columns= {
'user_id': fields.many2one('res.users', 'User', readonly=True),
}
_defaults = {
'user_id': lambda self,cr,uid,c={}: uid
}
class account_bank_statement_line(osv.osv):
_inherit = 'account.bank.statement.line'
_columns= {
'pos_statement_id': fields.many2one('pos.order', ondelete='cascade'),
}
class pos_order_line(osv.osv):
_name = "pos.order.line"
_description = "Lines of Point of Sale"
_rec_name = "product_id"
def _amount_line_all(self, cr, uid, ids, field_names, arg, context=None):
res = dict([(i, {}) for i in ids])
account_tax_obj = self.pool.get('account.tax')
cur_obj = self.pool.get('res.currency')
for line in self.browse(cr, uid, ids, context=context):
taxes_ids = [ tax for tax in line.product_id.taxes_id if tax.company_id.id == line.order_id.company_id.id ]
price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
taxes = account_tax_obj.compute_all(cr, uid, taxes_ids, price, line.qty, product=line.product_id, partner=line.order_id.partner_id or False)
cur = line.order_id.pricelist_id.currency_id
res[line.id]['price_subtotal'] = cur_obj.round(cr, uid, cur, taxes['total'])
res[line.id]['price_subtotal_incl'] = cur_obj.round(cr, uid, cur, taxes['total_included'])
return res
def onchange_product_id(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False, context=None):
context = context or {}
if not product_id:
return {}
if not pricelist:
raise osv.except_osv(_('No Pricelist!'),
_('You have to select a pricelist in the sale form !\n' \
'Please set one before choosing a product.'))
price = self.pool.get('product.pricelist').price_get(cr, uid, [pricelist],
product_id, qty or 1.0, partner_id)[pricelist]
result = self.onchange_qty(cr, uid, ids, product_id, 0.0, qty, price, context=context)
result['value']['price_unit'] = price
return result
def onchange_qty(self, cr, uid, ids, product, discount, qty, price_unit, context=None):
result = {}
if not product:
return result
account_tax_obj = self.pool.get('account.tax')
cur_obj = self.pool.get('res.currency')
prod = self.pool.get('product.product').browse(cr, uid, product, context=context)
price = price_unit * (1 - (discount or 0.0) / 100.0)
taxes = account_tax_obj.compute_all(cr, uid, prod.taxes_id, price, qty, product=prod, partner=False)
result['price_subtotal'] = taxes['total']
result['price_subtotal_incl'] = taxes['total_included']
return {'value': result}
_columns = {
'company_id': fields.many2one('res.company', 'Company', required=True),
'name': fields.char('Line No', required=True, copy=False),
'notice': fields.char('Discount Notice'),
'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], required=True, change_default=True),
'price_unit': fields.float(string='Unit Price', digits_compute=dp.get_precision('Account')),
'qty': fields.float('Quantity', digits_compute=dp.get_precision('Product UoS')),
'price_subtotal': fields.function(_amount_line_all, multi='pos_order_line_amount', digits_compute=dp.get_precision('Account'), string='Subtotal w/o Tax', store=True),
'price_subtotal_incl': fields.function(_amount_line_all, multi='pos_order_line_amount', digits_compute=dp.get_precision('Account'), string='Subtotal', store=True),
'discount': fields.float('Discount (%)', digits_compute=dp.get_precision('Account')),
'order_id': fields.many2one('pos.order', 'Order Ref', ondelete='cascade'),
'create_date': fields.datetime('Creation Date', readonly=True),
}
_defaults = {
'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order.line'),
'qty': lambda *a: 1,
'discount': lambda *a: 0.0,
'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
}
class ean_wizard(osv.osv_memory):
_name = 'pos.ean_wizard'
_columns = {
'ean13_pattern': fields.char('Reference', size=13, required=True, translate=True),
}
def sanitize_ean13(self, cr, uid, ids, context):
for r in self.browse(cr,uid,ids):
ean13 = openerp.addons.product.product.sanitize_ean13(r.ean13_pattern)
m = context.get('active_model')
m_id = context.get('active_id')
self.pool[m].write(cr,uid,[m_id],{'ean13':ean13})
return { 'type' : 'ir.actions.act_window_close' }
class pos_category(osv.osv):
_name = "pos.category"
_description = "Public Category"
_order = "sequence, name"
_constraints = [
(osv.osv._check_recursion, 'Error ! You cannot create recursive categories.', ['parent_id'])
]
def name_get(self, cr, uid, ids, context=None):
res = []
for cat in self.browse(cr, uid, ids, context=context):
names = [cat.name]
pcat = cat.parent_id
while pcat:
names.append(pcat.name)
pcat = pcat.parent_id
res.append((cat.id, ' / '.join(reversed(names))))
return res
def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
res = self.name_get(cr, uid, ids, context=context)
return dict(res)
def _get_image(self, cr, uid, ids, name, args, context=None):
result = dict.fromkeys(ids, False)
for obj in self.browse(cr, uid, ids, context=context):
result[obj.id] = tools.image_get_resized_images(obj.image)
return result
def _set_image(self, cr, uid, id, name, value, args, context=None):
return self.write(cr, uid, [id], {'image': tools.image_resize_image_big(value)}, context=context)
_columns = {
'name': fields.char('Name', required=True, translate=True),
'complete_name': fields.function(_name_get_fnc, type="char", string='Name'),
'parent_id': fields.many2one('pos.category','Parent Category', select=True),
'child_id': fields.one2many('pos.category', 'parent_id', string='Children Categories'),
'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of product categories."),
# NOTE: there is no 'default image', because by default we don't show thumbnails for categories. However if we have a thumbnail
# for at least one category, then we display a default image on the other, so that the buttons have consistent styling.
# In this case, the default image is set by the js code.
# NOTE2: image: all image fields are base64 encoded and PIL-supported
'image': fields.binary("Image",
help="This field holds the image used as image for the cateogry, limited to 1024x1024px."),
'image_medium': fields.function(_get_image, fnct_inv=_set_image,
string="Medium-sized image", type="binary", multi="_get_image",
store={
'pos.category': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
},
help="Medium-sized image of the category. It is automatically "\
"resized as a 128x128px image, with aspect ratio preserved. "\
"Use this field in form views or some kanban views."),
'image_small': fields.function(_get_image, fnct_inv=_set_image,
string="Smal-sized image", type="binary", multi="_get_image",
store={
'pos.category': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
},
help="Small-sized image of the category. It is automatically "\
"resized as a 64x64px image, with aspect ratio preserved. "\
"Use this field anywhere a small image is required."),
}
class product_template(osv.osv):
_inherit = 'product.template'
_columns = {
'income_pdt': fields.boolean('Point of Sale Cash In', help="Check if, this is a product you can use to put cash into a statement for the point of sale backend."),
'expense_pdt': fields.boolean('Point of Sale Cash Out', help="Check if, this is a product you can use to take cash from a statement for the point of sale backend, example: money lost, transfer to bank, etc."),
'available_in_pos': fields.boolean('Available in the Point of Sale', help='Check if you want this product to appear in the Point of Sale'),
'to_weight' : fields.boolean('To Weigh With Scale', help="Check if the product should be weighted using the hardware scale integration"),
'pos_categ_id': fields.many2one('pos.category','Point of Sale Category', help="Those categories are used to group similar products for point of sale."),
}
_defaults = {
'to_weight' : False,
'available_in_pos': True,
}
def unlink(self, cr, uid, ids, context=None):
product_ctx = dict(context or {}, active_test=False)
if self.search_count(cr, uid, [('id', 'in', ids), ('available_in_pos', '=', True)], context=product_ctx):
if self.pool['pos.session'].search_count(cr, uid, [('state', '!=', 'closed')], context=context):
raise osv.except_osv(_('Error!'),
_('You cannot delete a product saleable in point of sale while a session is still opened.'))
return super(product_template, self).unlink(cr, uid, ids, context=context)
class res_partner(osv.osv):
_inherit = 'res.partner'
def create_from_ui(self, cr, uid, partner, context=None):
""" create or modify a partner from the point of sale ui.
partner contains the partner's fields. """
#image is a dataurl, get the data after the comma
if partner.get('image',False):
img = partner['image'].split(',')[1]
partner['image'] = img
if partner.get('id',False): # Modifying existing partner
partner_id = partner['id']
del partner['id']
self.write(cr, uid, [partner_id], partner, context=context)
else:
partner_id = self.create(cr, uid, partner, context=context)
return partner_id
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
patriciolobos/desa8
|
openerp/addons/point_of_sale/point_of_sale.py
|
Python
|
agpl-3.0
| 74,430
|
# ***************************************************************************
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
"""Provides functions to create multipoint Wire objects."""
## @package make_wire
# \ingroup draftmake
# \brief Provides functions to create multipoint Wire objects.
## \addtogroup draftmake
# @{
import FreeCAD as App
import DraftGeomUtils
import draftutils.utils as utils
import draftutils.gui_utils as gui_utils
from draftobjects.wire import Wire
if App.GuiUp:
from draftviewproviders.view_wire import ViewProviderWire
def make_wire(pointslist, closed=False, placement=None, face=None, support=None, bs2wire=False):
"""makeWire(pointslist,[closed],[placement])
Creates a Wire object from the given list of vectors. If face is
true (and wire is closed), the wire will appear filled. Instead of
a pointslist, you can also pass a Part Wire.
Parameters
----------
pointslist : [Base.Vector]
List of points to create the polyline
closed : bool
If closed is True or first and last points are identical,
the created polyline will be closed.
placement : Base.Placement
If a placement is given, it is used.
face : Bool
If face is False, the rectangle is shown as a wireframe,
otherwise as a face.
support :
TODO: Describe
bs2wire : bool
TODO: Describe
"""
if not App.ActiveDocument:
App.Console.PrintError("No active document. Aborting\n")
return None
import Part
if isinstance(pointslist, (list,tuple)):
for pnt in pointslist:
if not isinstance(pnt, App.Vector):
App.Console.PrintError(
"Items must be Base.Vector objects, not {}\n".format(
type(pnt)))
return None
elif isinstance(pointslist, Part.Wire):
for edge in pointslist.Edges:
if not DraftGeomUtils.is_straight_line(edge):
App.Console.PrintError("All edges must be straight lines\n")
return None
closed = pointslist.isClosed()
pointslist = [v.Point for v in pointslist.OrderedVertexes]
else:
App.Console.PrintError("Can't make Draft Wire from {}\n".format(
type(pointslist)))
return None
if len(pointslist) == 0:
App.Console.PrintWarning("Draft Wire created with empty point list\n")
if placement:
utils.type_check([(placement, App.Placement)], "make_wire")
ipl = placement.inverse()
if not bs2wire:
pointslist = [ipl.multVec(p) for p in pointslist]
if len(pointslist) == 2:
fname = "Line"
else:
fname = "Wire"
obj = App.ActiveDocument.addObject("Part::Part2DObjectPython", fname)
Wire(obj)
obj.Points = pointslist
obj.Closed = closed
obj.Support = support
if face != None:
obj.MakeFace = face
if placement:
obj.Placement = placement
if App.GuiUp:
ViewProviderWire(obj.ViewObject)
gui_utils.format_object(obj)
gui_utils.select(obj)
return obj
makeWire = make_wire
## @}
|
sanguinariojoe/FreeCAD
|
src/Mod/Draft/draftmake/make_wire.py
|
Python
|
lgpl-2.1
| 4,714
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-05 20:20
from __future__ import unicode_literals
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('osf', '0035_metaschema_active'),
]
operations = [
migrations.RemoveField(
model_name='preprintprovider',
name='banner_name',
),
migrations.RemoveField(
model_name='preprintprovider',
name='header_text',
),
migrations.RemoveField(
model_name='preprintprovider',
name='logo_name',
),
migrations.AddField(
model_name='preprintprovider',
name='additional_providers',
field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=200), blank=True, default=list, size=None),
),
migrations.AddField(
model_name='preprintprovider',
name='allow_submissions',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='preprintprovider',
name='footer_links',
field=models.TextField(blank=True, default=''),
),
migrations.AlterField(
model_name='preprintprovider',
name='advisory_board',
field=models.TextField(blank=True, default=''),
),
migrations.AlterField(
model_name='preprintprovider',
name='description',
field=models.TextField(blank=True, default=''),
),
]
|
mfraezz/osf.io
|
osf/migrations/0036_auto_20170605_1520.py
|
Python
|
apache-2.0
| 1,657
|
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Data import *
from QuantConnect.Data.Market import *
from QuantConnect.Interfaces import *
from QuantConnect.Securities import *
from QuantConnect.Securities.Interfaces import *
class TickDataFilteringAlgorithm(QCAlgorithm):
'''Tick Filter Example'''
def Initialize(self):
'''Initialize the tick filtering example algorithm'''
self.SetStartDate(2013,10,07) #Set Start Date
self.SetEndDate(2013,10,11) #Set End Date
self.SetCash(25000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.AddSecurity(SecurityType.Equity, "SPY", Resolution.Tick)
# Add our custom data filter.
self.Securities["SPY"].DataFilter = ExchangeDataFilter(self)
def OnData(self, data):
'''Data arriving here will now be filtered.
Arguments:
data: Ticks data array
'''
if not data.ContainsKey("SPY"): return
spyTickList = data["SPY"]
#Ticks return a list of ticks this second
for tick in spyTickList:
self.Log(tick.Exchange)
if not self.Portfolio.Invested:
self.SetHoldings("SPY", 1)
class ExchangeDataFilter(ISecurityDataFilter):
'''Exchange filter class'''
def __init__(self, algo):
'''Save instance of the algorithm namespace'''
self.__algo = algo
def Filter(self, asset, data):
'''Filter out a tick from this vehicle, with this new data:
Arguments:
data: New data packet
asset: Vehicle of this filter.
Returns:
TRUE: Accept Tick
FALSE: Reject Tick
'''
return type(data) == Tick and data.Exchange == "P"
|
mabeale/Lean
|
Algorithm.Python/TickDataFilteringAlgorithm.py
|
Python
|
apache-2.0
| 2,658
|
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module for a class that contains a request body resource and parameters."""
from protorpc import message_types
from protorpc import messages
class ResourceContainer(object):
"""Container for a request body resource combined with parameters.
Used for API methods which may also have path or query parameters in addition
to a request body.
Attributes:
body_message_class: A message class to represent a request body.
parameters_message_class: A placeholder message class for request
parameters.
"""
__remote_info_cache = {} # pylint: disable=g-bad-name
__combined_message_class = None # pylint: disable=invalid-name
def __init__(self, _body_message_class=message_types.VoidMessage, **kwargs):
"""Constructor for ResourceContainer.
Stores a request body message class and attempts to create one from the
keyword arguments passed in.
Args:
_body_message_class: A keyword argument to be treated like a positional
argument. This will not conflict with the potential names of fields
since they can't begin with underscore. We make this a keyword
argument since the default VoidMessage is a very common choice given
the prevalence of GET methods.
**kwargs: Keyword arguments specifying field names (the named arguments)
and instances of ProtoRPC fields as the values.
"""
self.body_message_class = _body_message_class
self.parameters_message_class = type('ParameterContainer',
(messages.Message,), kwargs)
@property
def combined_message_class(self):
"""A ProtoRPC message class with both request and parameters fields.
Caches the result in a local private variable. Uses _CopyField to create
copies of the fields from the existing request and parameters classes since
those fields are "owned" by the message classes.
Raises:
TypeError: If a field name is used in both the request message and the
parameters but the two fields do not represent the same type.
Returns:
Value of combined message class for this property.
"""
if self.__combined_message_class is not None:
return self.__combined_message_class
fields = {}
# We don't need to preserve field.number since this combined class is only
# used for the protorpc remote.method and is not needed for the API config.
# The only place field.number matters is in parameterOrder, but this is set
# based on container.parameters_message_class which will use the field
# numbers originally passed in.
# Counter for fields.
field_number = 1
for field in self.body_message_class.all_fields():
fields[field.name] = _CopyField(field, number=field_number)
field_number += 1
for field in self.parameters_message_class.all_fields():
if field.name in fields:
if not _CompareFields(field, fields[field.name]):
raise TypeError('Field %r contained in both parameters and request '
'body, but the fields differ.' % (field.name,))
else:
# Skip a field that's already there.
continue
fields[field.name] = _CopyField(field, number=field_number)
field_number += 1
self.__combined_message_class = type('CombinedContainer',
(messages.Message,), fields)
return self.__combined_message_class
@classmethod
def add_to_cache(cls, remote_info, container): # pylint: disable=g-bad-name
"""Adds a ResourceContainer to a cache tying it to a protorpc method.
Args:
remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding
to a method.
container: An instance of ResourceContainer.
Raises:
TypeError: if the container is not an instance of cls.
KeyError: if the remote method has been reference by a container before.
This created remote method should never occur because a remote method
is created once.
"""
if not isinstance(container, cls):
raise TypeError('%r not an instance of %r, could not be added to cache.' %
(container, cls))
if remote_info in cls.__remote_info_cache:
raise KeyError('Cache has collision but should not.')
cls.__remote_info_cache[remote_info] = container
@classmethod
def get_request_message(cls, remote_info): # pylint: disable=g-bad-name
"""Gets request message or container from remote info.
Args:
remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding
to a method.
Returns:
Either an instance of the request type from the remote or the
ResourceContainer that was cached with the remote method.
"""
if remote_info in cls.__remote_info_cache:
return cls.__remote_info_cache[remote_info]
else:
return remote_info.request_type()
def _GetFieldAttributes(field):
"""Decomposes field into the needed arguments to pass to the constructor.
This can be used to create copies of the field or to compare if two fields
are "equal" (since __eq__ is not implemented on messages.Field).
Args:
field: A ProtoRPC message field (potentially to be copied).
Raises:
TypeError: If the field is not an instance of messages.Field.
Returns:
A pair of relevant arguments to be passed to the constructor for the field
type. The first element is a list of positional arguments for the
constructor and the second is a dictionary of keyword arguments.
"""
if not isinstance(field, messages.Field):
raise TypeError('Field %r to be copied not a ProtoRPC field.' % (field,))
positional_args = []
kwargs = {
'required': field.required,
'repeated': field.repeated,
'variant': field.variant,
'default': field._Field__default, # pylint: disable=protected-access
}
if isinstance(field, messages.MessageField):
# Message fields can't have a default
kwargs.pop('default')
if not isinstance(field, message_types.DateTimeField):
positional_args.insert(0, field.message_type)
elif isinstance(field, messages.EnumField):
positional_args.insert(0, field.type)
return positional_args, kwargs
def _CompareFields(field, other_field):
"""Checks if two ProtoRPC fields are "equal".
Compares the arguments, rather than the id of the elements (which is
the default __eq__ behavior) as well as the class of the fields.
Args:
field: A ProtoRPC message field to be compared.
other_field: A ProtoRPC message field to be compared.
Returns:
Boolean indicating whether the fields are equal.
"""
field_attrs = _GetFieldAttributes(field)
other_field_attrs = _GetFieldAttributes(other_field)
if field_attrs != other_field_attrs:
return False
return field.__class__ == other_field.__class__
def _CopyField(field, number=None):
"""Copies a (potentially) owned ProtoRPC field instance into a new copy.
Args:
field: A ProtoRPC message field to be copied.
number: An integer for the field to override the number of the field.
Defaults to None.
Raises:
TypeError: If the field is not an instance of messages.Field.
Returns:
A copy of the ProtoRPC message field.
"""
positional_args, kwargs = _GetFieldAttributes(field)
number = number or field.number
positional_args.append(number)
return field.__class__(*positional_args, **kwargs)
|
catapult-project/catapult
|
third_party/google-endpoints/endpoints/resource_container.py
|
Python
|
bsd-3-clause
| 8,074
|
from decimal import Decimal as D
import datetime
from django.test import TestCase
from django_dynamic_fixture import G
from oscar.apps.offer import models
from oscar.apps.order.models import OrderDiscount
from oscar.core.compat import get_user_model
from oscar.test.factories import create_order
User = get_user_model()
class TestADateBasedConditionalOffer(TestCase):
def setUp(self):
self.start = datetime.date(2011, 01, 01)
self.end = datetime.date(2011, 02, 01)
self.offer = models.ConditionalOffer(start_datetime=self.start,
end_datetime=self.end)
def test_is_available_during_date_range(self):
test = datetime.date(2011, 01, 10)
self.assertTrue(self.offer.is_available(test_date=test))
def test_is_inactive_before_date_range(self):
test = datetime.date(2010, 03, 10)
self.assertFalse(self.offer.is_available(test_date=test))
def test_is_inactive_after_date_range(self):
test = datetime.date(2011, 03, 10)
self.assertFalse(self.offer.is_available(test_date=test))
def test_is_active_on_end_datetime(self):
self.assertTrue(self.offer.is_available(test_date=self.end))
class TestAConsumptionFrequencyBasedConditionalOffer(TestCase):
def setUp(self):
self.offer = models.ConditionalOffer(max_global_applications=4)
def test_is_available_with_no_applications(self):
self.assertTrue(self.offer.is_available())
def test_is_available_with_fewer_applications_than_max(self):
self.offer.num_applications = 3
self.assertTrue(self.offer.is_available())
def test_is_inactive_with_equal_applications_to_max(self):
self.offer.num_applications = 4
self.assertFalse(self.offer.is_available())
def test_is_inactive_with_more_applications_than_max(self):
self.offer.num_applications = 4
self.assertFalse(self.offer.is_available())
def test_restricts_number_of_applications_correctly_with_no_applications(self):
self.assertEqual(4, self.offer.get_max_applications())
def test_restricts_number_of_applications_correctly_with_fewer_applications_than_max(self):
self.offer.num_applications = 3
self.assertEqual(1, self.offer.get_max_applications())
def test_restricts_number_of_applications_correctly_with_more_applications_than_max(self):
self.offer.num_applications = 5
self.assertEqual(0, self.offer.get_max_applications())
class TestAPerUserConditionalOffer(TestCase):
def setUp(self):
self.offer = models.ConditionalOffer(max_user_applications=1)
self.user = G(User)
def test_is_available_with_no_applications(self):
self.assertTrue(self.offer.is_available())
def test_max_applications_is_correct_when_no_applications(self):
self.assertEqual(1, self.offer.get_max_applications(self.user))
def test_max_applications_is_correct_when_equal_applications(self):
order = create_order(user=self.user)
G(OrderDiscount, order=order, offer_id=self.offer.id, frequency=1)
self.assertEqual(0, self.offer.get_max_applications(self.user))
def test_max_applications_is_correct_when_more_applications(self):
order = create_order(user=self.user)
G(OrderDiscount, order=order, offer_id=self.offer.id, frequency=5)
self.assertEqual(0, self.offer.get_max_applications(self.user))
class TestCappedDiscountConditionalOffer(TestCase):
def setUp(self):
self.offer = models.ConditionalOffer(
max_discount=D('100.00'),
total_discount=D('0.00'))
def test_is_available_when_below_threshold(self):
self.assertTrue(self.offer.is_available())
def test_is_inactive_when_on_threshold(self):
self.offer.total_discount = self.offer.max_discount
self.assertFalse(self.offer.is_available())
def test_is_inactive_when_above_threshold(self):
self.offer.total_discount = self.offer.max_discount + D('10.00')
self.assertFalse(self.offer.is_available())
class TestASuspendedOffer(TestCase):
def setUp(self):
self.offer = models.ConditionalOffer(
status=models.ConditionalOffer.SUSPENDED)
def test_is_unavailable(self):
self.assertFalse(self.offer.is_available())
def test_lists_suspension_as_an_availability_restriction(self):
restrictions = self.offer.availability_restrictions()
self.assertEqual(1, len(restrictions))
|
Giftingnation/GN-Oscar-Custom
|
tests/unit/offer/availability_tests.py
|
Python
|
bsd-3-clause
| 4,529
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
"""
oauthlib.oauth2.rfc6749
~~~~~~~~~~~~~~~~~~~~~~~
This module is an implementation of various logic needed
for consuming OAuth 2.0 RFC6749.
"""
import time
from oauthlib.oauth2.rfc6749 import tokens
from oauthlib.oauth2.rfc6749.parameters import prepare_token_request
from oauthlib.oauth2.rfc6749.errors import TokenExpiredError
from oauthlib.oauth2.rfc6749.errors import InsecureTransportError
from oauthlib.oauth2.rfc6749.utils import is_secure_transport
AUTH_HEADER = 'auth_header'
URI_QUERY = 'query'
BODY = 'body'
class Client(object):
"""Base OAuth2 client responsible for access tokens.
While this class can be used to simply append tokens onto requests
it is often more useful to use a client targeted at a specific workflow.
"""
def __init__(self, client_id,
default_token_placement=AUTH_HEADER,
token_type='Bearer',
access_token=None,
refresh_token=None,
mac_key=None,
mac_algorithm=None,
token=None,
**kwargs):
"""Initialize a client with commonly used attributes."""
self.client_id = client_id
self.default_token_placement = default_token_placement
self.token_type = token_type
self.access_token = access_token
self.refresh_token = refresh_token
self.mac_key = mac_key
self.mac_algorithm = mac_algorithm
self.token = token or {}
self._expires_at = None
self._populate_attributes(self.token)
@property
def token_types(self):
"""Supported token types and their respective methods
Additional tokens can be supported by extending this dictionary.
The Bearer token spec is stable and safe to use.
The MAC token spec is not yet stable and support for MAC tokens
is experimental and currently matching version 00 of the spec.
"""
return {
'Bearer': self._add_bearer_token,
'MAC': self._add_mac_token
}
def add_token(self, uri, http_method='GET', body=None, headers=None,
token_placement=None, **kwargs):
"""Add token to the request uri, body or authorization header.
The access token type provides the client with the information
required to successfully utilize the access token to make a protected
resource request (along with type-specific attributes). The client
MUST NOT use an access token if it does not understand the token
type.
For example, the "bearer" token type defined in
[`I-D.ietf-oauth-v2-bearer`_] is utilized by simply including the access
token string in the request:
.. code-block:: http
GET /resource/1 HTTP/1.1
Host: example.com
Authorization: Bearer mF_9.B5f-4.1JqM
while the "mac" token type defined in [`I-D.ietf-oauth-v2-http-mac`_] is
utilized by issuing a MAC key together with the access token which is
used to sign certain components of the HTTP requests:
.. code-block:: http
GET /resource/1 HTTP/1.1
Host: example.com
Authorization: MAC id="h480djs93hd8",
nonce="274312:dj83hs9s",
mac="kDZvddkndxvhGRXZhvuDjEWhGeE="
.. _`I-D.ietf-oauth-v2-bearer`: http://tools.ietf.org/html/rfc6749#section-12.2
.. _`I-D.ietf-oauth-v2-http-mac`: http://tools.ietf.org/html/rfc6749#section-12.2
"""
if not is_secure_transport(uri):
raise InsecureTransportError()
token_placement = token_placement or self.default_token_placement
case_insensitive_token_types = dict((k.lower(), v) for k, v in self.token_types.items())
if not self.token_type.lower() in case_insensitive_token_types:
raise ValueError("Unsupported token type: %s" % self.token_type)
if not self.access_token:
raise ValueError("Missing access token.")
if self._expires_at and self._expires_at < time.time():
raise TokenExpiredError()
return case_insensitive_token_types[self.token_type.lower()](uri, http_method, body,
headers, token_placement, **kwargs)
def prepare_refresh_body(self, body='', refresh_token=None, scope=None, **kwargs):
"""Prepare an access token request, using a refresh token.
If the authorization server issued a refresh token to the client, the
client makes a refresh request to the token endpoint by adding the
following parameters using the "application/x-www-form-urlencoded"
format in the HTTP request entity-body:
grant_type
REQUIRED. Value MUST be set to "refresh_token".
refresh_token
REQUIRED. The refresh token issued to the client.
scope
OPTIONAL. The scope of the access request as described by
Section 3.3. The requested scope MUST NOT include any scope
not originally granted by the resource owner, and if omitted is
treated as equal to the scope originally granted by the
resource owner.
"""
refresh_token = refresh_token or self.refresh_token
return prepare_token_request('refresh_token', body=body, scope=scope,
refresh_token=refresh_token, **kwargs)
def _add_bearer_token(self, uri, http_method='GET', body=None,
headers=None, token_placement=None):
"""Add a bearer token to the request uri, body or authorization header."""
if token_placement == AUTH_HEADER:
headers = tokens.prepare_bearer_headers(self.access_token, headers)
elif token_placement == URI_QUERY:
uri = tokens.prepare_bearer_uri(self.access_token, uri)
elif token_placement == BODY:
body = tokens.prepare_bearer_body(self.access_token, body)
else:
raise ValueError("Invalid token placement.")
return uri, headers, body
def _add_mac_token(self, uri, http_method='GET', body=None,
headers=None, token_placement=AUTH_HEADER, ext=None, **kwargs):
"""Add a MAC token to the request authorization header.
Warning: MAC token support is experimental as the spec is not yet stable.
"""
headers = tokens.prepare_mac_header(self.access_token, uri,
self.mac_key, http_method, headers=headers, body=body, ext=ext,
hash_algorithm=self.mac_algorithm, **kwargs)
return uri, headers, body
def _populate_attributes(self, response):
"""Add commonly used values such as access_token to self."""
if 'access_token' in response:
self.access_token = response.get('access_token')
if 'refresh_token' in response:
self.refresh_token = response.get('refresh_token')
if 'token_type' in response:
self.token_type = response.get('token_type')
if 'expires_in' in response:
self.expires_in = response.get('expires_in')
self._expires_at = time.time() + int(self.expires_in)
if 'expires_at' in response:
self._expires_at = int(response.get('expires_at'))
if 'code' in response:
self.code = response.get('code')
if 'mac_key' in response:
self.mac_key = response.get('mac_key')
if 'mac_algorithm' in response:
self.mac_algorithm = response.get('mac_algorithm')
def prepare_request_uri(self, *args, **kwargs):
"""Abstract method used to create request URIs."""
raise NotImplementedError("Must be implemented by inheriting classes.")
def prepare_request_body(self, *args, **kwargs):
"""Abstract method used to create request bodies."""
raise NotImplementedError("Must be implemented by inheriting classes.")
def parse_request_uri_response(self, *args, **kwargs):
"""Abstract method used to parse redirection responses."""
def parse_request_body_response(self, *args, **kwargs):
"""Abstract method used to parse JSON responses."""
|
yasoob/PythonRSSReader
|
venv/lib/python2.7/dist-packages/oauthlib/oauth2/rfc6749/clients/base.py
|
Python
|
mit
| 8,298
|
import random
import string
from base import *
from util import *
MAGIC = str_random (100)
LENGTH = 100
OFFSET = 15
class Test (TestBase):
def __init__ (self):
TestBase.__init__ (self, __file__)
self.name = "Content Range, start"
self.request = "GET /Range100b HTTP/1.0\r\n" +\
"Range: bytes=%d-\r\n" % (OFFSET)
length = LENGTH - OFFSET
self.expected_error = 206
self.expected_content = [MAGIC[OFFSET:], "Content-Length: %d" % (length)]
self.forbidden_content = MAGIC[:OFFSET]
def Prepare (self, www):
self.WriteFile (www, "Range100b", 0444, MAGIC)
|
chetan/cherokee
|
qa/054-ContentRange.py
|
Python
|
gpl-2.0
| 704
|
from enigma import eServiceReference, eServiceCenter
class ServiceReference(eServiceReference):
def __init__(self, ref, reftype = eServiceReference.idInvalid, flags = 0, path = ''):
if reftype != eServiceReference.idInvalid:
self.ref = eServiceReference(reftype, flags, path)
elif not isinstance(ref, eServiceReference):
self.ref = eServiceReference(ref or "")
else:
self.ref = ref
self.serviceHandler = eServiceCenter.getInstance()
def __str__(self):
return self.ref.toString()
def getServiceName(self):
info = self.info()
return info and info.getName(self.ref) or ""
def info(self):
return self.serviceHandler.info(self.ref)
def list(self):
return self.serviceHandler.list(self.ref)
def getType(self):
return self.ref.type
def getPath(self):
return self.ref.getPath()
def getFlags(self):
return self.ref.flags
def isRecordable(self):
ref = self.ref
return ref.flags & eServiceReference.isGroup or (ref.type == eServiceReference.idDVB or ref.type == eServiceReference.idDVB + 0x100)
|
digidudeofdw/enigma2
|
ServiceReference.py
|
Python
|
gpl-2.0
| 1,038
|
from __future__ import with_statement
import inspect
import logging
import sys
from django.conf import settings
from django.forms.forms import BoundField
from django.template import Context
from django.template.loader import get_template
from django.utils.html import conditional_escape
from django.utils.functional import memoize
from .base import KeepContext
from .compatibility import text_type, PY2
# Global field template, default template used for rendering a field.
TEMPLATE_PACK = getattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap')
# By memoizeing we avoid loading the template every time render_field
# is called without a template
def default_field_template(template_pack=TEMPLATE_PACK):
return get_template("%s/field.html" % template_pack)
default_field_template = memoize(default_field_template, {}, 1)
def render_field(field, form, form_style, context, template=None, labelclass=None, layout_object=None, attrs=None, template_pack=TEMPLATE_PACK):
"""
Renders a django-crispy-forms field
:param field: Can be a string or a Layout object like `Row`. If it's a layout
object, we call its render method, otherwise we instantiate a BoundField
and render it using default template 'CRISPY_TEMPLATE_PACK/field.html'
The field is added to a list that the form holds called `rendered_fields`
to avoid double rendering fields.
:param form: The form/formset to which that field belongs to.
:param form_style: A way to pass style name to the CSS framework used.
:template: Template used for rendering the field.
:layout_object: If passed, it points to the Layout object that is being rendered.
We use it to store its bound fields in a list called `layout_object.bound_fields`
:attrs: Attributes for the field's widget
"""
with KeepContext(context):
FAIL_SILENTLY = getattr(settings, 'CRISPY_FAIL_SILENTLY', True)
if hasattr(field, 'render'):
if 'template_pack' in inspect.getargspec(field.render)[0]:
return field.render(form, form_style, context, template_pack=template_pack)
else:
return field.render(form, form_style, context)
else:
# In Python 2 form field names cannot contain unicode characters without ASCII mapping
if PY2:
# This allows fields to be unicode strings, always they don't use non ASCII
try:
if isinstance(field, text_type):
field = field.encode('ascii').decode()
# If `field` is not unicode then we turn it into a unicode string, otherwise doing
# str(field) would give no error and the field would not be resolved, causing confusion
else:
field = text_type(field)
except (UnicodeEncodeError, UnicodeDecodeError):
raise Exception("Field '%s' is using forbidden unicode characters" % field)
try:
# Injecting HTML attributes into field's widget, Django handles rendering these
field_instance = form.fields[field]
if attrs is not None:
widgets = getattr(field_instance.widget, 'widgets', [field_instance.widget])
# We use attrs as a dictionary later, so here we make a copy
list_attrs = attrs
if isinstance(attrs, dict):
list_attrs = [attrs] * len(widgets)
for index, (widget, attr) in enumerate(zip(widgets, list_attrs)):
if hasattr(field_instance.widget, 'widgets'):
if 'type' in attr and attr['type'] == "hidden":
field_instance.widget.widgets[index].is_hidden = True
field_instance.widget.widgets[index] = field_instance.hidden_widget()
field_instance.widget.widgets[index].attrs.update(attr)
else:
if 'type' in attr and attr['type'] == "hidden":
field_instance.widget.is_hidden = True
field_instance.widget = field_instance.hidden_widget()
field_instance.widget.attrs.update(attr)
except KeyError:
if not FAIL_SILENTLY:
raise Exception("Could not resolve form field '%s'." % field)
else:
field_instance = None
logging.warning("Could not resolve form field '%s'." % field, exc_info=sys.exc_info())
if hasattr(form, 'rendered_fields'):
if not field in form.rendered_fields:
form.rendered_fields.add(field)
else:
if not FAIL_SILENTLY:
raise Exception("A field should only be rendered once: %s" % field)
else:
logging.warning("A field should only be rendered once: %s" % field, exc_info=sys.exc_info())
if field_instance is None:
html = ''
else:
bound_field = BoundField(form, field_instance, field)
if template is None:
if form.crispy_field_template is None:
template = default_field_template(template_pack)
else: # FormHelper.field_template set
template = get_template(form.crispy_field_template)
else:
template = get_template(template)
# We save the Layout object's bound fields in the layout object's `bound_fields` list
if layout_object is not None:
if hasattr(layout_object, 'bound_fields') and isinstance(layout_object.bound_fields, list):
layout_object.bound_fields.append(bound_field)
else:
layout_object.bound_fields = [bound_field]
context.update({
'field': bound_field,
'labelclass': labelclass,
'flat_attrs': flatatt(attrs if isinstance(attrs, dict) else {}),
})
html = template.render(context)
return html
def flatatt(attrs):
"""
Taken from django.core.utils
Convert a dictionary of attributes to a single string.
The returned string will contain a leading space followed by key="value",
XML-style pairs. It is assumed that the keys do not need to be XML-escaped.
If the passed dictionary is empty, then return an empty string.
"""
return u''.join([u' %s="%s"' % (k.replace('_', '-'), conditional_escape(v)) for k, v in attrs.items()])
def render_crispy_form(form, helper=None, context=None):
"""
Renders a form and returns its HTML output.
This function wraps the template logic in a function easy to use in a Django view.
"""
from crispy_forms.templatetags.crispy_forms_tags import CrispyFormNode
if helper is not None:
node = CrispyFormNode('form', 'helper')
else:
node = CrispyFormNode('form', None)
node_context = Context(context)
node_context.update({
'form': form,
'helper': helper
})
return node.render(node_context)
|
patrickstocklin/chattR
|
lib/python2.7/site-packages/crispy_forms/utils.py
|
Python
|
gpl-2.0
| 7,226
|
import ocl
import pyocl
import camvtk
import time
import datetime
import vtk
def main(filename="frame/f.png"):
print ocl.revision()
myscreen = camvtk.VTKScreen()
myscreen.camera.SetPosition(-15, -8, 15)
myscreen.camera.SetFocalPoint(5,5, 0)
# axis arrows
camvtk.drawArrows(myscreen,center=(-1,-1,0))
# screenshot writer
w2if = vtk.vtkWindowToImageFilter()
w2if.SetInput(myscreen.renWin)
lwr = vtk.vtkPNGWriter()
lwr.SetInput( w2if.GetOutput() )
c = ocl.CylCutter(1,4) # cutter
c.length = 3
print "cutter length=", c.length
# generate CL-points
stl = camvtk.STLSurf("../stl/gnu_tux_mod.stl")
polydata = stl.src.GetOutput()
s = ocl.STLSurf()
camvtk.vtkPolyData2OCLSTL(polydata, s)
print "STL surface read,", s.size(), "triangles"
print s.getBounds()
#exit()
minx=0
dx=0.1
maxx=9
miny=0
dy=0.4
maxy=12
z=-17
# this generates a list of CL-points in a grid
clpoints = pyocl.CLPointGridZigZag(minx,dx,maxx,miny,dy,maxy,z)
print "generated grid with", len(clpoints)," CL-points"
# batchdropcutter
bdc = ocl.BatchDropCutter()
bdc.setSTL(s)
bdc.setCutter(c)
for p in clpoints:
bdc.appendPoint(p)
t_before = time.time()
print "threads=",bdc.getThreads()
bdc.run()
t_after = time.time()
calctime = t_after-t_before
print " done in ", calctime," s"
clpoints = bdc.getCLPoints()
# filter
print "filtering. before filter we have", len(clpoints),"cl-points"
t_before = time.time()
f = ocl.LineCLFilter()
f.setTolerance(0.001)
for p in clpoints:
f.addCLPoint(p)
f.run()
clpts = f.getCLPoints()
calctime = time.time()-t_before
print "after filtering we have", len(clpts),"cl-points"
print " done in ", calctime," s"
#exit()
# stupid init code
ocode=ocl.Ocode()
tree_maxdepth=10
ocode.set_depth(tree_maxdepth) # depth and scale set here.
ocode.set_scale(10)
# cube
stockvol = ocl.BoxOCTVolume()
stockvol.corner = ocl.Point(0,0,-0.5)
stockvol.v1 = ocl.Point(9,0,0)
stockvol.v2 = ocl.Point(0,12,0)
stockvol.v3 = ocl.Point(0,0,3.5)
stockvol.calcBB()
t_before = time.time()
stock = ocl.LinOCT()
stock.init(0)
stock.build( stockvol )
calctime = time.time()-t_before
print " stock built in ", calctime," s, stock.size()=",stock.size()
# draw initial octree
#tlist = pyocl.octree2trilist(stock)
#surf = camvtk.STLSurf(triangleList=tlist)
#myscreen.addActor(surf)
# draw initial cutter
#startp = ocl.Point(0,0,0)
#cyl = camvtk.Cylinder(center=(startp.x,startp.y,startp.z), radius=c.radius,
# height=c.length,
# rotXYZ=(90,0,0), color=camvtk.grey)
#cyl.SetWireframe()
#myscreen.addActor(cyl)
timetext = camvtk.Text()
timetext.SetPos( (myscreen.width-300, myscreen.height-30) )
myscreen.addActor( timetext)
ocltext = camvtk.Text()
ocltext.SetPos( (myscreen.width-300, myscreen.height-60) )
myscreen.addActor( ocltext)
ocltext.SetText("OpenCAMLib")
octtext = camvtk.Text()
octtext.SetPos( (myscreen.width-300, myscreen.height-90) )
myscreen.addActor( octtext)
octtext.SetText("Octree cutting-simulation")
infotext = camvtk.Text()
infotext.SetPos( (myscreen.width-300, myscreen.height-180) )
myscreen.addActor( infotext)
Nmoves = len(clpts)
print Nmoves,"CL-points to process"
for n in xrange(0,Nmoves-1):
timetext.SetText(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
#if n<Nmoves-1:
print n," to ",n+1," of ",Nmoves
startp = clpts[n] # start of move
endp = clpts[n+1] # end of move
#t_before = time.time()
sweep = ocl.LinOCT()
sweep.init(0)
#calctime = time.time()-t_before
#print " sweep-init done in ", calctime," s, sweep.size()=",sweep.size()
g1vol = ocl.CylMoveOCTVolume(c, ocl.Point(startp.x,startp.y,startp.z), ocl.Point(endp.x,endp.y,endp.z))
t_before = time.time()
sweep.build( g1vol )
calctime = time.time()-t_before
print " sweep-build done in ", calctime," s, sweep.size()=",sweep.size()
# draw cutter
cyl1 = camvtk.Cylinder(center=(startp.x,startp.y,startp.z), radius=c.radius,
height=c.length,
rotXYZ=(90,0,0), color=camvtk.lgreen)
cyl1.SetWireframe()
#myscreen.addActor(cyl1)
cyl2 = camvtk.Cylinder(center=(endp.x,endp.y,endp.z), radius=c.radius,
height=c.length,
rotXYZ=(90,0,0), color=camvtk.pink)
cyl2.SetWireframe()
#myscreen.addActor(cyl2)
#camvtk.drawCylCutter(myscreen, c, startp)
#camvtk.drawCylCutter(myscreen, c, endp)
myscreen.addActor( camvtk.Line( p1=(startp.x,startp.y,startp.z), p2=(endp.x,endp.y,endp.z), color=camvtk.red))
#camvtk.drawTree2(myscreen,sweep,color=camvtk.red,opacity=0.5)
t_before = time.time()
stock.diff(sweep)
calctime = time.time()-t_before
print " diff done in ", calctime," s, stock.size()", stock.size()
info = "tree-depth:%i \nmove: %i \nstock-nodes: %i \nsweep-nodes: %i" % (tree_maxdepth, n, stock.size(), sweep.size() )
infotext.SetText(info)
if ((n!=0 and n%10==0) or n==Nmoves-2): # draw only every m:th frame
# sweep surface
t_before = time.time()
#sweep_tlist = pyocl.octree2trilist(sweep)
sweep_tlist = sweep.get_triangles()
sweepsurf = camvtk.STLSurf(triangleList=sweep_tlist)
sweepsurf.SetColor(camvtk.red)
sweepsurf.SetOpacity(0.1)
myscreen.addActor(sweepsurf)
calctime = time.time()-t_before
print " sweepsurf-render ", calctime," s"
# stock surface
t_before = time.time()
#tlist = pyocl.octree2trilist(stock)
tlist = stock.get_triangles()
stocksurf = camvtk.STLSurf(triangleList=tlist)
stocksurf.SetColor(camvtk.cyan)
stocksurf.SetOpacity(1.0)
myscreen.addActor(stocksurf)
calctime = time.time()-t_before
print " stocksurf-render ", calctime," s"
#time.sleep(1.1)
# write screenshot to disk
lwr.SetFileName("frames/tux_frame"+ ('%06d' % n)+".png")
#lwr.SetFileName(filename)
t_before = time.time() # time the render process
myscreen.render()
w2if.Modified()
lwr.Write()
calctime = time.time()-t_before
print " render ", calctime," s"
#myscreen.render()
#time.sleep(0.1)
myscreen.removeActor(sweepsurf)
if n != (Nmoves-2):
myscreen.removeActor(stocksurf)
#myscreen.removeActor(cyl1)
#myscreen.removeActor(cyl2)
#myscreen.render()
#time.sleep(0.1)
print " render()...",
myscreen.render()
print "done."
#time.sleep(0.2)
myscreen.iren.Start()
if __name__ == "__main__":
main()
|
AlanZatarain/opencamlib
|
scripts/old/cutsim_test_tux_1.py
|
Python
|
gpl-3.0
| 7,645
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
from odoo.modules.loading import force_demo
from odoo.addons.base.models.ir_module import assert_log_admin_access
class IrDemo(models.TransientModel):
_name = 'ir.demo'
_description = 'Demo'
@assert_log_admin_access
def install_demo(self):
force_demo(self.env.cr)
return {
'type': 'ir.actions.act_url',
'target': 'self',
'url': '/web',
}
|
jeremiahyan/odoo
|
odoo/addons/base/models/ir_demo.py
|
Python
|
gpl-3.0
| 542
|
"""
Tests for Blocks Views
"""
from django.core.urlresolvers import reverse
from string import join
from urllib import urlencode
from urlparse import urlunparse
from opaque_keys.edx.locator import CourseLocator
from student.models import CourseEnrollment
from student.tests.factories import AdminFactory, CourseEnrollmentFactory, UserFactory
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
from xmodule.modulestore.tests.factories import ToyCourseFactory
from .helpers import deserialize_usage_key
class TestBlocksView(SharedModuleStoreTestCase):
"""
Test class for BlocksView
"""
requested_fields = ['graded', 'format', 'student_view_multi_device', 'children', 'not_a_field']
BLOCK_TYPES_WITH_STUDENT_VIEW_DATA = ['video', 'discussion']
@classmethod
def setUpClass(cls):
super(TestBlocksView, cls).setUpClass()
# create a toy course
cls.course_key = ToyCourseFactory.create().id
cls.course_usage_key = cls.store.make_course_usage_key(cls.course_key)
cls.non_orphaned_block_usage_keys = set(
unicode(item.location)
for item in cls.store.get_items(cls.course_key)
# remove all orphaned items in the course, except for the root 'course' block
if cls.store.get_parent_location(item.location) or item.category == 'course'
)
def setUp(self):
super(TestBlocksView, self).setUp()
# create a user, enrolled in the toy course
self.user = UserFactory.create()
self.client.login(username=self.user.username, password='test')
CourseEnrollmentFactory.create(user=self.user, course_id=self.course_key)
# default values for url and query_params
self.url = reverse(
'blocks_in_block_tree',
kwargs={'usage_key_string': unicode(self.course_usage_key)}
)
self.query_params = {'depth': 'all', 'username': self.user.username}
def verify_response(self, expected_status_code=200, params=None, url=None):
"""
Ensure that sending a GET request to the specified URL returns the
expected status code.
Arguments:
expected_status_code: The status_code that is expected in the
response.
params: Parameters to add to self.query_params to include in the
request.
url: The URL to send the GET request. Default is self.url.
Returns:
response: The HttpResponse returned by the request
"""
if params:
self.query_params.update(params)
response = self.client.get(url or self.url, self.query_params)
self.assertEquals(response.status_code, expected_status_code)
return response
def verify_response_block_list(self, response):
"""
Verify that the response contains only the expected block ids.
"""
self.assertSetEqual(
{block['id'] for block in response.data},
self.non_orphaned_block_usage_keys,
)
def verify_response_block_dict(self, response):
"""
Verify that the response contains the expected blocks
"""
self.assertSetEqual(
set(response.data['blocks'].iterkeys()),
self.non_orphaned_block_usage_keys,
)
def verify_response_with_requested_fields(self, response):
"""
Verify the response has the expected structure
"""
self.verify_response_block_dict(response)
for block_key_string, block_data in response.data['blocks'].iteritems():
block_key = deserialize_usage_key(block_key_string, self.course_key)
xblock = self.store.get_item(block_key)
self.assert_in_iff('children', block_data, xblock.has_children)
self.assert_in_iff('graded', block_data, xblock.graded is not None)
self.assert_in_iff('format', block_data, xblock.format is not None)
self.assert_true_iff(block_data['student_view_multi_device'], block_data['type'] == 'html')
self.assertNotIn('not_a_field', block_data)
if xblock.has_children:
self.assertSetEqual(
set(unicode(child.location) for child in xblock.get_children()),
set(block_data['children']),
)
def assert_in_iff(self, member, container, predicate):
"""
Assert that member is in container if and only if predicate is true.
Arguments:
member - any object
container - any container
predicate - an expression, tested for truthiness
"""
if predicate:
self.assertIn(member, container)
else:
self.assertNotIn(member, container)
def assert_true_iff(self, expression, predicate):
"""
Assert that the expression is true if and only if the predicate is true
Arguments:
expression
predicate
"""
if predicate:
self.assertTrue(expression)
else:
self.assertFalse(expression)
def test_not_authenticated(self):
self.client.logout()
self.verify_response(401)
def test_not_enrolled(self):
CourseEnrollment.unenroll(self.user, self.course_key)
self.verify_response(403)
def test_non_existent_course(self):
usage_key = self.store.make_course_usage_key(CourseLocator('non', 'existent', 'course'))
url = reverse(
'blocks_in_block_tree',
kwargs={'usage_key_string': unicode(usage_key)}
)
self.verify_response(403, url=url)
def test_no_user_non_staff(self):
self.query_params.pop('username')
self.query_params['all_blocks'] = True
self.verify_response(403)
def test_no_user_staff_not_all_blocks(self):
self.query_params.pop('username')
self.verify_response(400)
def test_no_user_staff_all_blocks(self):
self.client.login(username=AdminFactory.create().username, password='test')
self.query_params.pop('username')
self.query_params['all_blocks'] = True
self.verify_response()
def test_basic(self):
response = self.verify_response()
self.assertEquals(response.data['root'], unicode(self.course_usage_key))
self.verify_response_block_dict(response)
for block_key_string, block_data in response.data['blocks'].iteritems():
block_key = deserialize_usage_key(block_key_string, self.course_key)
self.assertEquals(block_data['id'], block_key_string)
self.assertEquals(block_data['type'], block_key.block_type)
self.assertEquals(block_data['display_name'], self.store.get_item(block_key).display_name or '')
def test_return_type_param(self):
response = self.verify_response(params={'return_type': 'list'})
self.verify_response_block_list(response)
def test_block_counts_param(self):
response = self.verify_response(params={'block_counts': ['course', 'chapter']})
self.verify_response_block_dict(response)
for block_data in response.data['blocks'].itervalues():
self.assertEquals(
block_data['block_counts']['course'],
1 if block_data['type'] == 'course' else 0,
)
self.assertEquals(
block_data['block_counts']['chapter'],
(
1 if block_data['type'] == 'chapter' else
5 if block_data['type'] == 'course' else
0
)
)
def test_student_view_data_param(self):
response = self.verify_response(params={
'student_view_data': self.BLOCK_TYPES_WITH_STUDENT_VIEW_DATA + ['chapter']
})
self.verify_response_block_dict(response)
for block_data in response.data['blocks'].itervalues():
self.assert_in_iff(
'student_view_data',
block_data,
block_data['type'] in self.BLOCK_TYPES_WITH_STUDENT_VIEW_DATA
)
def test_navigation_param(self):
response = self.verify_response(params={'nav_depth': 10})
self.verify_response_block_dict(response)
for block_data in response.data['blocks'].itervalues():
self.assertIn('descendants', block_data)
def test_requested_fields_param(self):
response = self.verify_response(
params={'requested_fields': self.requested_fields}
)
self.verify_response_with_requested_fields(response)
def test_with_list_field_url(self):
query = urlencode(self.query_params.items() + [
('requested_fields', self.requested_fields[0]),
('requested_fields', self.requested_fields[1]),
('requested_fields', join(self.requested_fields[1:], ',')),
])
self.query_params = None
response = self.verify_response(
url=urlunparse(("", "", self.url, "", query, ""))
)
self.verify_response_with_requested_fields(response)
class TestBlocksInCourseView(TestBlocksView): # pylint: disable=test-inherits-tests
"""
Test class for BlocksInCourseView
"""
def setUp(self):
super(TestBlocksInCourseView, self).setUp()
self.url = reverse('blocks_in_course')
self.query_params['course_id'] = unicode(self.course_key)
def test_no_course_id(self):
self.query_params.pop('course_id')
self.verify_response(400)
def test_invalid_course_id(self):
self.verify_response(400, params={'course_id': 'invalid_course_id'})
def test_non_existent_course(self):
self.verify_response(403, params={'course_id': unicode(CourseLocator('non', 'existent', 'course'))})
|
shabab12/edx-platform
|
lms/djangoapps/course_api/blocks/tests/test_views.py
|
Python
|
agpl-3.0
| 9,891
|
"""
Copyright 2009 55 Minutes (http://www.55minutes.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from django.conf import settings
from django.core.management import call_command
from django.core.management.commands import test
from django_coverage import settings as coverage_settings
class Command(test.Command):
help = ("Runs the test suite for the specified applications, or the "
"entire site if no apps are specified. Then generates coverage "
"report both onscreen and as HTML.")
def handle(self, *test_labels, **options):
"""
Replaces the original test runner with the coverage test runner, but
keeps track of what the original runner was so that the coverage
runner can inherit from it. Then, call the test command. This
plays well with apps that override the test command, such as South.
"""
coverage_settings.ORIG_TEST_RUNNER = settings.TEST_RUNNER
settings.TEST_RUNNER = coverage_settings.COVERAGE_TEST_RUNNER
call_command('test', *test_labels, **options)
|
21strun/django-coverage
|
django_coverage/management/commands/test_coverage.py
|
Python
|
apache-2.0
| 1,565
|
import base64
import json
from django.core.urlresolvers import reverse
from onadata.apps.main.views import api
from onadata.apps.viewer.models.parsed_instance import ParsedInstance, \
_encode_for_mongo, _decode_from_mongo
from test_base import TestBase
def dict_for_mongo_without_userform_id(parsed_instance):
d = parsed_instance.to_dict_for_mongo()
# remove _userform_id since its not returned by the API
d.pop(ParsedInstance.USERFORM_ID)
return d
class TestFormAPI(TestBase):
def setUp(self):
TestBase.setUp(self)
self._create_user_and_login()
self._publish_transportation_form_and_submit_instance()
self.api_url = reverse(api, kwargs={
'username': self.user.username,
'id_string': self.xform.id_string
})
def test_api(self):
# query string
response = self.client.get(self.api_url, {})
self.assertEqual(response.status_code, 200)
d = dict_for_mongo_without_userform_id(
self.xform.instances.all()[0].parsed_instance)
find_d = json.loads(response.content)[0]
self.assertEqual(find_d, d)
def test_api_with_query(self):
# query string
query = '{"transport/available_transportation_types_to_referral_facil'\
'ity":"none"}'
data = {'query': query}
response = self.client.get(self.api_url, data)
self.assertEqual(response.status_code, 200)
d = dict_for_mongo_without_userform_id(
self.xform.instances.all()[0].parsed_instance)
find_d = json.loads(response.content)[0]
self.assertEqual(find_d, d)
def test_api_query_no_records(self):
# query string
query = '{"available_transporation_types_to_referral_facility": "bicy'\
'cle"}'
data = {'query': query}
response = self.client.get(self.api_url, data)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, '[]')
def test_handle_bad_json(self):
response = self.client.get(self.api_url, {'query': 'bad'})
self.assertEqual(response.status_code, 400)
self.assertEqual(True, 'JSON' in response.content)
def test_api_jsonp(self):
# query string
callback = 'jsonpCallback'
response = self.client.get(self.api_url, {'callback': callback})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content.startswith(callback + '('), True)
self.assertEqual(response.content.endswith(')'), True)
start = callback.__len__() + 1
end = response.content.__len__() - 1
content = response.content[start: end]
d = dict_for_mongo_without_userform_id(
self.xform.instances.all()[0].parsed_instance)
find_d = json.loads(content)[0]
self.assertEqual(find_d, d)
def test_api_with_query_start_limit(self):
# query string
query = '{"transport/available_transportation_types_to_referral_facil'\
'ity":"none"}'
data = {'query': query, 'start': 0, 'limit': 10}
response = self.client.get(self.api_url, data)
self.assertEqual(response.status_code, 200)
d = dict_for_mongo_without_userform_id(
self.xform.instances.all()[0].parsed_instance)
find_d = json.loads(response.content)[0]
self.assertEqual(find_d, d)
def test_api_with_query_invalid_start_limit(self):
# query string
query = '{"transport/available_transportation_types_to_referral_facil'\
'ity":"none"}'
data = {'query': query, 'start': -100, 'limit': -100}
response = self.client.get(self.api_url, data)
self.assertEqual(response.status_code, 400)
def test_api_count(self):
# query string
query = '{"transport/available_transportation_types_to_referral_facil'\
'ity":"none"}'
data = {'query': query, 'count': 1}
response = self.client.get(self.api_url, data)
self.assertEqual(response.status_code, 200)
find_d = json.loads(response.content)[0]
self.assertTrue('count' in find_d)
self.assertEqual(find_d.get('count'), 1)
def test_api_column_select(self):
# query string
query = '{"transport/available_transportation_types_to_referral_facil'\
'ity":"none"}'
columns = '["transport/available_transportation_types_to_referral_fac'\
'ility"]'
data = {'query': query, 'fields': columns}
response = self.client.get(self.api_url, data)
self.assertEqual(response.status_code, 200)
find_d = json.loads(response.content)[0]
self.assertTrue(
'transport/available_transportation_types_to_referral_facility' in
find_d)
self.assertFalse('_attachments' in find_d)
def test_api_decode_from_mongo(self):
field = "$section1.group01.question1"
encoded = _encode_for_mongo(field)
self.assertEqual(encoded, (
"%(dollar)ssection1%(dot)sgroup01%(dot)squestion1" % {
"dollar": base64.b64encode("$"),
"dot": base64.b64encode(".")}))
decoded = _decode_from_mongo(encoded)
self.assertEqual(field, decoded)
def test_api_with_or_query(self):
"""Test that an or query is interpreted correctly since we use an
internal or query to filter out deleted records"""
for i in range(1, 3):
self._submit_transport_instance(i)
# record 0: does NOT have the 'transport/loop_over_transport_types_freq
# uency/ambulance/frequency_to_referral_facility' field
# record 1: 'transport/loop_over_transport_types_frequency/ambulance/fr
# equency_to_referral_facility': 'daily'
# record 2: 'transport/loop_over_transport_types_frequency/ambulance/fr
# equency_to_referral_facility': 'weekly'
params = {
'query':
'{"$or": [{"transport/loop_over_transport_types_frequency/ambulanc'
'e/frequency_to_referral_facility": "weekly"}, {"transport/loop_ov'
'er_transport_types_frequency/ambulance/frequency_to_referral_faci'
'lity": "daily"}]}'}
response = self.client.get(self.api_url, params)
self.assertEqual(response.status_code, 200)
data = json.loads(response.content)
self.assertEqual(len(data), 2)
# check that blank params give us all our records i.e. 3
params = {}
response = self.client.get(self.api_url, params)
self.assertEqual(response.status_code, 200)
data = json.loads(response.content)
self.assertEqual(len(data), 3)
def test_api_cors_options(self):
response = self.anon.options(self.api_url)
allowed_headers = ['Accept', 'Origin', 'X-Requested-With',
'Authorization']
provided_headers = [h.strip() for h in response[
'Access-Control-Allow-Headers'].split(',')]
self.assertListEqual(allowed_headers, provided_headers)
self.assertEqual(response['Access-Control-Allow-Methods'], 'GET')
self.assertEqual(response['Access-Control-Allow-Origin'], '*')
|
jomolinare/kobocat
|
onadata/apps/main/tests/test_form_api.py
|
Python
|
bsd-2-clause
| 7,311
|
"""Tests for calls that span files.
These used to be a problem when we built a (single-file--whoops!) call graph,
but we don't anymore, so we can probably delete this at some point.
"""
from dxr.testing import DxrInstanceTestCase
class CrossFileCallerTests(DxrInstanceTestCase):
def test_callers(self):
"""Make sure a "caller" needle is laid down at the callsite, pointing
to the called function."""
self.found_line_eq('callers:another_file(int)',
u'int a = <b>another_file(blah)</b>;',
5)
|
gartung/dxr
|
dxr/plugins/clang/tests/test_cross_file_callers/test_cross_file_callers.py
|
Python
|
mit
| 576
|
import threading
import shared
import time
import sys
import os
import pickle
import tr#anslate
from helper_sql import *
from debug import logger
"""
The singleCleaner class is a timer-driven thread that cleans data structures
to free memory, resends messages when a remote node doesn't respond, and
sends pong messages to keep connections alive if the network isn't busy.
It cleans these data structures in memory:
inventory (moves data to the on-disk sql database)
inventorySets (clears then reloads data out of sql database)
It cleans these tables on the disk:
inventory (clears expired objects)
pubkeys (clears pubkeys older than 4 weeks old which we have not used personally)
It resends messages when there has been no response:
resends getpubkey messages in 5 days (then 10 days, then 20 days, etc...)
resends msg messages in 5 days (then 10 days, then 20 days, etc...)
"""
class singleCleaner(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
timeWeLastClearedInventoryAndPubkeysTables = 0
try:
shared.maximumLengthOfTimeToBotherResendingMessages = (float(shared.config.get('bitmessagesettings', 'stopresendingafterxdays')) * 24 * 60 * 60) + (float(shared.config.get('bitmessagesettings', 'stopresendingafterxmonths')) * (60 * 60 * 24 *365)/12)
except:
# Either the user hasn't set stopresendingafterxdays and stopresendingafterxmonths yet or the options are missing from the config file.
shared.maximumLengthOfTimeToBotherResendingMessages = float('inf')
while True:
shared.UISignalQueue.put((
'updateStatusBar', 'Doing housekeeping (Flushing inventory in memory to disk...)'))
with shared.inventoryLock: # If you use both the inventoryLock and the sqlLock, always use the inventoryLock OUTSIDE of the sqlLock.
with SqlBulkExecute() as sql:
for hash, storedValue in shared.inventory.items():
objectType, streamNumber, payload, expiresTime, tag = storedValue
sql.execute(
'''INSERT INTO inventory VALUES (?,?,?,?,?,?)''',
hash,
objectType,
streamNumber,
payload,
expiresTime,
tag)
del shared.inventory[hash]
shared.UISignalQueue.put(('updateStatusBar', ''))
shared.broadcastToSendDataQueues((
0, 'pong', 'no data')) # commands the sendData threads to send out a pong message if they haven't sent anything else in the last five minutes. The socket timeout-time is 10 minutes.
# If we are running as a daemon then we are going to fill up the UI
# queue which will never be handled by a UI. We should clear it to
# save memory.
if shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'):
shared.UISignalQueue.queue.clear()
if timeWeLastClearedInventoryAndPubkeysTables < int(time.time()) - 7380:
timeWeLastClearedInventoryAndPubkeysTables = int(time.time())
sqlExecute(
'''DELETE FROM inventory WHERE expirestime<? ''',
int(time.time()) - (60 * 60 * 3))
# pubkeys
sqlExecute(
'''DELETE FROM pubkeys WHERE time<? AND usedpersonally='no' ''',
int(time.time()) - shared.lengthOfTimeToHoldOnToAllPubkeys)
# Let us resend getpubkey objects if we have not yet heard a pubkey, and also msg objects if we have not yet heard an acknowledgement
queryreturn = sqlQuery(
'''select toaddress, ackdata, status FROM sent WHERE ((status='awaitingpubkey' OR status='msgsent') AND folder='sent' AND sleeptill<? AND senttime>?) ''',
int(time.time()),
int(time.time()) - shared.maximumLengthOfTimeToBotherResendingMessages)
for row in queryreturn:
if len(row) < 2:
with shared.printLock:
sys.stderr.write(
'Something went wrong in the singleCleaner thread: a query did not return the requested fields. ' + repr(row))
time.sleep(3)
break
toAddress, ackData, status = row
if status == 'awaitingpubkey':
resendPubkeyRequest(toAddress)
elif status == 'msgsent':
resendMsg(ackData)
# Let's also clear and reload shared.inventorySets to keep it from
# taking up an unnecessary amount of memory.
for streamNumber in shared.inventorySets:
shared.inventorySets[streamNumber] = set()
queryData = sqlQuery('''SELECT hash FROM inventory WHERE streamnumber=?''', streamNumber)
for row in queryData:
shared.inventorySets[streamNumber].add(row[0])
with shared.inventoryLock:
for hash, storedValue in shared.inventory.items():
objectType, streamNumber, payload, expiresTime, tag = storedValue
if not streamNumber in shared.inventorySets:
shared.inventorySets[streamNumber] = set()
shared.inventorySets[streamNumber].add(hash)
# Let us write out the knowNodes to disk if there is anything new to write out.
if shared.needToWriteKnownNodesToDisk:
shared.knownNodesLock.acquire()
output = open(shared.appdata + 'knownnodes.dat', 'wb')
try:
pickle.dump(shared.knownNodes, output)
output.close()
except Exception as err:
if "Errno 28" in str(err):
logger.fatal('(while receiveDataThread shared.needToWriteKnownNodesToDisk) Alert: Your disk or data storage volume is full. ')
shared.UISignalQueue.put(('alert', (tr.translateText("MainWindow", "Disk full"), tr.translateText("MainWindow", 'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'), True)))
if shared.daemon:
os._exit(0)
shared.knownNodesLock.release()
shared.needToWriteKnownNodesToDisk = False
time.sleep(300)
def resendPubkeyRequest(address):
logger.debug('It has been a long time and we haven\'t heard a response to our getpubkey request. Sending again.')
try:
del shared.neededPubkeys[
address] # We need to take this entry out of the shared.neededPubkeys structure because the shared.workerQueue checks to see whether the entry is already present and will not do the POW and send the message because it assumes that it has already done it recently.
except:
pass
shared.UISignalQueue.put((
'updateStatusBar', 'Doing work necessary to again attempt to request a public key...'))
sqlExecute(
'''UPDATE sent SET status='msgqueued' WHERE toaddress=?''',
address)
shared.workerQueue.put(('sendmessage', ''))
def resendMsg(ackdata):
logger.debug('It has been a long time and we haven\'t heard an acknowledgement to our msg. Sending again.')
sqlExecute(
'''UPDATE sent SET status='msgqueued' WHERE ackdata=?''',
ackdata)
shared.workerQueue.put(('sendmessage', ''))
shared.UISignalQueue.put((
'updateStatusBar', 'Doing work necessary to again attempt to deliver a message...'))
|
JosephGoulden/PyBitmessageF2F
|
src/class_singleCleaner.py
|
Python
|
mit
| 7,922
|