repo_name
stringlengths 5
100
| path
stringlengths 4
299
| copies
stringclasses 990
values | size
stringlengths 4
7
| content
stringlengths 666
1.03M
| license
stringclasses 15
values | hash
int64 -9,223,351,895,964,839,000
9,223,297,778B
| line_mean
float64 3.17
100
| line_max
int64 7
1k
| alpha_frac
float64 0.25
0.98
| autogenerated
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|
chirilo/remo | remo/profiles/helpers.py | 3 | 2078 | import urlparse
from datetime import timedelta
from django.utils import timezone
from django.conf import settings
from funfactory.helpers import urlparams
from jingo import register
from libravatar import libravatar_url
from remo.profiles.models import FunctionalArea, UserAvatar
from remo.reports.utils import get_last_report
INACTIVE_HIGH = timedelta(weeks=8)
INACTIVE_LOW = timedelta(weeks=4)
@register.filter
def get_avatar_url(user, size=50):
"""Get a url pointing to user's avatar.
The libravatar network is used for avatars. Return cached value if
its last update was less than 24 hours before. Optional argument
size can be provided to set the avatar size.
"""
if not user:
return None
default_img_url = reduce(lambda u, x: urlparse.urljoin(u, x),
[settings.SITE_URL,
settings.STATIC_URL,
'base/img/remo/remo_avatar.png'])
user_avatar, created = UserAvatar.objects.get_or_create(user=user)
now = timezone.now()
if (user_avatar.last_update < now - timedelta(days=7)) or created:
user_avatar.avatar_url = libravatar_url(email=user.email, https=True)
user_avatar.save()
avatar_url = urlparams(user_avatar.avatar_url, default=default_img_url)
if size != -1:
avatar_url = urlparams(avatar_url, size=size)
return avatar_url
@register.filter
def get_functional_area(name):
"""Return the Functional Area object given the name."""
try:
return FunctionalArea.objects.get(name=name)
except FunctionalArea.DoesNotExist:
return None
@register.filter
def get_activity_level(user):
"""Return user's inactivity level."""
last_report = get_last_report(user)
if not last_report:
return ''
today = timezone.now().date()
inactivity_period = today - last_report.report_date
if inactivity_period > INACTIVE_LOW:
if inactivity_period > INACTIVE_HIGH:
return 'inactive-high'
return 'inactive-low'
return ''
| bsd-3-clause | 4,446,051,624,484,907,500 | 26.706667 | 77 | 0.671319 | false |
na-ka-na/object-query | src/example/common_test.py | 1 | 4538 | import sys
import subprocess
TEST_SQL_QUERIES = [
# 1
"SELECT financial.quarterly_profits,financial.quarterly_revenues,all_employees.id,\
all_employees.name,all_employees.active,all_employees.active_direct_reports,\
all_employees.enumx, all_employees.enumy,founded,board_of_directors\
FROM Example1.Company",
# 2
"SELECT all_employees.id, all_employees.name\
FROM Example1.Company\
WHERE all_employees.id IS NOT NULL AND\
((all_employees.name='def' AND all_employees.active=true) OR\
all_employees.name='abc') AND\
financial.quarterly_profits>0",
# 3
"SELECT all_employees.id, financial.quarterly_revenues/all_employees.active_direct_reports\
FROM Example1.Company\
WHERE all_employees.active_direct_reports > 0 AND\
financial.quarterly_revenues*2 > 1",
# 4
"SELECT financial.quarterly_profits,all_employees.name,all_employees.active\
FROM Example1.Company\
ORDER BY all_employees.active,financial.quarterly_profits DESC,all_employees.id ASC",
# 5
"SELECT STR(all_employees.id) + ': ' + all_employees.name + ' (' + STR(all_employees.active) + ')' AS employee,\
STR(all_employees.id) + ' ' + employee + ' ' + STR(founded) AS employee2\
FROM Example1.Company\
WHERE employee2 LIKE '.*true.*'",
# 6
"SELECT all_employees.name, all_employees.active_direct_reports\
FROM Example1.Company\
WHERE all_employees.active_direct_reports IS NOT NULL",
# 7
"SELECT EmployeeStr(all_employees.name, all_employees.id), STR(all_employees.id), STR(all_employees)\
FROM Example1.Company",
# 8
"SELECT *, all_employees.* AS emp\
FROM Example1.Company",
]
def runTest(querytype, testnum, cmake_prefix_paths):
SOURCE_DIR = '../../src'
data_file = SOURCE_DIR + '/example/example1.json'
golden_out = querytype + '_golden' + str(testnum) + '.out'
actual_out = querytype + '_actual' + str(testnum) + '.out'
cmd_parts = ['../main/RunQuery']
cmd_parts.append('--queryType=' + querytype)
cmd_parts.append('--codeGenDir=' + SOURCE_DIR + '/example')
cmd_parts.append('--codeGenPrefix=' + querytype + '_generated_query' + str(testnum))
cmd_parts.append('--codeCompileDir=.')
if querytype == 'proto':
cmd_parts.append('--cppProtoHeader=example1.pb.h')
cmd_parts.append('--cppProtoLib=./libExampleProtos.so')
cmd_parts.append('--cppExtraIncludes=proto_example_utils.h')
elif querytype == 'json':
cmd_parts.append('--cppExtraIncludes=json_example_utils.h')
cppExtraIncludeDirs = []
cppExtraLinkLibDirs = []
if len(cmake_prefix_paths) > 0:
cppExtraIncludeDirs.extend([p + '/include' for p in cmake_prefix_paths])
cppExtraLinkLibDirs.extend([p + '/lib' for p in cmake_prefix_paths])
if len(cppExtraIncludeDirs) > 0:
cmd_parts.append('--cppExtraIncludeDirs=' + ','.join(cppExtraIncludeDirs))
if len(cppExtraLinkLibDirs) > 0:
cmd_parts.append('--cppExtraLinkLibDirs=' + ','.join(cppExtraLinkLibDirs))
cmd_parts.append(TEST_SQL_QUERIES[testnum-1])
cmd_parts.append(data_file)
# subprocess.check* will raise error if command fails
sys.stderr.write('RUNNING ' + ' '.join(cmd_parts) + '\n')
with open(actual_out, 'w') as acutal_hndl:
subprocess.check_call(cmd_parts, stdout=acutal_hndl)
# diff doesn't return non zero exit if files differ, so do it manually
cmd_parts = ['diff', '--brief', golden_out, actual_out]
sys.stderr.write('RUNNING ' + ' '.join(cmd_parts) + '\n')
diff_res = subprocess.check_output(cmd_parts)
if len(diff_res) > 0:
sys.stderr.write(diff_res)
exit(1)
sys.stderr.write('Success\n')
if __name__ == "__main__":
if len(sys.argv) < 3:
sys.stderr.write('Invalid num arguments, expected atleast 2, querytype, testnum\n')
sys.exit(1)
querytype = sys.argv[1]
if querytype != 'proto' and querytype != 'json':
sys.stderr.write('querytype should be either proto or json')
sys.exit(1)
testnum = int(sys.argv[2])
if (testnum < 1) or (testnum > len(TEST_SQL_QUERIES)):
sys.stderr.write('Invalid testnum ' + str(testnum) + ' valid range: [1,' +
str(len(TEST_SQL_QUERIES)) + ']')
sys.exit(1)
cmake_prefix_paths = []
if len(sys.argv) >= 4:
cmake_prefix_paths = sys.argv[3].split(',')
runTest(querytype, testnum, cmake_prefix_paths)
| apache-2.0 | -3,920,341,204,342,473,700 | 38.807018 | 116 | 0.641692 | false |
mdeemer/XlsxWriter | xlsxwriter/test/worksheet/test_write_row.py | 8 | 2661 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, [email protected]
#
import unittest
from ...compatibility import StringIO
from ...worksheet import Worksheet
from ...format import Format
class TestWriteRow(unittest.TestCase):
"""
Test the Worksheet _write_row() method.
"""
def setUp(self):
self.fh = StringIO()
self.worksheet = Worksheet()
self.worksheet._set_filehandle(self.fh)
def test_write_row_1(self):
"""Test the _write_row() method"""
self.worksheet._write_row(0, None)
exp = """<row r="1">"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_row_2(self):
"""Test the _write_row() method"""
self.worksheet._write_row(2, '2:2')
exp = """<row r="3" spans="2:2">"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_row_3(self):
"""Test the _write_row() method"""
self.worksheet._write_row(1, None, [30, None, 0, 0, 0])
exp = """<row r="2" ht="30" customHeight="1">"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_row_4(self):
"""Test the _write_row() method"""
self.worksheet._write_row(3, None, [15, None, 1, 0, 0])
exp = """<row r="4" hidden="1">"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_row_5(self):
"""Test the _write_row() method"""
cell_format = Format({'xf_index': 1})
self.worksheet._write_row(6, None, [15, cell_format, 0, 0, 0])
exp = """<row r="7" s="1" customFormat="1">"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_row_6(self):
"""Test the _write_row() method"""
self.worksheet._write_row(9, None, [3, None, 0, 0, 0])
exp = """<row r="10" ht="3" customHeight="1">"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_row_7(self):
"""Test the _write_row() method"""
self.worksheet._write_row(12, None, [24, None, 1, 0, 0])
exp = """<row r="13" ht="24" hidden="1" customHeight="1">"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_row_8(self):
"""Test the _write_row() method"""
self.worksheet._write_row(12, None, [24, None, 1, 0, 0], 1)
exp = """<row r="13" ht="24" hidden="1" customHeight="1"/>"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
| bsd-2-clause | 6,492,686,246,478,060,000 | 24.342857 | 79 | 0.527245 | false |
hdinsight/hue | apps/sqoop/src/sqoop/client/submission.py | 33 | 3758 | # 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.
import logging
from desktop.lib.python_util import force_dict_to_strings
from exception import SqoopException
from config import Config
class Submission(object):
"""
Sqoop submission object.
Example of sqoop submission dictionary received by server: {
"progress": 0.0,
"last-update-date": 1371775331096,
"external-id": "job_201306201740_0001",
"status": "RUNNING",
"job": 1,
"creation-date": 1371775311721,
"external-link": "http://solaris:50030/jobdetails.jsp?jobid=job_201306201740_0001"
}
"""
def __init__(self, job_id, status, progress, created, updated, enabled=True, **kwargs):
self.job_id = job_id
self.status = status
self.progress = progress
self.created = created
self.updated = updated
self.external_id = kwargs.get('external_id', None)
self.external_link = kwargs.get('external_link', None)
self.enabled = enabled
@staticmethod
def from_dict(submission_dict):
submission_dict['job_id'] = submission_dict['job']
submission_dict['created'] = submission_dict['creation-date']
submission_dict['updated'] = submission_dict['last-update-date']
submission_dict['external_id'] = submission_dict.get('external-id', None)
submission_dict['external_link'] = submission_dict.get('external-link', None)
return Submission(**force_dict_to_strings(submission_dict))
def to_dict(self):
d = {
'job': self.job_id,
'status': self.status,
'progress': self.progress,
'creation-date': self.created,
'last-update-date': self.updated,
'enabled': self.enabled
}
if self.external_id:
d['external-id'] = self.external_id
if self.external_id:
d['external-link'] = self.external_link
return d
class SqoopSubmissionException(Exception):
def __init__(self, job_id, status, progress, created, updated, **kwargs):
self.job_id = job_id
self.status = status
self.progress = progress
self.created = created
self.updated = updated
self.exception = kwargs.get('exception', None)
self.exception_trace = kwargs.get('exception_trace', None)
@staticmethod
def from_dict(submission_dict):
submission_dict['job_id'] = submission_dict['job']
submission_dict['created'] = submission_dict['creation-date']
submission_dict['updated'] = submission_dict['last-update-date']
submission_dict['exception'] = submission_dict.get('exception', None)
submission_dict['exception_trace'] = submission_dict.get('exception-trace', None)
submission = SqoopSubmissionException(**force_dict_to_strings(submission_dict))
return submission
def to_dict(self):
d = {
'job': self.job_id,
'status': self.status,
'progress': self.progress,
'creation-date': self.created,
'last-update-date': self.updated
}
if self.exception:
d['exception'] = self.exception
if self.exception_trace:
d['exception-trace'] = self.exception_trace
return d | apache-2.0 | -7,805,499,011,752,448,000 | 32.265487 | 89 | 0.691325 | false |
rnicoll/dogecoin | contrib/devtools/circular-dependencies.py | 14 | 3135 | #!/usr/bin/env python3
# Copyright (c) 2018-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import sys
import re
MAPPING = {
'core_read.cpp': 'core_io.cpp',
'core_write.cpp': 'core_io.cpp',
}
# Directories with header-based modules, where the assumption that .cpp files
# define functions and variables declared in corresponding .h files is
# incorrect.
HEADER_MODULE_PATHS = [
'interfaces/'
]
def module_name(path):
if path in MAPPING:
path = MAPPING[path]
if any(path.startswith(dirpath) for dirpath in HEADER_MODULE_PATHS):
return path
if path.endswith(".h"):
return path[:-2]
if path.endswith(".c"):
return path[:-2]
if path.endswith(".cpp"):
return path[:-4]
return None
files = dict()
deps = dict()
RE = re.compile("^#include <(.*)>")
# Iterate over files, and create list of modules
for arg in sys.argv[1:]:
module = module_name(arg)
if module is None:
print("Ignoring file %s (does not constitute module)\n" % arg)
else:
files[arg] = module
deps[module] = set()
# Iterate again, and build list of direct dependencies for each module
# TODO: implement support for multiple include directories
for arg in sorted(files.keys()):
module = files[arg]
with open(arg, 'r', encoding="utf8") as f:
for line in f:
match = RE.match(line)
if match:
include = match.group(1)
included_module = module_name(include)
if included_module is not None and included_module in deps and included_module != module:
deps[module].add(included_module)
# Loop to find the shortest (remaining) circular dependency
have_cycle = False
while True:
shortest_cycle = None
for module in sorted(deps.keys()):
# Build the transitive closure of dependencies of module
closure = dict()
for dep in deps[module]:
closure[dep] = []
while True:
old_size = len(closure)
old_closure_keys = sorted(closure.keys())
for src in old_closure_keys:
for dep in deps[src]:
if dep not in closure:
closure[dep] = closure[src] + [src]
if len(closure) == old_size:
break
# If module is in its own transitive closure, it's a circular dependency; check if it is the shortest
if module in closure and (shortest_cycle is None or len(closure[module]) + 1 < len(shortest_cycle)):
shortest_cycle = [module] + closure[module]
if shortest_cycle is None:
break
# We have the shortest circular dependency; report it
module = shortest_cycle[0]
print("Circular dependency: %s" % (" -> ".join(shortest_cycle + [module])))
# And then break the dependency to avoid repeating in other cycles
deps[shortest_cycle[-1]] = deps[shortest_cycle[-1]] - set([module])
have_cycle = True
sys.exit(1 if have_cycle else 0)
| mit | -2,165,279,856,597,644,000 | 33.450549 | 109 | 0.622967 | false |
lancezlin/ml_template_py | lib/python2.7/site-packages/pandas/io/tests/parser/skiprows.py | 7 | 7257 | # -*- coding: utf-8 -*-
"""
Tests that skipped rows are properly handled during
parsing for all of the parsers defined in parsers.py
"""
from datetime import datetime
import numpy as np
import pandas.util.testing as tm
from pandas import DataFrame
from pandas.compat import StringIO, range, lrange
class SkipRowsTests(object):
def test_skiprows_bug(self):
# see gh-505
text = """#foo,a,b,c
#foo,a,b,c
#foo,a,b,c
#foo,a,b,c
#foo,a,b,c
#foo,a,b,c
1/1/2000,1.,2.,3.
1/2/2000,4,5,6
1/3/2000,7,8,9
"""
data = self.read_csv(StringIO(text), skiprows=lrange(6), header=None,
index_col=0, parse_dates=True)
data2 = self.read_csv(StringIO(text), skiprows=6, header=None,
index_col=0, parse_dates=True)
expected = DataFrame(np.arange(1., 10.).reshape((3, 3)),
columns=[1, 2, 3],
index=[datetime(2000, 1, 1), datetime(2000, 1, 2),
datetime(2000, 1, 3)])
expected.index.name = 0
tm.assert_frame_equal(data, expected)
tm.assert_frame_equal(data, data2)
def test_deep_skiprows(self):
# see gh-4382
text = "a,b,c\n" + \
"\n".join([",".join([str(i), str(i + 1), str(i + 2)])
for i in range(10)])
condensed_text = "a,b,c\n" + \
"\n".join([",".join([str(i), str(i + 1), str(i + 2)])
for i in [0, 1, 2, 3, 4, 6, 8, 9]])
data = self.read_csv(StringIO(text), skiprows=[6, 8])
condensed_data = self.read_csv(StringIO(condensed_text))
tm.assert_frame_equal(data, condensed_data)
def test_skiprows_blank(self):
# see gh-9832
text = """#foo,a,b,c
#foo,a,b,c
#foo,a,b,c
#foo,a,b,c
1/1/2000,1.,2.,3.
1/2/2000,4,5,6
1/3/2000,7,8,9
"""
data = self.read_csv(StringIO(text), skiprows=6, header=None,
index_col=0, parse_dates=True)
expected = DataFrame(np.arange(1., 10.).reshape((3, 3)),
columns=[1, 2, 3],
index=[datetime(2000, 1, 1), datetime(2000, 1, 2),
datetime(2000, 1, 3)])
expected.index.name = 0
tm.assert_frame_equal(data, expected)
def test_skiprow_with_newline(self):
# see gh-12775 and gh-10911
data = """id,text,num_lines
1,"line 11
line 12",2
2,"line 21
line 22",2
3,"line 31",1"""
expected = [[2, 'line 21\nline 22', 2],
[3, 'line 31', 1]]
expected = DataFrame(expected, columns=[
'id', 'text', 'num_lines'])
df = self.read_csv(StringIO(data), skiprows=[1])
tm.assert_frame_equal(df, expected)
data = ('a,b,c\n~a\n b~,~e\n d~,'
'~f\n f~\n1,2,~12\n 13\n 14~')
expected = [['a\n b', 'e\n d', 'f\n f']]
expected = DataFrame(expected, columns=[
'a', 'b', 'c'])
df = self.read_csv(StringIO(data),
quotechar="~",
skiprows=[2])
tm.assert_frame_equal(df, expected)
data = ('Text,url\n~example\n '
'sentence\n one~,url1\n~'
'example\n sentence\n two~,url2\n~'
'example\n sentence\n three~,url3')
expected = [['example\n sentence\n two', 'url2']]
expected = DataFrame(expected, columns=[
'Text', 'url'])
df = self.read_csv(StringIO(data),
quotechar="~",
skiprows=[1, 3])
tm.assert_frame_equal(df, expected)
def test_skiprow_with_quote(self):
# see gh-12775 and gh-10911
data = """id,text,num_lines
1,"line '11' line 12",2
2,"line '21' line 22",2
3,"line '31' line 32",1"""
expected = [[2, "line '21' line 22", 2],
[3, "line '31' line 32", 1]]
expected = DataFrame(expected, columns=[
'id', 'text', 'num_lines'])
df = self.read_csv(StringIO(data), skiprows=[1])
tm.assert_frame_equal(df, expected)
def test_skiprow_with_newline_and_quote(self):
# see gh-12775 and gh-10911
data = """id,text,num_lines
1,"line \n'11' line 12",2
2,"line \n'21' line 22",2
3,"line \n'31' line 32",1"""
expected = [[2, "line \n'21' line 22", 2],
[3, "line \n'31' line 32", 1]]
expected = DataFrame(expected, columns=[
'id', 'text', 'num_lines'])
df = self.read_csv(StringIO(data), skiprows=[1])
tm.assert_frame_equal(df, expected)
data = """id,text,num_lines
1,"line '11\n' line 12",2
2,"line '21\n' line 22",2
3,"line '31\n' line 32",1"""
expected = [[2, "line '21\n' line 22", 2],
[3, "line '31\n' line 32", 1]]
expected = DataFrame(expected, columns=[
'id', 'text', 'num_lines'])
df = self.read_csv(StringIO(data), skiprows=[1])
tm.assert_frame_equal(df, expected)
data = """id,text,num_lines
1,"line '11\n' \r\tline 12",2
2,"line '21\n' \r\tline 22",2
3,"line '31\n' \r\tline 32",1"""
expected = [[2, "line '21\n' \r\tline 22", 2],
[3, "line '31\n' \r\tline 32", 1]]
expected = DataFrame(expected, columns=[
'id', 'text', 'num_lines'])
df = self.read_csv(StringIO(data), skiprows=[1])
tm.assert_frame_equal(df, expected)
def test_skiprows_lineterminator(self):
# see gh-9079
data = '\n'.join(['SMOSMANIA ThetaProbe-ML2X ',
'2007/01/01 01:00 0.2140 U M ',
'2007/01/01 02:00 0.2141 M O ',
'2007/01/01 04:00 0.2142 D M '])
expected = DataFrame([['2007/01/01', '01:00', 0.2140, 'U', 'M'],
['2007/01/01', '02:00', 0.2141, 'M', 'O'],
['2007/01/01', '04:00', 0.2142, 'D', 'M']],
columns=['date', 'time', 'var', 'flag',
'oflag'])
# test with default line terminators "LF" and "CRLF"
df = self.read_csv(StringIO(data), skiprows=1, delim_whitespace=True,
names=['date', 'time', 'var', 'flag', 'oflag'])
tm.assert_frame_equal(df, expected)
df = self.read_csv(StringIO(data.replace('\n', '\r\n')),
skiprows=1, delim_whitespace=True,
names=['date', 'time', 'var', 'flag', 'oflag'])
tm.assert_frame_equal(df, expected)
# "CR" is not respected with the Python parser yet
if self.engine == 'c':
df = self.read_csv(StringIO(data.replace('\n', '\r')),
skiprows=1, delim_whitespace=True,
names=['date', 'time', 'var', 'flag', 'oflag'])
tm.assert_frame_equal(df, expected)
def test_skiprows_infield_quote(self):
# see gh-14459
data = 'a"\nb"\na\n1'
expected = DataFrame({'a': [1]})
df = self.read_csv(StringIO(data), skiprows=2)
tm.assert_frame_equal(df, expected)
| mit | 2,992,246,385,916,498,000 | 35.285 | 79 | 0.492352 | false |
DemocracyClub/EveryElection | every_election/apps/election_snooper/snoopers/aldc.py | 1 | 1511 | from datetime import datetime
from .base import BaseSnooper
from election_snooper.models import SnoopedElection
class ALDCScraper(BaseSnooper):
snooper_name = "ALDC"
base_url = "https://www.aldc.org/"
def get_all(self):
url = "{}category/forthcoming-by-elections/".format(self.base_url)
print(url)
soup = self.get_soup(url)
for tile in soup.find_all("article"):
title = tile.find("h2").text.strip()
detail_url = url + "#" + tile["id"]
date = tile.find("date").text.strip()
content = tile.find("div", {"class": "c-editor"}).find_all("p")
if content and content[0].text.lower().count("cause") == 1:
seat_control, cause = content[0].text.lower().split("cause")
cause = cause.split("\n")[0].strip(": .")
else:
cause = "unknown"
data = {
"title": title,
"source": url,
"cause": cause,
"detail": "\n".join([x.text for x in content]),
"snooper_name": self.snooper_name,
}
try:
data["date"] = datetime.strptime(date, "%B %d, %Y")
except ValueError:
pass
item, created = SnoopedElection.objects.update_or_create(
snooper_name=self.snooper_name, detail_url=detail_url, defaults=data
)
if created:
self.post_to_slack(item)
| bsd-3-clause | -653,901,966,267,699,000 | 34.139535 | 84 | 0.513567 | false |
romain-dartigues/ansible-modules-core | files/ini_file.py | 5 | 9129 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Jan-Piet Mens <jpmens () gmail.com>
# (c) 2015, Ales Nosek <anosek.nosek () gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
DOCUMENTATION = '''
---
module: ini_file
short_description: Tweak settings in INI files
extends_documentation_fragment: files
description:
- Manage (add, remove, change) individual settings in an INI-style file without having
to manage the file as a whole with, say, M(template) or M(assemble). Adds missing
sections if they don't exist.
- Before version 2.0, comments are discarded when the source file is read, and therefore will not show up in the destination file.
version_added: "0.9"
options:
dest:
description:
- Path to the INI-style file; this file is created if required
required: true
default: null
section:
description:
- Section name in INI file. This is added if C(state=present) automatically when
a single value is being set.
required: true
default: null
option:
description:
- if set (required for changing a I(value)), this is the name of the option.
- May be omitted if adding/removing a whole I(section).
required: false
default: null
value:
description:
- the string value to be associated with an I(option). May be omitted when removing an I(option).
required: false
default: null
backup:
description:
- Create a backup file including the timestamp information so you can get
the original file back if you somehow clobbered it incorrectly.
required: false
default: "no"
choices: [ "yes", "no" ]
others:
description:
- all arguments accepted by the M(file) module also work here
required: false
state:
description:
- If set to C(absent) the option or section will be removed if present instead of created.
required: false
default: "present"
choices: [ "present", "absent" ]
no_extra_spaces:
description:
- do not insert spaces before and after '=' symbol
required: false
default: false
version_added: "2.1"
notes:
- While it is possible to add an I(option) without specifying a I(value), this makes
no sense.
- A section named C(default) cannot be added by the module, but if it exists, individual
options within the section can be updated. (This is a limitation of Python's I(ConfigParser).)
Either use M(template) to create a base INI file with a C([default]) section, or use
M(lineinfile) to add the missing line.
requirements: [ ConfigParser ]
author:
- "Jan-Piet Mens (@jpmens)"
- "Ales Nosek (@noseka1)"
'''
EXAMPLES = '''
# Ensure "fav=lemonade is in section "[drinks]" in specified file
- ini_file: dest=/etc/conf section=drinks option=fav value=lemonade mode=0600 backup=yes
- ini_file: dest=/etc/anotherconf
section=drinks
option=temperature
value=cold
backup=yes
'''
import os
import re
# ==============================================================
# match_opt
def match_opt(option, line):
option = re.escape(option)
return re.match('%s( |\t)*=' % option, line) \
or re.match('# *%s( |\t)*=' % option, line) \
or re.match('; *%s( |\t)*=' % option, line)
# ==============================================================
# match_active_opt
def match_active_opt(option, line):
option = re.escape(option)
return re.match('%s( |\t)*=' % option, line)
# ==============================================================
# do_ini
def do_ini(module, filename, section=None, option=None, value=None, state='present', backup=False, no_extra_spaces=False):
if not os.path.exists(filename):
try:
open(filename,'w').close()
except:
module.fail_json(msg="Destination file %s not writable" % filename)
ini_file = open(filename, 'r')
try:
ini_lines = ini_file.readlines()
# append a fake section line to simplify the logic
ini_lines.append('[')
finally:
ini_file.close()
within_section = not section
section_start = 0
changed = False
if no_extra_spaces:
assignment_format = '%s=%s\n'
else:
assignment_format = '%s = %s\n'
for index, line in enumerate(ini_lines):
if line.startswith('[%s]' % section):
within_section = True
section_start = index
elif line.startswith('['):
if within_section:
if state == 'present':
# insert missing option line at the end of the section
for i in range(index, 0, -1):
# search backwards for previous non-blank or non-comment line
if not re.match(r'^[ \t]*([#;].*)?$', ini_lines[i - 1]):
ini_lines.insert(i, assignment_format % (option, value))
changed = True
break
elif state == 'absent' and not option:
# remove the entire section
del ini_lines[section_start:index]
changed = True
break
else:
if within_section and option:
if state == 'present':
# change the existing option line
if match_opt(option, line):
newline = assignment_format % (option, value)
changed = ini_lines[index] != newline
ini_lines[index] = newline
if changed:
# remove all possible option occurences from the rest of the section
index = index + 1
while index < len(ini_lines):
line = ini_lines[index]
if line.startswith('['):
break
if match_active_opt(option, line):
del ini_lines[index]
else:
index = index + 1
break
else:
# comment out the existing option line
if match_active_opt(option, line):
ini_lines[index] = '#%s' % ini_lines[index]
changed = True
break
# remove the fake section line
del ini_lines[-1:]
if not within_section and option and state == 'present':
ini_lines.append('[%s]\n' % section)
ini_lines.append(assignment_format % (option, value))
changed = True
backup_file = None
if changed and not module.check_mode:
if backup:
backup_file = module.backup_local(filename)
ini_file = open(filename, 'w')
try:
ini_file.writelines(ini_lines)
finally:
ini_file.close()
return (changed, backup_file)
# ==============================================================
# main
def main():
module = AnsibleModule(
argument_spec = dict(
dest = dict(required=True),
section = dict(required=True),
option = dict(required=False),
value = dict(required=False),
backup = dict(default='no', type='bool'),
state = dict(default='present', choices=['present', 'absent']),
no_extra_spaces = dict(required=False, default=False, type='bool')
),
add_file_common_args = True,
supports_check_mode = True
)
dest = os.path.expanduser(module.params['dest'])
section = module.params['section']
option = module.params['option']
value = module.params['value']
state = module.params['state']
backup = module.params['backup']
no_extra_spaces = module.params['no_extra_spaces']
(changed,backup_file) = do_ini(module, dest, section, option, value, state, backup, no_extra_spaces)
file_args = module.load_file_common_arguments(module.params)
changed = module.set_fs_attributes_if_different(file_args, changed)
results = { 'changed': changed, 'msg': "OK", 'dest': dest }
if backup_file is not None:
results['backup_file'] = backup_file
# Mission complete
module.exit_json(**results)
# import module snippets
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()
| gpl-3.0 | -6,194,531,008,285,917,000 | 34.247104 | 135 | 0.569394 | false |
VitalPet/bank-statement-import | account_bank_statement_import_ofx/tests/test_import_bank_statement.py | 8 | 1451 | # -*- coding: utf-8 -*-
from openerp.tests.common import TransactionCase
from openerp.modules.module import get_module_resource
class TestOfxFile(TransactionCase):
"""Tests for import bank statement ofx file format
(account.bank.statement.import)
"""
def setUp(self):
super(TestOfxFile, self).setUp()
self.statement_import_model = self.env['account.bank.statement.import']
self.bank_statement_model = self.env['account.bank.statement']
def test_ofx_file_import(self):
ofx_file_path = get_module_resource(
'account_bank_statement_import_ofx',
'test_ofx_file', 'test_ofx.ofx')
ofx_file = open(ofx_file_path, 'rb').read().encode('base64')
bank_statement = self.statement_import_model.create(
dict(data_file=ofx_file))
bank_statement.import_file()
bank_st_record = self.bank_statement_model.search(
[('name', '=', '000000123')])[0]
self.assertEquals(bank_st_record.balance_start, 2156.56)
self.assertEquals(bank_st_record.balance_end_real, 1796.56)
line = bank_st_record.line_ids[0]
self.assertEquals(line.name, 'Agrolait')
self.assertEquals(line.ref, '219378')
self.assertEquals(line.partner_id.id, self.ref('base.res_partner_2'))
self.assertEquals(
line.bank_account_id.id,
self.ref('account_bank_statement_import.ofx_partner_bank_1'))
| agpl-3.0 | -5,732,413,137,133,032,000 | 40.457143 | 79 | 0.645072 | false |
pyrolysis/kinetic_schemes | agu-2019/agu_2019.py | 1 | 1956 | """
Cantera batch reactor example where kinetic scheme based on Agu 2019 paper for
biomass fast pyrolysis.
Reference
---------
Cornelius E. Agu, Christoph Pfeifer, Marianne Eikeland, Lars-Andre Tokheim,
and Britt M.E. Moldestad. Detailed One-Dimensional Model for Steam-Biomass
Gasification in a Bubbling Fluidized Bed. Energy and Fuels, vol. 33, pp.
7385-7397, 2019.
"""
import cantera as ct
import matplotlib.pyplot as plt
import numpy as np
# Cantera batch reactor example with Blasi biomass pyrolysis kinetics
# ----------------------------------------------------------------------------
tk = 773.15 # temperature [K]
p = 101_325.0 # pressure [Pa]
y = 'biomass:1 char:0 tar:0 volatiles:0' # initial mass fractions [-]
gas = ct.Solution('agu.cti')
gas.TPY = tk, p, y
r = ct.IdealGasConstPressureReactor(gas, energy='off')
sim = ct.ReactorNet([r])
states = ct.SolutionArray(gas, extra=['t'])
# time vector to evaluate reaction rates [s]
time = np.linspace(0, 25, num=1000)
for tm in time:
sim.advance(tm)
states.append(r.thermo.state, t=tm)
# Print
# ----------------------------------------------------------------------------
print(f"""
Input parameters
----------------
T = {tk} K
P = {p} Pa""")
print("""
Final mass fractions
--------------------""")
for s in states.species_names:
print(f'{s} = {states(s).Y[:, 0][-1]:.4f}')
# Plot
# ----------------------------------------------------------------------------
fig, ax = plt.subplots(tight_layout=True)
ax.plot(states.t, states('biomass').Y[:, 0], label='biomass')
ax.plot(states.t, states('char').Y[:, 0], label='char')
ax.plot(states.t, states('tar').Y[:, 0], label='tar')
ax.plot(states.t, states('volatiles').Y[:, 0], label='volatiles')
ax.grid(color='0.9')
ax.legend(loc='best')
ax.set_frame_on(False)
ax.tick_params(color='0.9')
ax.set_xlabel('Time [s]')
ax.set_ylabel('Mass fraction [-]')
plt.show()
| mit | -3,213,541,442,199,642,600 | 27.764706 | 78 | 0.566973 | false |
mganeva/mantid | scripts/LargeScaleStructures/ReflectometerCors.py | 1 | 3182 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
#pylint: disable=invalid-name
from __future__ import (absolute_import, division, print_function)
from mantid.simpleapi import *
def heliumDetectorEff(workspace):
''' Calculate the corrected Helium detector values. '''
ac= 6.022169e23 # Avogadro's constant mol-1
vm= 2.24136e4 # Molar volume of gas cm3 mol-1
gp= 10.0 # Gas pressure (atms)
gsig0= 5333.0e-24 # Gas cross section at LAM0 cm2
gt= 2.5 # Gas path length cm
lam0= 1.8 # Characteristic wavelength
gn= ac*gp/vm # Number density of gas
sgn= gn*gsig0*gt/lam0 # Exponential term for gas
OneMinusExponentialCor(InputWorkspace=workspace,OutputWorkspace=workspace,C=str(sgn),Operation="Divide")
wt= 60.014 # Molecular weight Ni-Cu g mol-1
rho= 8.00 # Density Ni-Cu g cm-3
ct= 0.05 # Monel (Ni-Cu) wall thickness cm
wsig0= 4.522e-24 # Wall cross section at LAM0 cm2
wn= ac*rho/wt # Number density of wall
swn= wn*wsig0*ct/lam0 # Exponential term for wall
ExponentialCorrection(InputWorkspace=workspace,OutputWorkspace=workspace,C1=str(swn),Operation="Divide")
# simple polynomial correction based on a D2O spectrum taken at 1.5 deg
PolynomialCorrection(InputWorkspace=workspace,OutputWorkspace=workspace,Coefficients="-1.3697,0.8602,-0.7839,0.2866,-0.0447,0.0025")
return
def monitor2Eff(workspace):
''' Calculate the corrected monitor2 values. '''
# expon= unt*(1-exp(-8.3047 * zz * x_mean ))
# yout[i]= yin[i]*(1.0-expon) / expon
# eout[i]= ein[i]*(1.0-expon) / expon
# The above correction is equivalent to: (1/unt - 1) + e^(-8.3047*zz*x)
# ------------------------------
# ( 1 - e^(-8.3047*zz*x) )
unt=0.24 # 0.05 # ratio of scintillator to total area
zz = 0.6 #0.03 # thickness(cm) of scintillator
c1 = 0.7112*zz #8.3047*zz
ExponentialCorrection(InputWorkspace=workspace,OutputWorkspace=workspace,C1=str(c1),Operation="Multiply")
shift = (1.0/unt)-1.0
CreateSingleValuedWorkspace(OutputWorkspace="shift",DataValue=str(shift),ErrorValue="0.0")
Plus(LHSWorkspace=workspace,RHSWorkspace="shift",OutputWorkspace=workspace)
mtd.remove("shift")
OneMinusExponentialCor(InputWorkspace=workspace,OutputWorkspace=workspace,C=str(c1))
return
def main():
'''This main routine. It is executed on if the script is run directly, not if it is imported.'''
LoadRawDialog(OutputWorkspace="ws",SpectrumMin="1",SpectrumMax="1")
ConvertUnits(InputWorkspace="ws",OutputWorkspace="ws",Target="Wavelength",AlignBins="1")
heliumDetectorEff("ws")
monitor2Eff("ws")
print("Done!")
if __name__ == '__main__':
main()
| gpl-3.0 | 4,819,791,908,584,293,000 | 42 | 136 | 0.631678 | false |
lrosengreen/cloudberry | old/timelapse.py | 1 | 3423 | #!/usr/bin/env python
from __future__ import division, print_function
# cloudberryCam v0 copyright (c) 2013-2015 Lars Rosengreen
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import datetime
import io
import os
import shutil
import sys
import time
import picamera
_current_directory = os.path.dirname(os.path.abspath(__file__))
_preview_directory = "/mnt/ramdisk/previews"
_picture_directory = _current_directory + "/pictures"
_start_time = datetime.datetime.now()
_timelapse_interval = 2 # how long to wait between taking pictures (in seconds)
def free_space():
"Free disk space in gigabytes."
s = os.statvfs('/')
return (s.f_bavail * s.f_frsize) / 1.0e9
def run():
if not os.path.exists(_preview_directory):
os.makedirs(_preview_directory)
if not os.path.exists(_picture_directory):
os.makedirs(_picture_directory)
counter = 0
with picamera.PiCamera() as camera:
camera.resolution = (2592, 1944) #2592, 1944
camera.vflip = True
camera.hflip = True
camera.annotate_background = True
camera.start_preview()
time.sleep(5)
start_time = datetime.datetime.now()
next_time = start_time
try:
timestamp = datetime.datetime.now()
while free_space() > 0.5:
timestamp = datetime.datetime.now()
next_time = next_time + datetime.timedelta(seconds=_timelapse_interval)
fname = os.path.join(_picture_directory, "{:06d} {}.jpg".format(counter, timestamp.strftime("%Y%b%d %Hh%Mm%Ss")))
camera.annotate_text = timestamp.strftime("%Y%b%d %H:%M:%S").lower()
camera.capture(fname)
#if counter % 20 == 0:
shutil.copy(fname, os.path.join(_preview_directory, "preview.jpg"))
# figure out how long to wait before taking next picture
if datetime.datetime.now() <= next_time:
wait_time = next_time - datetime.datetime.now()
wait_time = wait_time.seconds + wait_time.microseconds * 1e-6
else:
# It could be that the time to take next picture has already passed.
# In that case, wait time should be negative and value passed to
# time.sleep() should be 0.
wait_time = datetime.datetime.now() - next_time
wait_time = -1 * (wait_time.seconds + wait_time.microseconds * 1e-6)
print("time:{} images:{} wait:{}s".format(str(timestamp - start_time).split(".")[0], counter, wait_time))
time.sleep(0 if wait_time < 0 else wait_time)
counter += 1
finally:
camera.stop_preview()
camera.close()
if __name__ == "__main__":
run()
| gpl-3.0 | 4,989,787,037,272,037,000 | 37.460674 | 129 | 0.618755 | false |
Mhynlo/SickRage | sickbeard/notifiers/pushalot.py | 7 | 4268 | # coding=utf-8
# Author: Maciej Olesinski (https://github.com/molesinski/)
# Based on prowl.py by Nic Wolfe <[email protected]>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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.
#
# SickRage 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 SickRage. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
import sickbeard
from sickbeard import logger, common
class Notifier(object):
def __init__(self):
self.session = sickbeard.helpers.make_session()
def test_notify(self, pushalot_authorizationtoken):
return self._sendPushalot(
pushalot_authorizationtoken=pushalot_authorizationtoken,
event='Test',
message='Testing Pushalot settings from SickRage',
force=True
)
def notify_snatch(self, ep_name):
if sickbeard.PUSHALOT_NOTIFY_ONSNATCH:
self._sendPushalot(
pushalot_authorizationtoken=None,
event=common.notifyStrings[common.NOTIFY_SNATCH],
message=ep_name
)
def notify_download(self, ep_name):
if sickbeard.PUSHALOT_NOTIFY_ONDOWNLOAD:
self._sendPushalot(
pushalot_authorizationtoken=None,
event=common.notifyStrings[common.NOTIFY_DOWNLOAD],
message=ep_name
)
def notify_subtitle_download(self, ep_name, lang):
if sickbeard.PUSHALOT_NOTIFY_ONSUBTITLEDOWNLOAD:
self._sendPushalot(
pushalot_authorizationtoken=None,
event=common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD],
message='{0}:{1}'.format(ep_name, lang)
)
def notify_git_update(self, new_version='??'):
update_text = common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT]
title = common.notifyStrings[common.NOTIFY_GIT_UPDATE]
self._sendPushalot(
pushalot_authorizationtoken=None,
event=title,
message=update_text + new_version
)
def notify_login(self, ipaddress=''):
update_text = common.notifyStrings[common.NOTIFY_LOGIN_TEXT]
title = common.notifyStrings[common.NOTIFY_LOGIN]
self._sendPushalot(
pushalot_authorizationtoken=None,
event=title,
message=update_text.format(ipaddress)
)
def _sendPushalot(self, pushalot_authorizationtoken=None, event=None, message=None, force=False):
if not (sickbeard.USE_PUSHALOT or force):
return False
pushalot_authorizationtoken = pushalot_authorizationtoken or sickbeard.PUSHALOT_AUTHORIZATIONTOKEN
logger.log('Pushalot event: {0}'.format(event), logger.DEBUG)
logger.log('Pushalot message: {0}'.format(message), logger.DEBUG)
logger.log('Pushalot api: {0}'.format(pushalot_authorizationtoken), logger.DEBUG)
post_data = {
'AuthorizationToken': pushalot_authorizationtoken,
'Title': event or '',
'Body': message or ''
}
jdata = sickbeard.helpers.getURL(
'https://pushalot.com/api/sendmessage',
post_data=post_data, session=self.session,
returns='json'
) or {}
'''
{'Status': 200, 'Description': 'The request has been completed successfully.', 'Success': True}
'''
success = jdata.pop('Success', False)
if success:
logger.log('Pushalot notifications sent.', logger.DEBUG)
else:
logger.log('Pushalot notification failed: {0} {1}'.format(
jdata.get('Status', ''),
jdata.get('Description', 'Unknown')
), logger.ERROR)
return success
| gpl-3.0 | 8,081,017,744,685,623,000 | 35.169492 | 106 | 0.633786 | false |
rjschwei/azure-sdk-for-python | examples/AzureResourceViewer/AzureResourceViewer/storage_extensions.py | 11 | 2755 | #-------------------------------------------------------------------------
# Copyright (c) Microsoft. 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.
#--------------------------------------------------------------------------
def iterate_containers(self, prefix=None, include=None):
next_marker = None
while True:
results = self.list_containers(
prefix=prefix,
marker=next_marker,
include=include,
)
for result in results:
yield result
next_marker = results.next_marker
if not next_marker:
break
def iterate_queues(self, prefix=None, include=None):
next_marker = None
while True:
results = self.list_queues(
prefix=prefix,
marker=next_marker,
include=include,
)
for result in results:
yield result
next_marker = results.next_marker
if not next_marker:
break
def iterate_tables(self, table_name=None):
next_marker = None
while True:
results = self.query_tables(
table_name=table_name,
next_table_name=next_marker,
)
for result in results:
yield result
if hasattr(results, 'x_ms_continuation'):
next_marker = results.x_ms_continuation.get('NextTableName')
else:
break
def iterate_shares(self, prefix=None, include=None):
next_marker = None
while True:
results = self.list_shares(
prefix=prefix,
marker=next_marker,
include=include,
)
for result in results:
yield result
next_marker = results.next_marker
if not next_marker:
break
def iterate_blobs(self, container_name, prefix=None, include=None, delimiter=None):
next_marker = None
while True:
results = self.list_blobs(
container_name,
marker=next_marker,
prefix=prefix,
include=include,
delimiter=delimiter,
)
for result in results:
yield result
next_marker = results.next_marker
if not next_marker:
break
| mit | -4,219,986,029,349,866,500 | 27.677083 | 83 | 0.567744 | false |
cbrunet/ouf | src/ouf/filemodel/proxymodel.py | 1 | 2098 |
import os.path
from PyQt5 import QtCore
from ouf.filemodel import SortRole
# TODO: show/hide backups files (end with ~)
# TODO: dir first
class FileProxyModel(QtCore.QSortFilterProxyModel):
def __init__(self, parent=None):
super().__init__(parent)
self._current_path = ""
self.setDynamicSortFilter(True)
# self.setSortCaseSensitivity(False)
# self.setSortLocaleAware(True)
# self.setSortRole(SortRole)
self._show_hidden = False
self._show_dirs_only = False
@property
def current_path(self):
return self._current_path
@current_path.setter
def current_path(self, path):
self.invalidate()
self._current_path = path
@property
def show_hidden(self):
return self._show_hidden
@show_hidden.setter
def show_hidden(self, show):
self._show_hidden = show
self.invalidate() # Why doesn't invalidateFilter work?
@property
def show_dirs_only(self):
return self._show_dirs_only
@show_dirs_only.setter
def show_dirs_only(self, show):
self._show_dirs_only = show
self.invalidate() # Why doesn't invalidateFilter work?
def filterAcceptsRow(self, source_row, source_parent):
"""
Args:
source_row:
source_parent:
Returns:
"""
index = self.sourceModel().index(source_row, 0, source_parent)
if index.isValid():
item = index.internalPointer()
if self.current_path.startswith(item.path):
# Allow to navigate in hidden folder even if not visible
return True
if not self.show_hidden:
return not item.is_hidden
if self.show_dirs_only:
if not item.is_dir:
return False
return super().filterAcceptsRow(source_row, source_parent)
def lessThan(self, left, right):
if left.isValid() and right.isValid():
return left.data(SortRole) < right.data(SortRole)
return False
| gpl-3.0 | 1,528,479,035,053,375,000 | 23.97619 | 72 | 0.595806 | false |
jendap/tensorflow | tensorflow/python/data/experimental/kernel_tests/restructured_dataset_test.py | 3 | 3111 | # 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 the private `_RestructuredDataset` transformation."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.data.experimental.ops import batching
from tensorflow.python.data.kernel_tests import test_base
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.data.util import nest
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.platform import test
# TODO(b/117581999): Add eager specific test.
class RestructuredDatasetTest(test_base.DatasetTestBase):
@test_util.run_deprecated_v1
def testRestructureDataset(self):
components = (array_ops.placeholder(dtypes.int32),
(array_ops.placeholder(dtypes.int32, shape=[None]),
array_ops.placeholder(dtypes.int32, shape=[20, 30])))
dataset = dataset_ops.Dataset.from_tensors(components)
i32 = dtypes.int32
test_cases = [((i32, i32, i32), None),
(((i32, i32), i32), None),
((i32, i32, i32), (None, None, None)),
((i32, i32, i32), ([17], [17], [20, 30]))]
for new_types, new_shape_lists in test_cases:
# pylint: disable=protected-access
new = batching._RestructuredDataset(dataset, new_types, new_shape_lists)
# pylint: enable=protected-access
self.assertEqual(new_types, new.output_types)
if new_shape_lists is not None:
for expected_shape_list, shape in zip(
nest.flatten(new_shape_lists), nest.flatten(new.output_shapes)):
if expected_shape_list is None:
self.assertIs(None, shape.ndims)
else:
self.assertEqual(expected_shape_list, shape.as_list())
fail_cases = [((i32, dtypes.int64, i32), None),
((i32, i32, i32, i32), None),
((i32, i32, i32), ((None, None), None)),
((i32, i32, i32), (None, None, None, None)),
((i32, i32, i32), (None, [None], [21, 30]))]
for new_types, new_shape_lists in fail_cases:
with self.assertRaises(ValueError):
# pylint: disable=protected-access
new = batching._RestructuredDataset(dataset, new_types, new_shape_lists)
# pylint: enable=protected-access
if __name__ == "__main__":
test.main()
| apache-2.0 | 673,297,888,761,146,900 | 41.040541 | 80 | 0.650916 | false |
Mj258/weiboapi | srapyDemo/envs/Lib/site-packages/scrapy/utils/python.py | 19 | 9040 | """
This module contains essential stuff that should've come with Python itself ;)
It also contains functions (or functionality) which is in Python versions
higher than 2.5 which used to be the lowest version supported by Scrapy.
"""
import os
import re
import inspect
import weakref
import errno
import six
from functools import partial, wraps
def flatten(x):
"""flatten(sequence) -> list
Returns a single, flat list which contains all elements retrieved
from the sequence and all recursively contained sub-sequences
(iterables).
Examples:
>>> [1, 2, [3,4], (5,6)]
[1, 2, [3, 4], (5, 6)]
>>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, (8,9,10)])
[1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]"""
return list(iflatten(x))
def iflatten(x):
"""iflatten(sequence) -> iterator
Similar to ``.flatten()``, but returns iterator instead"""
for el in x:
if hasattr(el, "__iter__"):
for el_ in flatten(el):
yield el_
else:
yield el
def unique(list_, key=lambda x: x):
"""efficient function to uniquify a list preserving item order"""
seen = set()
result = []
for item in list_:
seenkey = key(item)
if seenkey in seen:
continue
seen.add(seenkey)
result.append(item)
return result
def str_to_unicode(text, encoding=None, errors='strict'):
"""Return the unicode representation of text in the given encoding. Unlike
.encode(encoding) this function can be applied directly to a unicode
object without the risk of double-decoding problems (which can happen if
you don't use the default 'ascii' encoding)
"""
if encoding is None:
encoding = 'utf-8'
if isinstance(text, str):
return text.decode(encoding, errors)
elif isinstance(text, unicode):
return text
else:
raise TypeError('str_to_unicode must receive a str or unicode object, got %s' % type(text).__name__)
def unicode_to_str(text, encoding=None, errors='strict'):
"""Return the str representation of text in the given encoding. Unlike
.encode(encoding) this function can be applied directly to a str
object without the risk of double-decoding problems (which can happen if
you don't use the default 'ascii' encoding)
"""
if encoding is None:
encoding = 'utf-8'
if isinstance(text, unicode):
return text.encode(encoding, errors)
elif isinstance(text, str):
return text
else:
raise TypeError('unicode_to_str must receive a unicode or str object, got %s' % type(text).__name__)
def re_rsearch(pattern, text, chunk_size=1024):
"""
This function does a reverse search in a text using a regular expression
given in the attribute 'pattern'.
Since the re module does not provide this functionality, we have to find for
the expression into chunks of text extracted from the end (for the sake of efficiency).
At first, a chunk of 'chunk_size' kilobytes is extracted from the end, and searched for
the pattern. If the pattern is not found, another chunk is extracted, and another
search is performed.
This process continues until a match is found, or until the whole file is read.
In case the pattern wasn't found, None is returned, otherwise it returns a tuple containing
the start position of the match, and the ending (regarding the entire text).
"""
def _chunk_iter():
offset = len(text)
while True:
offset -= (chunk_size * 1024)
if offset <= 0:
break
yield (text[offset:], offset)
yield (text, 0)
pattern = re.compile(pattern) if isinstance(pattern, basestring) else pattern
for chunk, offset in _chunk_iter():
matches = [match for match in pattern.finditer(chunk)]
if matches:
return (offset + matches[-1].span()[0], offset + matches[-1].span()[1])
return None
def memoizemethod_noargs(method):
"""Decorator to cache the result of a method (without arguments) using a
weak reference to its object
"""
cache = weakref.WeakKeyDictionary()
@wraps(method)
def new_method(self, *args, **kwargs):
if self not in cache:
cache[self] = method(self, *args, **kwargs)
return cache[self]
return new_method
_BINARYCHARS = set(map(chr, range(32))) - set(["\0", "\t", "\n", "\r"])
def isbinarytext(text):
"""Return True if the given text is considered binary, or false
otherwise, by looking for binary bytes at their chars
"""
assert isinstance(text, str), "text must be str, got '%s'" % type(text).__name__
return any(c in _BINARYCHARS for c in text)
def get_func_args(func, stripself=False):
"""Return the argument name list of a callable"""
if inspect.isfunction(func):
func_args, _, _, _ = inspect.getargspec(func)
elif inspect.isclass(func):
return get_func_args(func.__init__, True)
elif inspect.ismethod(func):
return get_func_args(func.__func__, True)
elif inspect.ismethoddescriptor(func):
return []
elif isinstance(func, partial):
return [x for x in get_func_args(func.func)[len(func.args):]
if not (func.keywords and x in func.keywords)]
elif hasattr(func, '__call__'):
if inspect.isroutine(func):
return []
elif getattr(func, '__name__', None) == '__call__':
return []
else:
return get_func_args(func.__call__, True)
else:
raise TypeError('%s is not callable' % type(func))
if stripself:
func_args.pop(0)
return func_args
def get_spec(func):
"""Returns (args, kwargs) tuple for a function
>>> import re
>>> get_spec(re.match)
(['pattern', 'string'], {'flags': 0})
>>> class Test(object):
... def __call__(self, val):
... pass
... def method(self, val, flags=0):
... pass
>>> get_spec(Test)
(['self', 'val'], {})
>>> get_spec(Test.method)
(['self', 'val'], {'flags': 0})
>>> get_spec(Test().method)
(['self', 'val'], {'flags': 0})
"""
if inspect.isfunction(func) or inspect.ismethod(func):
spec = inspect.getargspec(func)
elif hasattr(func, '__call__'):
spec = inspect.getargspec(func.__call__)
else:
raise TypeError('%s is not callable' % type(func))
defaults = spec.defaults or []
firstdefault = len(spec.args) - len(defaults)
args = spec.args[:firstdefault]
kwargs = dict(zip(spec.args[firstdefault:], defaults))
return args, kwargs
def equal_attributes(obj1, obj2, attributes):
"""Compare two objects attributes"""
# not attributes given return False by default
if not attributes:
return False
for attr in attributes:
# support callables like itemgetter
if callable(attr):
if not attr(obj1) == attr(obj2):
return False
else:
# check that objects has attribute
if not hasattr(obj1, attr):
return False
if not hasattr(obj2, attr):
return False
# compare object attributes
if not getattr(obj1, attr) == getattr(obj2, attr):
return False
# all attributes equal
return True
class WeakKeyCache(object):
def __init__(self, default_factory):
self.default_factory = default_factory
self._weakdict = weakref.WeakKeyDictionary()
def __getitem__(self, key):
if key not in self._weakdict:
self._weakdict[key] = self.default_factory(key)
return self._weakdict[key]
def stringify_dict(dct_or_tuples, encoding='utf-8', keys_only=True):
"""Return a (new) dict with the unicode keys (and values if, keys_only is
False) of the given dict converted to strings. `dct_or_tuples` can be a
dict or a list of tuples, like any dict constructor supports.
"""
d = {}
for k, v in six.iteritems(dict(dct_or_tuples)):
k = k.encode(encoding) if isinstance(k, unicode) else k
if not keys_only:
v = v.encode(encoding) if isinstance(v, unicode) else v
d[k] = v
return d
def is_writable(path):
"""Return True if the given path can be written (if it exists) or created
(if it doesn't exist)
"""
if os.path.exists(path):
return os.access(path, os.W_OK)
else:
return os.access(os.path.dirname(path), os.W_OK)
def setattr_default(obj, name, value):
"""Set attribute value, but only if it's not already set. Similar to
setdefault() for dicts.
"""
if not hasattr(obj, name):
setattr(obj, name, value)
def retry_on_eintr(function, *args, **kw):
"""Run a function and retry it while getting EINTR errors"""
while True:
try:
return function(*args, **kw)
except IOError as e:
if e.errno != errno.EINTR:
raise
| mit | -597,779,735,852,445,600 | 31.753623 | 108 | 0.614712 | false |
vanyh/handkeinzungen-app | places/serializers.py | 1 | 1167 | import json
from rest_framework import serializers
from .models import Place, AlternativeName
class GeoJsonSerializer(serializers.BaseSerializer):
def to_representation(self, obj):
if obj.lng:
geojson = {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [float(obj.lng), float(obj.lat)]
},
"properties": {
"name": obj.name,
"placeType": obj.place_type
}
}
return geojson
else:
return None
class AlternativeNameSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = AlternativeName
fields = "__all__"
class PlaceHelperSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Place
fields = "__all__"
class PlaceSerializer(serializers.HyperlinkedModelSerializer):
alternative_name = AlternativeNameSerializer(many=True)
part_of = PlaceHelperSerializer(many=False)
class Meta:
model = Place
fields = "__all__"
| mit | 3,882,192,932,309,661,700 | 24.369565 | 72 | 0.568123 | false |
Azulinho/ansible | lib/ansible/modules/cloud/amazon/ec2_ami.py | 26 | 27146 | #!/usr/bin/python
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'certified'}
DOCUMENTATION = '''
---
module: ec2_ami
version_added: "1.3"
short_description: create or destroy an image in ec2
description:
- Registers or deregisters ec2 images.
options:
instance_id:
description:
- Instance ID to create the AMI from.
name:
description:
- The name of the new AMI.
architecture:
version_added: "2.3"
description:
- The target architecture of the image to register
kernel_id:
version_added: "2.3"
description:
- The target kernel id of the image to register.
virtualization_type:
version_added: "2.3"
description:
- The virtualization type of the image to register.
root_device_name:
version_added: "2.3"
description:
- The root device name of the image to register.
wait:
description:
- Wait for the AMI to be in state 'available' before returning.
default: "no"
choices: [ "yes", "no" ]
wait_timeout:
description:
- How long before wait gives up, in seconds.
default: 900
state:
description:
- Register or deregister an AMI.
default: 'present'
choices: [ "absent", "present" ]
description:
description:
- Human-readable string describing the contents and purpose of the AMI.
no_reboot:
description:
- Flag indicating that the bundling process should not attempt to shutdown the instance before bundling. If this flag is True, the
responsibility of maintaining file system integrity is left to the owner of the instance.
default: no
choices: [ "yes", "no" ]
image_id:
description:
- Image ID to be deregistered.
device_mapping:
version_added: "2.0"
description:
- List of device hashes/dictionaries with custom configurations (same block-device-mapping parameters).
- >
Valid properties include: device_name, volume_type, size/volume_size (in GB), delete_on_termination (boolean), no_device (boolean),
snapshot_id, iops (for io1 volume_type), encrypted
delete_snapshot:
description:
- Delete snapshots when deregistering the AMI.
default: "no"
choices: [ "yes", "no" ]
tags:
description:
- A dictionary of tags to add to the new image; '{"key":"value"}' and '{"key":"value","key":"value"}'
version_added: "2.0"
purge_tags:
description: Whether to remove existing tags that aren't passed in the C(tags) parameter
version_added: "2.5"
default: "no"
launch_permissions:
description:
- Users and groups that should be able to launch the AMI. Expects dictionary with a key of user_ids and/or group_names. user_ids should
be a list of account ids. group_name should be a list of groups, "all" is the only acceptable value currently.
- You must pass all desired launch permissions if you wish to modify existing launch permissions (passing just groups will remove all users)
version_added: "2.0"
image_location:
description:
- The s3 location of an image to use for the AMI.
version_added: "2.5"
enhanced_networking:
description:
- A boolean representing whether enhanced networking with ENA is enabled or not.
version_added: "2.5"
billing_products:
description:
- A list of valid billing codes. To be used with valid accounts by aws marketplace vendors.
version_added: "2.5"
ramdisk_id:
description:
- The ID of the RAM disk.
version_added: "2.5"
sriov_net_support:
description:
- Set to simple to enable enhanced networking with the Intel 82599 Virtual Function interface for the AMI and any instances that you launch from the AMI.
version_added: "2.5"
author:
- "Evan Duffield (@scicoin-project) <[email protected]>"
- "Constantin Bugneac (@Constantin07) <[email protected]>"
- "Ross Williams (@gunzy83) <[email protected]>"
- "Willem van Ketwich (@wilvk) <[email protected]>"
extends_documentation_fragment:
- aws
- ec2
'''
# Thank you to iAcquire for sponsoring development of this module.
EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.
# Basic AMI Creation
- ec2_ami:
instance_id: i-xxxxxx
wait: yes
name: newtest
tags:
Name: newtest
Service: TestService
# Basic AMI Creation, without waiting
- ec2_ami:
instance_id: i-xxxxxx
wait: no
name: newtest
# AMI Registration from EBS Snapshot
- ec2_ami:
name: newtest
state: present
architecture: x86_64
virtualization_type: hvm
root_device_name: /dev/xvda
device_mapping:
- device_name: /dev/xvda
volume_size: 8
snapshot_id: snap-xxxxxxxx
delete_on_termination: true
volume_type: gp2
# AMI Creation, with a custom root-device size and another EBS attached
- ec2_ami:
instance_id: i-xxxxxx
name: newtest
device_mapping:
- device_name: /dev/sda1
size: XXX
delete_on_termination: true
volume_type: gp2
- device_name: /dev/sdb
size: YYY
delete_on_termination: false
volume_type: gp2
# AMI Creation, excluding a volume attached at /dev/sdb
- ec2_ami:
instance_id: i-xxxxxx
name: newtest
device_mapping:
- device_name: /dev/sda1
size: XXX
delete_on_termination: true
volume_type: gp2
- device_name: /dev/sdb
no_device: yes
# Deregister/Delete AMI (keep associated snapshots)
- ec2_ami:
image_id: "{{ instance.image_id }}"
delete_snapshot: False
state: absent
# Deregister AMI (delete associated snapshots too)
- ec2_ami:
image_id: "{{ instance.image_id }}"
delete_snapshot: True
state: absent
# Update AMI Launch Permissions, making it public
- ec2_ami:
image_id: "{{ instance.image_id }}"
state: present
launch_permissions:
group_names: ['all']
# Allow AMI to be launched by another account
- ec2_ami:
image_id: "{{ instance.image_id }}"
state: present
launch_permissions:
user_ids: ['123456789012']
'''
RETURN = '''
architecture:
description: architecture of image
returned: when AMI is created or already exists
type: string
sample: "x86_64"
block_device_mapping:
description: block device mapping associated with image
returned: when AMI is created or already exists
type: dict
sample: {
"/dev/sda1": {
"delete_on_termination": true,
"encrypted": false,
"size": 10,
"snapshot_id": "snap-1a03b80e7",
"volume_type": "standard"
}
}
creationDate:
description: creation date of image
returned: when AMI is created or already exists
type: string
sample: "2015-10-15T22:43:44.000Z"
description:
description: description of image
returned: when AMI is created or already exists
type: string
sample: "nat-server"
hypervisor:
description: type of hypervisor
returned: when AMI is created or already exists
type: string
sample: "xen"
image_id:
description: id of the image
returned: when AMI is created or already exists
type: string
sample: "ami-1234abcd"
is_public:
description: whether image is public
returned: when AMI is created or already exists
type: bool
sample: false
launch_permission:
description: permissions allowing other accounts to access the AMI
returned: when AMI is created or already exists
type: list
sample:
- group: "all"
location:
description: location of image
returned: when AMI is created or already exists
type: string
sample: "315210894379/nat-server"
name:
description: ami name of image
returned: when AMI is created or already exists
type: string
sample: "nat-server"
ownerId:
description: owner of image
returned: when AMI is created or already exists
type: string
sample: "435210894375"
platform:
description: platform of image
returned: when AMI is created or already exists
type: string
sample: null
root_device_name:
description: root device name of image
returned: when AMI is created or already exists
type: string
sample: "/dev/sda1"
root_device_type:
description: root device type of image
returned: when AMI is created or already exists
type: string
sample: "ebs"
state:
description: state of image
returned: when AMI is created or already exists
type: string
sample: "available"
tags:
description: a dictionary of tags assigned to image
returned: when AMI is created or already exists
type: dict
sample: {
"Env": "devel",
"Name": "nat-server"
}
virtualization_type:
description: image virtualization type
returned: when AMI is created or already exists
type: string
sample: "hvm"
snapshots_deleted:
description: a list of snapshot ids deleted after deregistering image
returned: after AMI is deregistered, if 'delete_snapshot' is set to 'yes'
type: list
sample: [
"snap-fbcccb8f",
"snap-cfe7cdb4"
]
'''
import time
from ansible.module_utils.ec2 import get_aws_connection_info, ec2_argument_spec, boto3_conn, camel_dict_to_snake_dict
from ansible.module_utils.ec2 import ansible_dict_to_boto3_tag_list, boto3_tag_list_to_ansible_dict, compare_aws_tags
from ansible.module_utils.aws.core import AnsibleAWSModule
try:
import botocore
except ImportError:
pass
def get_block_device_mapping(image):
bdm_dict = dict()
if image is not None and image.get('block_device_mappings') is not None:
bdm = image.get('block_device_mappings')
for device in bdm:
device_name = device.get('device_name')
if 'ebs' in device:
ebs = device.get("ebs")
bdm_dict_item = {
'size': ebs.get("volume_size"),
'snapshot_id': ebs.get("snapshot_id"),
'volume_type': ebs.get("volume_type"),
'encrypted': ebs.get("encrypted"),
'delete_on_termination': ebs.get("delete_on_termination")
}
elif 'virtual_name' in device:
bdm_dict_item = dict(virtual_name=device['virtual_name'])
bdm_dict[device_name] = bdm_dict_item
return bdm_dict
def get_ami_info(camel_image):
image = camel_dict_to_snake_dict(camel_image)
return dict(
image_id=image.get("image_id"),
state=image.get("state"),
architecture=image.get("architecture"),
block_device_mapping=get_block_device_mapping(image),
creationDate=image.get("creation_date"),
description=image.get("description"),
hypervisor=image.get("hypervisor"),
is_public=image.get("public"),
location=image.get("image_location"),
ownerId=image.get("owner_id"),
root_device_name=image.get("root_device_name"),
root_device_type=image.get("root_device_type"),
virtualization_type=image.get("virtualization_type"),
name=image.get("name"),
tags=boto3_tag_list_to_ansible_dict(image.get('tags')),
platform=image.get("platform"),
enhanced_networking=image.get("ena_support"),
image_owner_alias=image.get("image_owner_alias"),
image_type=image.get("image_type"),
kernel_id=image.get("kernel_id"),
product_codes=image.get("product_codes"),
ramdisk_id=image.get("ramdisk_id"),
sriov_net_support=image.get("sriov_net_support"),
state_reason=image.get("state_reason"),
launch_permissions=image.get('launch_permissions')
)
def create_image(module, connection):
instance_id = module.params.get('instance_id')
name = module.params.get('name')
wait = module.params.get('wait')
wait_timeout = module.params.get('wait_timeout')
description = module.params.get('description')
architecture = module.params.get('architecture')
kernel_id = module.params.get('kernel_id')
root_device_name = module.params.get('root_device_name')
virtualization_type = module.params.get('virtualization_type')
no_reboot = module.params.get('no_reboot')
device_mapping = module.params.get('device_mapping')
tags = module.params.get('tags')
launch_permissions = module.params.get('launch_permissions')
image_location = module.params.get('image_location')
enhanced_networking = module.params.get('enhanced_networking')
billing_products = module.params.get('billing_products')
ramdisk_id = module.params.get('ramdisk_id')
sriov_net_support = module.params.get('sriov_net_support')
try:
params = {
'Name': name,
'Description': description
}
images = connection.describe_images(
Filters=[
{
'Name': 'name',
'Values': [name]
}
]
).get('Images')
block_device_mapping = None
if device_mapping:
block_device_mapping = []
for device in device_mapping:
device['Ebs'] = {}
if 'device_name' not in device:
module.fail_json(msg="Error - Device name must be set for volume.")
device = rename_item_if_exists(device, 'device_name', 'DeviceName')
device = rename_item_if_exists(device, 'virtual_name', 'VirtualName')
device = rename_item_if_exists(device, 'no_device', 'NoDevice')
device = rename_item_if_exists(device, 'volume_type', 'VolumeType', 'Ebs')
device = rename_item_if_exists(device, 'snapshot_id', 'SnapshotId', 'Ebs')
device = rename_item_if_exists(device, 'delete_on_termination', 'DeleteOnTermination', 'Ebs')
device = rename_item_if_exists(device, 'size', 'VolumeSize', 'Ebs')
device = rename_item_if_exists(device, 'volume_size', 'VolumeSize', 'Ebs')
device = rename_item_if_exists(device, 'iops', 'Iops', 'Ebs')
device = rename_item_if_exists(device, 'encrypted', 'Encrypted', 'Ebs')
block_device_mapping.append(device)
if block_device_mapping:
params['BlockDeviceMappings'] = block_device_mapping
if instance_id:
params['InstanceId'] = instance_id
params['NoReboot'] = no_reboot
image_id = connection.create_image(**params).get('ImageId')
else:
if architecture:
params['Architecture'] = architecture
if virtualization_type:
params['VirtualizationType'] = virtualization_type
if image_location:
params['ImageLocation'] = image_location
if enhanced_networking:
params['EnaSupport'] = enhanced_networking
if billing_products:
params['BillingProducts'] = billing_products
if ramdisk_id:
params['RamdiskId'] = ramdisk_id
if sriov_net_support:
params['SriovNetSupport'] = sriov_net_support
if kernel_id:
params['KernelId'] = kernel_id
if root_device_name:
params['RootDeviceName'] = root_device_name
image_id = connection.register_image(**params).get('ImageId')
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
module.fail_json_aws(e, msg="Error registering image")
if wait:
waiter = connection.get_waiter('image_available')
delay = wait_timeout // 30
max_attempts = 30
waiter.wait(ImageIds=[image_id], WaiterConfig=dict(Delay=delay, MaxAttempts=max_attempts))
if tags:
try:
connection.create_tags(Resources=[image_id], Tags=ansible_dict_to_boto3_tag_list(tags))
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
module.fail_json_aws(e, msg="Error tagging image")
if launch_permissions:
try:
params = dict(Attribute='LaunchPermission', ImageId=image_id, LaunchPermission=dict(Add=list()))
for group_name in launch_permissions.get('group_names', []):
params['LaunchPermission']['Add'].append(dict(Group=group_name))
for user_id in launch_permissions.get('user_ids', []):
params['LaunchPermission']['Add'].append(dict(UserId=str(user_id)))
if params['LaunchPermission']['Add']:
connection.modify_image_attribute(**params)
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
module.fail_json_aws(e, msg="Error setting launch permissions for image %s" % image_id)
module.exit_json(msg="AMI creation operation complete.", changed=True,
**get_ami_info(get_image_by_id(module, connection, image_id)))
def deregister_image(module, connection):
image_id = module.params.get('image_id')
delete_snapshot = module.params.get('delete_snapshot')
wait = module.params.get('wait')
wait_timeout = module.params.get('wait_timeout')
image = get_image_by_id(module, connection, image_id)
if image is None:
module.exit_json(changed=False)
# Get all associated snapshot ids before deregistering image otherwise this information becomes unavailable.
snapshots = []
if 'BlockDeviceMappings' in image:
for mapping in image.get('BlockDeviceMappings'):
snapshot_id = mapping.get('SnapshotId')
if snapshot_id is not None:
snapshots.append(snapshot_id)
# When trying to re-deregister an already deregistered image it doesn't raise an exception, it just returns an object without image attributes.
if 'ImageId' in image:
try:
connection.deregister_image(ImageId=image_id)
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
module.fail_json_aws(e, msg="Error deregistering image")
else:
module.exit_json(msg="Image %s has already been deregistered." % image_id, changed=False)
image = get_image_by_id(module, connection, image_id)
wait_timeout = time.time() + wait_timeout
while wait and wait_timeout > time.time() and image is not None:
image = get_image_by_id(module, connection, image_id)
time.sleep(3)
if wait and wait_timeout <= time.time():
module.fail_json(msg="Timed out waiting for image to be deregistered.")
exit_params = {'msg': "AMI deregister operation complete.", 'changed': True}
if delete_snapshot:
try:
for snapshot_id in snapshots:
connection.delete_snapshot(SnapshotId=snapshot_id)
except botocore.exceptions.ClientError as e:
# Don't error out if root volume snapshot was already deregistered as part of deregister_image
if e.response['Error']['Code'] == 'InvalidSnapshot.NotFound':
pass
exit_params['snapshots_deleted'] = snapshots
module.exit_json(**exit_params)
def update_image(module, connection, image_id):
launch_permissions = module.params.get('launch_permissions')
image = get_image_by_id(module, connection, image_id)
if image is None:
module.fail_json(msg="Image %s does not exist" % image_id, changed=False)
changed = False
if launch_permissions is not None:
current_permissions = image['LaunchPermissions']
current_users = set(permission['UserId'] for permission in current_permissions if 'UserId' in permission)
desired_users = set(str(user_id) for user_id in launch_permissions.get('user_ids', []))
current_groups = set(permission['Group'] for permission in current_permissions if 'Group' in permission)
desired_groups = set(launch_permissions.get('group_names', []))
to_add_users = desired_users - current_users
to_remove_users = current_users - desired_users
to_add_groups = desired_groups - current_groups
to_remove_groups = current_groups - desired_groups
to_add = [dict(Group=group) for group in to_add_groups] + [dict(UserId=user_id) for user_id in to_add_users]
to_remove = [dict(Group=group) for group in to_remove_groups] + [dict(UserId=user_id) for user_id in to_remove_users]
if to_add or to_remove:
try:
connection.modify_image_attribute(ImageId=image_id, Attribute='launchPermission',
LaunchPermission=dict(Add=to_add, Remove=to_remove))
changed = True
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
module.fail_json_aws(e, msg="Error updating launch permissions")
desired_tags = module.params.get('tags')
if desired_tags is not None:
current_tags = boto3_tag_list_to_ansible_dict(image.get('Tags'))
tags_to_add, tags_to_remove = compare_aws_tags(current_tags, desired_tags, purge_tags=module.params.get('purge_tags'))
if tags_to_remove:
try:
connection.delete_tags(Resources=[image_id], Tags=[dict(Key=tagkey) for tagkey in tags_to_remove])
changed = True
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
module.fail_json_aws(e, msg="Error updating tags")
if tags_to_add:
try:
connection.create_tags(Resources=[image_id], Tags=ansible_dict_to_boto3_tag_list(tags_to_add))
changed = True
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
module.fail_json_aws(e, msg="Error updating tags")
description = module.params.get('description')
if description and description != image['Description']:
try:
connection.modify_image_attribute(Attribute='Description ', ImageId=image_id, Description=dict(Value=description))
changed = True
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
module.fail_json_aws(e, msg="Error setting description for image %s" % image_id)
if changed:
module.exit_json(msg="AMI updated.", changed=True,
**get_ami_info(get_image_by_id(module, connection, image_id)))
else:
module.exit_json(msg="AMI not updated.", changed=False,
**get_ami_info(get_image_by_id(module, connection, image_id)))
def get_image_by_id(module, connection, image_id):
try:
try:
images_response = connection.describe_images(ImageIds=[image_id])
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
module.fail_json_aws(e, msg="Error retrieving image %s" % image_id)
images = images_response.get('Images')
no_images = len(images)
if no_images == 0:
return None
if no_images == 1:
result = images[0]
try:
result['LaunchPermissions'] = connection.describe_image_attribute(Attribute='launchPermission', ImageId=image_id)['LaunchPermissions']
result['ProductCodes'] = connection.describe_image_attribute(Attribute='productCodes', ImageId=image_id)['ProductCodes']
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] != 'InvalidAMIID.Unavailable':
module.fail_json_aws(e, msg="Error retrieving image attributes" % image_id)
except botocore.exceptions.BotoCoreError as e:
module.fail_json_aws(e, msg="Error retrieving image attributes" % image_id)
return result
module.fail_json(msg="Invalid number of instances (%s) found for image_id: %s." % (str(len(images)), image_id))
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
module.fail_json_aws(e, msg="Error retrieving image by image_id")
def rename_item_if_exists(dict_object, attribute, new_attribute, child_node=None):
new_item = dict_object.get(attribute)
if new_item is not None:
if child_node is None:
dict_object[new_attribute] = dict_object.get(attribute)
else:
dict_object[child_node][new_attribute] = dict_object.get(attribute)
dict_object.pop(attribute)
return dict_object
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(dict(
instance_id=dict(),
image_id=dict(),
architecture=dict(default='x86_64'),
kernel_id=dict(),
virtualization_type=dict(default='hvm'),
root_device_name=dict(),
delete_snapshot=dict(default=False, type='bool'),
name=dict(),
wait=dict(type='bool', default=False),
wait_timeout=dict(default=900, type='int'),
description=dict(default=''),
no_reboot=dict(default=False, type='bool'),
state=dict(default='present'),
device_mapping=dict(type='list'),
tags=dict(type='dict'),
launch_permissions=dict(type='dict'),
image_location=dict(),
enhanced_networking=dict(type='bool'),
billing_products=dict(type='list'),
ramdisk_id=dict(),
sriov_net_support=dict(),
purge_tags=dict(type='bool', default=False)
))
module = AnsibleAWSModule(
argument_spec=argument_spec,
required_if=[
['state', 'absent', ['image_id']],
['state', 'present', ['name']],
]
)
try:
region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)
connection = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_kwargs)
except botocore.exceptions.NoRegionError:
module.fail_json(msg=("Region must be specified as a parameter in AWS_DEFAULT_REGION environment variable or in boto configuration file."))
if module.params.get('state') == 'absent':
deregister_image(module, connection)
elif module.params.get('state') == 'present':
if module.params.get('image_id'):
update_image(module, connection, module.params.get('image_id'))
if not module.params.get('instance_id') and not module.params.get('device_mapping'):
module.fail_json(msg="The parameters instance_id or device_mapping (register from EBS snapshot) are required for a new image.")
create_image(module, connection)
if __name__ == '__main__':
main()
| gpl-3.0 | 2,086,553,310,748,921,000 | 37.724679 | 159 | 0.639063 | false |
mathemage/h2o-3 | h2o-py/tests/testdir_munging/binop/pyunit_intdiv.py | 6 | 1252 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import h2o
from h2o.exceptions import H2OTypeError, H2OValueError
from tests import pyunit_utils
def test_intdiv():
"""Test H2OFrame.__intdiv__()."""
iris = h2o.import_file(path=pyunit_utils.locate("smalldata/iris/iris_wheader.csv"))
iris = iris[:, 0:4]
rows, cols = iris.shape
# frame / scalar
res = iris // 5
assert res.shape == (rows, cols)
res = 5 // iris[:, 0:2]
assert res.shape == (rows, 2)
# frame / col
res = iris // iris[0]
assert res.shape == (rows, cols)
res = iris[2] // iris
assert res.shape == (rows, 1)
# col / col
res = iris[0] // iris[1]
res.show()
res = iris[1] // iris[2] // iris[1]
res.show()
# col / scalar
res = iris[0] // 5
res.show()
try:
iris[0] // [1, 3]
assert False
except H2OTypeError:
pass
# frame / frame
res = iris[:, 0:2] // iris[:, 0:2]
assert res.shape == (150, 2)
try:
iris[:, 0:3] // iris[:, 0:2]
assert False, "expected error. frames are different dimensions."
except H2OValueError:
pass
if __name__ == "__main__":
pyunit_utils.standalone_test(test_intdiv)
else:
test_intdiv()
| apache-2.0 | 8,387,729,442,365,387,000 | 19.52459 | 87 | 0.548722 | false |
jonhadfield/ansible-modules-core | cloud/azure/azure_rm_virtualnetwork.py | 25 | 13788 | #!/usr/bin/python
#
# Copyright (c) 2016 Matt Davis, <[email protected]>
# Chris Houseknecht, <[email protected]>
#
# 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/>.
#
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'committer',
'version': '1.0'}
DOCUMENTATION = '''
---
module: azure_rm_virtualnetwork
version_added: "2.1"
short_description: Manage Azure virtual networks.
description:
- Create, update or delete a virtual networks. Allows setting and updating the available IPv4 address ranges
and setting custom DNS servers. Use the azure_rm_subnet module to associate subnets with a virtual network.
options:
resource_group:
description:
- name of resource group.
required: true
address_prefixes_cidr:
description:
- List of IPv4 address ranges where each is formatted using CIDR notation. Required when creating
a new virtual network or using purge_address_prefixes.
aliases:
- address_prefixes
default: null
required: false
dns_servers:
description:
- Custom list of DNS servers. Maximum length of two. The first server in the list will be treated
as the Primary server. This is an explicit list. Existing DNS servers will be replaced with the
specified list. Use the purge_dns_servers option to remove all custom DNS servers and revert to
default Azure servers.
default: null
required: false
location:
description:
- Valid azure location. Defaults to location of the resource group.
default: resource_group location
required: false
name:
description:
- name of the virtual network.
required: true
purge_address_prefixes:
description:
- Use with state present to remove any existing address_prefixes.
default: false
purge_dns_servers:
description:
- Use with state present to remove existing DNS servers, reverting to default Azure servers. Mutually
exclusive with dns_servers.
default: false
required: false
state:
description:
- Assert the state of the virtual network. Use 'present' to create or update and
'absent' to delete.
default: present
choices:
- absent
- present
required: false
extends_documentation_fragment:
- azure
- azure_tags
author:
- "Chris Houseknecht (@chouseknecht)"
- "Matt Davis (@nitzmahone)"
'''
EXAMPLES = '''
- name: Create a virtual network
azure_rm_virtualnetwork:
name: foobar
resource_group: Testing
address_prefixes_cidr:
- "10.1.0.0/16"
- "172.100.0.0/16"
dns_servers:
- "127.0.0.1"
- "127.0.0.2"
tags:
testing: testing
delete: on-exit
- name: Delete a virtual network
azure_rm_virtualnetwork:
name: foobar
resource_group: Testing
state: absent
'''
RETURN = '''
state:
description: Current state of the virtual network.
returned: always
type: dict
sample: {
"address_prefixes": [
"10.1.0.0/16",
"172.100.0.0/16"
],
"dns_servers": [
"127.0.0.1",
"127.0.0.3"
],
"etag": 'W/"0712e87c-f02f-4bb3-8b9e-2da0390a3886"',
"id": "/subscriptions/XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX/resourceGroups/Testing/providers/Microsoft.Network/virtualNetworks/my_test_network",
"location": "eastus",
"name": "my_test_network",
"provisioning_state": "Succeeded",
"tags": null,
"type": "Microsoft.Network/virtualNetworks"
}
'''
from ansible.module_utils.basic import *
from ansible.module_utils.azure_rm_common import *
try:
from msrestazure.azure_exceptions import CloudError
from azure.mgmt.network.models import VirtualNetwork, AddressSpace, DhcpOptions
except ImportError:
# This is handled in azure_rm_common
pass
def virtual_network_to_dict(vnet):
'''
Convert a virtual network object to a dict.
:param vnet: VirtualNet object
:return: dict
'''
results = dict(
id=vnet.id,
name=vnet.name,
location=vnet.location,
type=vnet.type,
tags=vnet.tags,
provisioning_state=vnet.provisioning_state,
etag=vnet.etag
)
if vnet.dhcp_options and len(vnet.dhcp_options.dns_servers) > 0:
results['dns_servers'] = []
for server in vnet.dhcp_options.dns_servers:
results['dns_servers'].append(server)
if vnet.address_space and len(vnet.address_space.address_prefixes) > 0:
results['address_prefixes'] = []
for space in vnet.address_space.address_prefixes:
results['address_prefixes'].append(space)
return results
class AzureRMVirtualNetwork(AzureRMModuleBase):
def __init__(self):
self.module_arg_spec = dict(
resource_group=dict(type='str', required=True),
name=dict(type='str', required=True),
state=dict(type='str', default='present', choices=['present', 'absent']),
location=dict(type='str'),
address_prefixes_cidr=dict(type='list', aliases=['address_prefixes']),
dns_servers=dict(type='list',),
purge_address_prefixes=dict(type='bool', default=False, aliases=['purge']),
purge_dns_servers=dict(type='bool', default=False),
)
mutually_exclusive = [
('dns_servers', 'purge_dns_servers')
]
required_if = [
('purge_address_prefixes', True, ['address_prefixes_cidr'])
]
self.resource_group = None
self.name = None
self.state = None
self.location = None
self.address_prefixes_cidr = None
self.purge_address_prefixes = None
self.dns_servers = None
self.purge_dns_servers = None
self.results=dict(
changed=False,
state=dict()
)
super(AzureRMVirtualNetwork, self).__init__(self.module_arg_spec,
mutually_exclusive=mutually_exclusive,
required_if=required_if,
supports_check_mode=True)
def exec_module(self, **kwargs):
for key in self.module_arg_spec.keys() + ['tags']:
setattr(self, key, kwargs[key])
self.results['check_mode'] = self.check_mode
resource_group = self.get_resource_group(self.resource_group)
if not self.location:
# Set default location
self.location = resource_group.location
if self.state == 'present' and self.purge_address_prefixes:
for prefix in self.address_prefixes_cidr:
if not CIDR_PATTERN.match(prefix):
self.fail("Parameter error: invalid address prefix value {0}".format(prefix))
if self.dns_servers and len(self.dns_servers) > 2:
self.fail("Parameter error: You can provide a maximum of 2 DNS servers.")
changed = False
results = dict()
try:
self.log('Fetching vnet {0}'.format(self.name))
vnet = self.network_client.virtual_networks.get(self.resource_group, self.name)
results = virtual_network_to_dict(vnet)
self.log('Vnet exists {0}'.format(self.name))
self.log(results, pretty_print=True)
self.check_provisioning_state(vnet, self.state)
if self.state == 'present':
if self.address_prefixes_cidr:
existing_address_prefix_set = set(vnet.address_space.address_prefixes)
requested_address_prefix_set = set(self.address_prefixes_cidr)
missing_prefixes = requested_address_prefix_set - existing_address_prefix_set
extra_prefixes = existing_address_prefix_set - requested_address_prefix_set
if len(missing_prefixes) > 0:
self.log('CHANGED: there are missing address_prefixes')
changed = True
if not self.purge_address_prefixes:
# add the missing prefixes
for prefix in missing_prefixes:
results['address_prefixes'].append(prefix)
if len(extra_prefixes) > 0 and self.purge_address_prefixes:
self.log('CHANGED: there are address_prefixes to purge')
changed = True
# replace existing address prefixes with requested set
results['address_prefixes'] = self.address_prefixes_cidr
update_tags, results['tags'] = self.update_tags(results['tags'])
if update_tags:
changed = True
if self.dns_servers:
existing_dns_set = set(vnet.dhcp_options.dns_servers)
requested_dns_set = set(self.dns_servers)
if existing_dns_set != requested_dns_set:
self.log('CHANGED: replacing DNS servers')
changed = True
results['dns_servers'] = self.dns_servers
if self.purge_dns_servers and vnet.dhcp_options and len(vnet.dhcp_options.dns_servers) > 0:
self.log('CHANGED: purging existing DNS servers')
changed = True
results['dns_servers'] = []
elif self.state == 'absent':
self.log("CHANGED: vnet exists but requested state is 'absent'")
changed = True
except CloudError:
self.log('Vnet {0} does not exist'.format(self.name))
if self.state == 'present':
self.log("CHANGED: vnet {0} does not exist but requested state is 'present'".format(self.name))
changed = True
self.results['changed'] = changed
self.results['state'] = results
if self.check_mode:
return self.results
if changed:
if self.state == 'present':
if not results:
# create a new virtual network
self.log("Create virtual network {0}".format(self.name))
if not self.address_prefixes_cidr:
self.fail('Parameter error: address_prefixes_cidr required when creating a virtual network')
vnet = VirtualNetwork(
location=self.location,
address_space=AddressSpace(
address_prefixes=self.address_prefixes_cidr
)
)
if self.dns_servers:
vnet.dhcp_options = DhcpOptions(
dns_servers=self.dns_servers
)
if self.tags:
vnet.tags = self.tags
self.results['state'] = self.create_or_update_vnet(vnet)
else:
# update existing virtual network
self.log("Update virtual network {0}".format(self.name))
vnet = VirtualNetwork(
location=results['location'],
address_space=AddressSpace(
address_prefixes=results['address_prefixes']
),
tags=results['tags']
)
if results.get('dns_servers'):
vnet.dhcp_options = DhcpOptions(
dns_servers=results['dns_servers']
)
self.results['state'] = self.create_or_update_vnet(vnet)
elif self.state == 'absent':
self.delete_virtual_network()
self.results['state']['status'] = 'Deleted'
return self.results
def create_or_update_vnet(self, vnet):
try:
poller = self.network_client.virtual_networks.create_or_update(self.resource_group, self.name, vnet)
new_vnet = self.get_poller_result(poller)
except Exception as exc:
self.fail("Error creating or updating virtual network {0} - {1}".format(self.name, str(exc)))
return virtual_network_to_dict(new_vnet)
def delete_virtual_network(self):
try:
poller = self.network_client.virtual_networks.delete(self.resource_group, self.name)
result = self.get_poller_result(poller)
except Exception as exc:
self.fail("Error deleting virtual network {0} - {1}".format(self.name, str(exc)))
return result
def main():
AzureRMVirtualNetwork()
if __name__ == '__main__':
main()
| gpl-3.0 | -3,761,450,506,219,953,700 | 36.467391 | 148 | 0.566435 | false |
maddox/home-assistant | homeassistant/components/sensor/arduino.py | 10 | 2227 | """
homeassistant.components.sensor.arduino
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for getting information from Arduino pins. Only analog pins are
supported.
Configuration:
To use the arduino sensor you will need to add something like the following
to your configuration.yaml file.
sensor:
platform: arduino
pins:
7:
name: Door switch
type: analog
0:
name: Brightness
type: analog
Variables:
pins
*Required
An array specifying the digital pins to use on the Arduino board.
These are the variables for the pins array:
name
*Required
The name for the pin that will be used in the frontend.
type
*Required
The type of the pin: 'analog'.
"""
import logging
import homeassistant.components.arduino as arduino
from homeassistant.helpers.entity import Entity
from homeassistant.const import DEVICE_DEFAULT_NAME
DEPENDENCIES = ['arduino']
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Arduino platform. """
# Verify that the Arduino board is present
if arduino.BOARD is None:
_LOGGER.error('A connection has not been made to the Arduino board.')
return False
sensors = []
pins = config.get('pins')
for pinnum, pin in pins.items():
if pin.get('name'):
sensors.append(ArduinoSensor(pin.get('name'),
pinnum,
'analog'))
add_devices(sensors)
class ArduinoSensor(Entity):
""" Represents an Arduino Sensor. """
def __init__(self, name, pin, pin_type):
self._pin = pin
self._name = name or DEVICE_DEFAULT_NAME
self.pin_type = pin_type
self.direction = 'in'
self._value = None
arduino.BOARD.set_mode(self._pin, self.direction, self.pin_type)
@property
def state(self):
""" Returns the state of the sensor. """
return self._value
@property
def name(self):
""" Get the name of the sensor. """
return self._name
def update(self):
""" Get the latest value from the pin. """
self._value = arduino.BOARD.get_analog_inputs()[self._pin][1]
| mit | -2,095,269,760,577,800,000 | 23.744444 | 77 | 0.62775 | false |
archesproject/arches | arches/app/models/migrations/5407_remove_tileserver_configs.py | 1 | 1529 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('models', '5407_remove_tileserver'),
]
operations = [
migrations.RunSQL(
"""
update nodes
set config = config - 'cacheTiles'
where datatype = 'geojson-feature-collection';
update nodes
set config = config - 'autoManageCache'
where datatype = 'geojson-feature-collection';
update d_data_types
set defaultconfig = defaultconfig - 'cacheTiles'
where datatype = 'geojson-feature-collection';
update d_data_types
set defaultconfig = defaultconfig - 'autoManageCache'
where datatype = 'geojson-feature-collection';
""",
"""
update d_data_types
set defaultconfig = jsonb_set(defaultconfig, '{cacheTiles}', 'false')
where datatype = 'geojson-feature-collection';
update nodes
set config = jsonb_set(config, '{cacheTiles}', 'false')
where datatype = 'geojson-feature-collection';
update d_data_types
set defaultconfig = jsonb_set(defaultconfig, '{autoManageCache}', 'false')
where datatype = 'geojson-feature-collection';
update nodes
set config = jsonb_set(config, '{autoManageCache}', 'false')
where datatype = 'geojson-feature-collection';
"""
),
]
| agpl-3.0 | 5,050,901,485,235,383,000 | 31.531915 | 86 | 0.564421 | false |
ryanlelek/SMORESGaitRecorder | proto/publish_pb2.py | 1 | 2603 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: publish.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
DESCRIPTOR = _descriptor.FileDescriptor(
name='publish.proto',
package='gazebo.msgs',
serialized_pb='\n\rpublish.proto\x12\x0bgazebo.msgs\"F\n\x07Publish\x12\r\n\x05topic\x18\x01 \x02(\t\x12\x10\n\x08msg_type\x18\x02 \x02(\t\x12\x0c\n\x04host\x18\x03 \x02(\t\x12\x0c\n\x04port\x18\x04 \x02(\r')
_PUBLISH = _descriptor.Descriptor(
name='Publish',
full_name='gazebo.msgs.Publish',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='topic', full_name='gazebo.msgs.Publish.topic', index=0,
number=1, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='msg_type', full_name='gazebo.msgs.Publish.msg_type', index=1,
number=2, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='host', full_name='gazebo.msgs.Publish.host', index=2,
number=3, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='port', full_name='gazebo.msgs.Publish.port', index=3,
number=4, type=13, cpp_type=3, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=30,
serialized_end=100,
)
DESCRIPTOR.message_types_by_name['Publish'] = _PUBLISH
class Publish(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageType
DESCRIPTOR = _PUBLISH
# @@protoc_insertion_point(class_scope:gazebo.msgs.Publish)
# @@protoc_insertion_point(module_scope)
| gpl-3.0 | 7,932,751,850,522,120,000 | 32.371795 | 210 | 0.696888 | false |
satdav/mozillians | vendor-local/lib/python/djcelery/schedulers.py | 10 | 7860 | from __future__ import absolute_import
import logging
from warnings import warn
from anyjson import deserialize, serialize
from celery import schedules
from celery.beat import Scheduler, ScheduleEntry
from celery.utils.encoding import safe_str, safe_repr
from kombu.utils.finalize import Finalize
from django.db import transaction
from django.core.exceptions import ObjectDoesNotExist
from .models import (PeriodicTask, PeriodicTasks,
CrontabSchedule, IntervalSchedule)
from .utils import DATABASE_ERRORS, now
class ModelEntry(ScheduleEntry):
model_schedules = ((schedules.crontab, CrontabSchedule, "crontab"),
(schedules.schedule, IntervalSchedule, "interval"))
save_fields = ["last_run_at", "total_run_count", "no_changes"]
def __init__(self, model):
self.name = model.name
self.task = model.task
self.schedule = model.schedule
try:
self.args = deserialize(model.args or u"[]")
self.kwargs = deserialize(model.kwargs or u"{}")
except ValueError:
# disable because of error deserializing args/kwargs
model.no_changes = True
model.enabled = False
model.save()
raise
self.options = {"queue": model.queue,
"exchange": model.exchange,
"routing_key": model.routing_key,
"expires": model.expires}
self.total_run_count = model.total_run_count
self.model = model
if not model.last_run_at:
model.last_run_at = self._default_now()
self.last_run_at = model.last_run_at
def is_due(self):
if not self.model.enabled:
return False, 5.0 # 5 second delay for re-enable.
return self.schedule.is_due(self.last_run_at)
def _default_now(self):
return now()
def next(self):
self.model.last_run_at = now()
self.model.total_run_count += 1
self.model.no_changes = True
return self.__class__(self.model)
__next__ = next # for 2to3
def save(self):
# Object may not be synchronized, so only
# change the fields we care about.
obj = self.model._default_manager.get(pk=self.model.pk)
for field in self.save_fields:
setattr(obj, field, getattr(self.model, field))
obj.save()
@classmethod
def to_model_schedule(cls, schedule):
for schedule_type, model_type, model_field in cls.model_schedules:
schedule = schedules.maybe_schedule(schedule)
if isinstance(schedule, schedule_type):
model_schedule = model_type.from_schedule(schedule)
model_schedule.save()
return model_schedule, model_field
raise ValueError("Can't convert schedule type %r to model" % schedule)
@classmethod
def from_entry(cls, name, skip_fields=("relative", "options"), **entry):
options = entry.get("options") or {}
fields = dict(entry)
for skip_field in skip_fields:
fields.pop(skip_field, None)
schedule = fields.pop("schedule")
model_schedule, model_field = cls.to_model_schedule(schedule)
fields[model_field] = model_schedule
fields["args"] = serialize(fields.get("args") or [])
fields["kwargs"] = serialize(fields.get("kwargs") or {})
fields["queue"] = options.get("queue")
fields["exchange"] = options.get("exchange")
fields["routing_key"] = options.get("routing_key")
return cls(PeriodicTask._default_manager.update_or_create(name=name,
defaults=fields))
def __repr__(self):
return "<ModelEntry: %s %s(*%s, **%s) {%s}>" % (safe_str(self.name),
self.task,
safe_repr(self.args),
safe_repr(self.kwargs),
self.schedule)
class DatabaseScheduler(Scheduler):
Entry = ModelEntry
Model = PeriodicTask
Changes = PeriodicTasks
_schedule = None
_last_timestamp = None
def __init__(self, *args, **kwargs):
self._dirty = set()
self._finalize = Finalize(self, self.sync, exitpriority=5)
Scheduler.__init__(self, *args, **kwargs)
self.max_interval = 5
def setup_schedule(self):
self.install_default_entries(self.schedule)
self.update_from_dict(self.app.conf.CELERYBEAT_SCHEDULE)
def all_as_schedule(self):
self.logger.debug("DatabaseScheduler: Fetching database schedule")
s = {}
for model in self.Model.objects.enabled():
try:
s[model.name] = self.Entry(model)
except ValueError:
pass
return s
def schedule_changed(self):
if self._last_timestamp is not None:
try:
# If MySQL is running with transaction isolation level
# REPEATABLE-READ (default), then we won't see changes done by
# other transactions until the current transaction is
# committed (Issue #41).
try:
transaction.commit()
except transaction.TransactionManagementError:
pass # not in transaction management.
ts = self.Changes.last_change()
if not ts or ts < self._last_timestamp:
return False
except DATABASE_ERRORS, exc:
warn(RuntimeWarning("Database gave error: %r" % (exc, )))
return False
self._last_timestamp = now()
return True
def reserve(self, entry):
new_entry = Scheduler.reserve(self, entry)
# Need to store entry by name, because the entry may change
# in the mean time.
self._dirty.add(new_entry.name)
return new_entry
@transaction.commit_manually
def sync(self):
self.logger.debug("Writing dirty entries...")
try:
while self._dirty:
try:
name = self._dirty.pop()
self.schedule[name].save()
except (KeyError, ObjectDoesNotExist):
pass
except:
transaction.rollback()
raise
else:
transaction.commit()
def update_from_dict(self, dict_):
s = {}
for name, entry in dict_.items():
try:
s[name] = self.Entry.from_entry(name, **entry)
except Exception, exc:
self.logger.error(
"Couldn't add entry %r to database schedule: %r. "
"Contents: %r" % (name, exc, entry))
self.schedule.update(s)
def install_default_entries(self, data):
entries = {}
if self.app.conf.CELERY_TASK_RESULT_EXPIRES:
entries.setdefault("celery.backend_cleanup", {
"task": "celery.backend_cleanup",
"schedule": schedules.crontab("0", "4", "*", nowfun=now),
"options": {"expires": 12 * 3600}})
self.update_from_dict(entries)
def get_schedule(self):
if self.schedule_changed():
self.sync()
self.logger.debug("DatabaseScheduler: Schedule changed.")
self._schedule = self.all_as_schedule()
if self.logger.isEnabledFor(logging.DEBUG):
self.logger.debug(
"Current schedule:\n" +
"\n".join(repr(entry)
for entry in self._schedule.values()))
return self._schedule
| bsd-3-clause | -2,644,339,543,803,860,000 | 36.428571 | 78 | 0.554707 | false |
js850/PyGMIN | scripts/compute_cv.py | 1 | 3067 | """
a script to calculate Cv from the Harmonic Superposition Approximation
"""
import argparse
import numpy as np
from pygmin.thermodynamics import minima_to_cv
from pygmin.storage import Database
from pygmin.utils.optim_compatibility import read_min_data
import matplotlib as mpl
mpl.use("Agg") # so we can use it without an X server
import matplotlib.pyplot as plt
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="compute the heat capacity from a database of minima using the harmonic"
"superposition approximation. The output will be written to Cv and Cv.pdf unless"
"specified differently")
# parser.add_argument("--db", type=str, nargs=1, help="database filename",
# default="otp.db")
parser.add_argument("fname", type=str, help="Database file name")
parser.add_argument("-k", type=int, help="Number of vibrational degrees freedom. "
"If this is not specified the heat capacity will be off by an additive constant", default=0)
parser.add_argument("-o", metavar="output", type=str,
help="output file name. The heat capacity will be written to output and output.pdf", default="Cv")
parser.add_argument("--Tmin", type=float, help="Minimum temperature for the calculation.", default=0.02)
parser.add_argument("--Tmax", type=float, help="Minimum temperature for the calculation.", default=1.0)
parser.add_argument("--Tcount", type=int, help="Number of temperature points for the calculation.", default=300)
parser.add_argument("--OPTIM", action="store_true", help="read data from a min.data file instead."
"fname should be the filename of the min.data file")
args = parser.parse_args()
print args.fname
print args
k = args.k
# get the list of minima
if args.OPTIM:
# fname is a min.data file
minima = read_min_data(args.fname)
else:
dbfname = args.fname
db = Database(dbfname, createdb=False)
minima = [m for m in db.minima() if m.fvib is not None and m.pgorder is not None]
if len(minima) == 0:
print "There are not minima with the necessary thermodynamic information in the database. Have you computed the normal mode"\
" frequencies and point group order for all the minima? See pygmin.thermodynamics "\
" for more information"
exit(1)
print "computing heat capacity from", len(minima), "minima"
Tmin = args.Tmin
Tmax = args.Tmax
nT = args.Tcount
dT = (Tmax-Tmin) / nT
T = np.array([Tmin + dT*i for i in range(nT)])
Z, U, U2, Cv = minima_to_cv(minima, T, k)
with open(args.o, "w") as fout:
fout.write("#T Cv <E> <E**2>\n")
for vals in zip(T, Cv, U, U2):
fout.write("%g %g %g %g\n" % vals)
plt.plot(T, Cv, '-')
plt.xlabel("T")
plt.ylabel("Cv")
plt.savefig(args.o + ".pdf")
| gpl-3.0 | 9,004,998,507,819,682,000 | 42.814286 | 138 | 0.621128 | false |
osuripple/pep.py | objects/streamList.py | 1 | 2168 | from objects import stream
from objects import glob
# TODO: use *args and **kwargs
class streamList:
def __init__(self):
self.streams = {}
def add(self, name):
"""
Create a new stream list if it doesn't already exist
:param name: stream name
:return:
"""
if name not in self.streams:
self.streams[name] = stream.stream(name)
def remove(self, name):
"""
Removes an existing stream and kick every user in it
:param name: stream name
:return:
"""
if name in self.streams:
for i in self.streams[name].clients:
if i in glob.tokens.tokens:
glob.tokens.tokens[i].leaveStream(name)
self.streams.pop(name)
def join(self, streamName, client=None, token=None):
"""
Add a client to a stream
:param streamName: stream name
:param client: client (osuToken) object
:param token: client uuid string
:return:
"""
if streamName not in self.streams:
return
self.streams[streamName].addClient(client=client, token=token)
def leave(self, streamName, client=None, token=None):
"""
Remove a client from a stream
:param streamName: stream name
:param client: client (osuToken) object
:param token: client uuid string
:return:
"""
if streamName not in self.streams:
return
self.streams[streamName].removeClient(client=client, token=token)
def broadcast(self, streamName, data, but=None):
"""
Send some data to all clients in a stream
:param streamName: stream name
:param data: data to send
:param but: array of tokens to ignore. Default: None (send to everyone)
:return:
"""
if streamName not in self.streams:
return
self.streams[streamName].broadcast(data, but)
def dispose(self, streamName, *args, **kwargs):
"""
Call `dispose` on `streamName`
:param streamName: name of the stream
:param args:
:param kwargs:
:return:
"""
if streamName not in self.streams:
return
self.streams[streamName].dispose(*args, **kwargs)
def getStream(self, streamName):
"""
Returns streamName's stream object or None if it doesn't exist
:param streamName:
:return:
"""
if streamName in self.streams:
return self.streams[streamName]
return None | agpl-3.0 | -8,497,456,927,264,516,000 | 22.074468 | 73 | 0.693266 | false |
nephomaniac/eutester | testcases/cloud_admin/get_debug.py | 6 | 5886 | #!/usr/bin/python
from eucaops import Eucaops
from eutester.eutestcase import EutesterTestCase
class GatherDebug(EutesterTestCase):
basic_commands = ['df -B M',
'ps aux',
'free',
'uptime']
network_commands = ['iptables -L',
'iptables -L -t nat',
'arp -a',
'ip addr show',
'ifconfig',
'brctl show',
'route',
'netstat -lnp']
euca_commands = ['cat /etc/eucalyptus/eucalyptus.conf | grep -v \'#\' ',
'cat /etc/eucalyptus/eucalyptus-version',
'ps aux | grep euca']
clc_commands = ['euca-describe-services -E -A',
'euca-describe-availability-zones verbose',
'euca-describe-instances verbose',
'euca-describe-volumes verbose',
'euca-describe-snapshots verbose',
'euca-describe-keypairs verbose',
'euca-describe-groups verbose']
sc_commands = ['ls -l /dev/',
'losetup -a',
'service tgtd status'
'tgtadm --lld iscsi --mode target --op show',
'service iscsid status'
'iscsiadm -m session -P 3',
'pvdisplay',
'lvdisplay',
'vgdisplay',
'mpathconf',
'multipath -ll']
nc_commands = ['service iscsid status',
'iscsiadm -m session -P 3',
'mpathconf',
'multipath -ll',
'virsh list',
'losetup -a',
'dmsetup status',
'll /var/lib/eucalyptus/instances/**/**/**']
def __init__(self):
self.setuptestcase()
self.setup_parser()
self.get_args()
# Setup basic eutester object
self.tester = Eucaops( config_file=self.args.config_file, password=self.args.password,download_creds=True)
def clean_method(self):
pass
def run_command_list(self,machine, list):
for command in list:
machine.sys(command)
def debug_clc(self, **kwargs):
clc_commands = self.basic_commands + self.network_commands + self.euca_commands + self.clc_commands
for machine in self.tester.get_component_machines("clc"):
for command in clc_commands:
machine.sys("source " + self.tester.credpath + "/eucarc && " + command)
for account in self.tester.get_all_accounts():
account_name = next((value for key, value in account.iteritems() if 'account_name' in key), None)
self.tester.debug( "## Account Name: " + account_name )
for user in self.tester.get_users_from_account(delegate_account=account_name):
user_name = next((value for key, value in user.iteritems() if 'user_name' in key), None)
self.tester.debug( "### User Name: " + user_name )
for policy in self.tester.get_user_policies(user_name, delegate_account=account_name):
self.tester.debug( "#### User " + user_name + " Policy ####" )
for key, value in policy.iteritems():
self.tester.debug( key + ": " + value )
for group in self.tester.get_all_groups(account_name=account_name):
group_name = next((value for key, value in group.iteritems() if 'group_name' in key), None)
self.tester.debug( "### Group Name: " + group_name )
for policy in self.tester.get_group_policies(group_name, delegate_account=account_name):
self.tester.debug( "#### Group " + group_name + " Policy ####" )
for key, value in policy.iteritems():
self.tester.debug( key + ": " + value )
def debug_walrus(self, **kwargs):
walrus_commands = self.basic_commands + self.network_commands + self.euca_commands
for machine in self.tester.get_component_machines("ws"):
self.run_command_list(machine,walrus_commands)
def debug_cc(self, **kwargs):
cc_commands = self.basic_commands + self.network_commands + self.euca_commands
for machine in self.tester.get_component_machines("cc"):
self.run_command_list(machine,cc_commands)
def debug_sc(self, **kwargs):
sc_commands = self.basic_commands + self.network_commands + self.euca_commands + self.sc_commands
for machine in self.tester.get_component_machines("sc"):
self.run_command_list(machine,sc_commands)
def debug_nc(self, **kwargs):
nc_commands = self.basic_commands + self.network_commands + self.euca_commands + self.nc_commands
for machine in self.tester.get_component_machines("nc"):
self.run_command_list(machine,nc_commands)
def cleanup(self):
pass
def DebugAll(self):
self.debug_clc()
self.debug_walrus()
self.debug_cc()
self.debug_sc()
self.debug_sc()
if __name__ == "__main__":
testcase = GatherDebug()
### Use the list of tests passed from config/command line to determine what subset of tests to run
### or use a predefined list "VolumeTagging", "InstanceTagging", "SnapshotTagging", "ImageTagging"
list = testcase.args.tests or ["DebugAll"]
### Convert test suite methods to EutesterUnitTest objects
unit_list = [ ]
for test in list:
unit_list.append( testcase.create_testunit_by_name(test) )
### Run the EutesterUnitTest objects
result = testcase.run_test_case_list(unit_list,clean_on_exit=True)
exit(result)
| bsd-2-clause | 8,746,002,617,961,746,000 | 41.963504 | 114 | 0.54825 | false |
OpenInkpot-archive/iplinux-python-redis | redis/client.py | 5 | 51204 | import datetime
import errno
import socket
import threading
import time
import warnings
from itertools import chain
from redis.exceptions import ConnectionError, ResponseError, InvalidResponse
from redis.exceptions import RedisError, AuthenticationError
class ConnectionPool(threading.local):
"Manages a list of connections on the local thread"
def __init__(self):
self.connections = {}
def make_connection_key(self, host, port, db):
"Create a unique key for the specified host, port and db"
return '%s:%s:%s' % (host, port, db)
def get_connection(self, host, port, db, password, socket_timeout):
"Return a specific connection for the specified host, port and db"
key = self.make_connection_key(host, port, db)
if key not in self.connections:
self.connections[key] = Connection(
host, port, db, password, socket_timeout)
return self.connections[key]
def get_all_connections(self):
"Return a list of all connection objects the manager knows about"
return self.connections.values()
class Connection(object):
"Manages TCP communication to and from a Redis server"
def __init__(self, host='localhost', port=6379, db=0, password=None,
socket_timeout=None):
self.host = host
self.port = port
self.db = db
self.password = password
self.socket_timeout = socket_timeout
self._sock = None
self._fp = None
def connect(self, redis_instance):
"Connects to the Redis server if not already connected"
if self._sock:
return
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.host, self.port))
except socket.error, e:
# args for socket.error can either be (errno, "message")
# or just "message"
if len(e.args) == 1:
error_message = "Error connecting to %s:%s. %s." % \
(self.host, self.port, e.args[0])
else:
error_message = "Error %s connecting %s:%s. %s." % \
(e.args[0], self.host, self.port, e.args[1])
raise ConnectionError(error_message)
sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
sock.settimeout(self.socket_timeout)
self._sock = sock
self._fp = sock.makefile('r')
redis_instance._setup_connection()
def disconnect(self):
"Disconnects from the Redis server"
if self._sock is None:
return
try:
self._sock.close()
except socket.error:
pass
self._sock = None
self._fp = None
def send(self, command, redis_instance):
"Send ``command`` to the Redis server. Return the result."
self.connect(redis_instance)
try:
self._sock.sendall(command)
except socket.error, e:
if e.args[0] == errno.EPIPE:
self.disconnect()
raise ConnectionError("Error %s while writing to socket. %s." % \
e.args)
def read(self, length=None):
"""
Read a line from the socket is length is None,
otherwise read ``length`` bytes
"""
try:
if length is not None:
return self._fp.read(length)
return self._fp.readline()
except socket.error, e:
self.disconnect()
if e.args and e.args[0] == errno.EAGAIN:
raise ConnectionError("Error while reading from socket: %s" % \
e.args[1])
return ''
def list_or_args(command, keys, args):
# returns a single list combining keys and args
# if keys is not a list or args has items, issue a
# deprecation warning
oldapi = bool(args)
try:
i = iter(keys)
# a string can be iterated, but indicates
# keys wasn't passed as a list
if isinstance(keys, basestring):
oldapi = True
except TypeError:
oldapi = True
keys = [keys]
if oldapi:
warnings.warn(DeprecationWarning(
"Passing *args to Redis.%s has been deprecated. "
"Pass an iterable to ``keys`` instead" % command
))
keys.extend(args)
return keys
def timestamp_to_datetime(response):
"Converts a unix timestamp to a Python datetime object"
if not response:
return None
try:
response = int(response)
except ValueError:
return None
return datetime.datetime.fromtimestamp(response)
def string_keys_to_dict(key_string, callback):
return dict([(key, callback) for key in key_string.split()])
def dict_merge(*dicts):
merged = {}
[merged.update(d) for d in dicts]
return merged
def parse_info(response):
"Parse the result of Redis's INFO command into a Python dict"
info = {}
def get_value(value):
if ',' not in value:
return value
sub_dict = {}
for item in value.split(','):
k, v = item.split('=')
try:
sub_dict[k] = int(v)
except ValueError:
sub_dict[k] = v
return sub_dict
for line in response.splitlines():
key, value = line.split(':')
try:
info[key] = int(value)
except ValueError:
info[key] = get_value(value)
return info
def pairs_to_dict(response):
"Create a dict given a list of key/value pairs"
return dict(zip(response[::2], response[1::2]))
def zset_score_pairs(response, **options):
"""
If ``withscores`` is specified in the options, return the response as
a list of (value, score) pairs
"""
if not response or not options['withscores']:
return response
return zip(response[::2], map(float, response[1::2]))
def int_or_none(response):
if response is None:
return None
return int(response)
def float_or_none(response):
if response is None:
return None
return float(response)
class Redis(threading.local):
"""
Implementation of the Redis protocol.
This abstract class provides a Python interface to all Redis commands
and an implementation of the Redis protocol.
Connection and Pipeline derive from this, implementing how
the commands are sent and received to the Redis server
"""
RESPONSE_CALLBACKS = dict_merge(
string_keys_to_dict(
'AUTH DEL EXISTS EXPIRE EXPIREAT HDEL HEXISTS HMSET MOVE MSETNX '
'RENAMENX SADD SISMEMBER SMOVE SETEX SETNX SREM ZADD ZREM',
bool
),
string_keys_to_dict(
'DECRBY HLEN INCRBY LLEN SCARD SDIFFSTORE SINTERSTORE '
'SUNIONSTORE ZCARD ZREMRANGEBYRANK ZREMRANGEBYSCORE ZREVRANK',
int
),
string_keys_to_dict(
# these return OK, or int if redis-server is >=1.3.4
'LPUSH RPUSH',
lambda r: isinstance(r, int) and r or r == 'OK'
),
string_keys_to_dict('ZSCORE ZINCRBY', float_or_none),
string_keys_to_dict(
'FLUSHALL FLUSHDB LSET LTRIM MSET RENAME '
'SAVE SELECT SET SHUTDOWN',
lambda r: r == 'OK'
),
string_keys_to_dict('BLPOP BRPOP', lambda r: r and tuple(r) or None),
string_keys_to_dict('SDIFF SINTER SMEMBERS SUNION',
lambda r: set(r)
),
string_keys_to_dict('ZRANGE ZRANGEBYSCORE ZREVRANGE', zset_score_pairs),
{
'BGREWRITEAOF': lambda r: \
r == 'Background rewriting of AOF file started',
'BGSAVE': lambda r: r == 'Background saving started',
'HGETALL': lambda r: r and pairs_to_dict(r) or {},
'INFO': parse_info,
'LASTSAVE': timestamp_to_datetime,
'PING': lambda r: r == 'PONG',
'RANDOMKEY': lambda r: r and r or None,
'TTL': lambda r: r != -1 and r or None,
'ZRANK': int_or_none,
}
)
# commands that should NOT pull data off the network buffer when executed
SUBSCRIPTION_COMMANDS = set([
'SUBSCRIBE', 'UNSUBSCRIBE', 'PSUBSCRIBE', 'PUNSUBSCRIBE'
])
def __init__(self, host='localhost', port=6379,
db=0, password=None, socket_timeout=None,
connection_pool=None,
charset='utf-8', errors='strict'):
self.encoding = charset
self.errors = errors
self.connection = None
self.subscribed = False
self.connection_pool = connection_pool and connection_pool or ConnectionPool()
self.select(db, host, port, password, socket_timeout)
#### Legacty accessors of connection information ####
def _get_host(self):
return self.connection.host
host = property(_get_host)
def _get_port(self):
return self.connection.port
port = property(_get_port)
def _get_db(self):
return self.connection.db
db = property(_get_db)
def pipeline(self, transaction=True):
"""
Return a new pipeline object that can queue multiple commands for
later execution. ``transaction`` indicates whether all commands
should be executed atomically. Apart from multiple atomic operations,
pipelines are useful for batch loading of data as they reduce the
number of back and forth network operations between client and server.
"""
return Pipeline(
self.connection,
transaction,
self.encoding,
self.errors
)
def lock(self, name, timeout=None, sleep=0.1):
"""
Return a new Lock object using key ``name`` that mimics
the behavior of threading.Lock.
If specified, ``timeout`` indicates a maximum life for the lock.
By default, it will remain locked until release() is called.
``sleep`` indicates the amount of time to sleep per loop iteration
when the lock is in blocking mode and another client is currently
holding the lock.
"""
return Lock(self, name, timeout=timeout, sleep=sleep)
#### COMMAND EXECUTION AND PROTOCOL PARSING ####
def _execute_command(self, command_name, command, **options):
subscription_command = command_name in self.SUBSCRIPTION_COMMANDS
if self.subscribed and not subscription_command:
raise RedisError("Cannot issue commands other than SUBSCRIBE and "
"UNSUBSCRIBE while channels are open")
try:
self.connection.send(command, self)
if subscription_command:
return None
return self.parse_response(command_name, **options)
except ConnectionError:
self.connection.disconnect()
self.connection.send(command, self)
if subscription_command:
return None
return self.parse_response(command_name, **options)
def execute_command(self, *args, **options):
"Sends the command to the redis server and returns it's response"
cmd_count = len(args)
cmds = []
for i in args:
enc_value = self.encode(i)
cmds.append('$%s\r\n%s\r\n' % (len(enc_value), enc_value))
return self._execute_command(
args[0],
'*%s\r\n%s' % (cmd_count, ''.join(cmds)),
**options
)
def _parse_response(self, command_name, catch_errors):
conn = self.connection
response = conn.read()[:-2] # strip last two characters (\r\n)
if not response:
self.connection.disconnect()
raise ConnectionError("Socket closed on remote end")
# server returned a null value
if response in ('$-1', '*-1'):
return None
byte, response = response[0], response[1:]
# server returned an error
if byte == '-':
if response.startswith('ERR '):
response = response[4:]
raise ResponseError(response)
# single value
elif byte == '+':
return response
# int value
elif byte == ':':
return int(response)
# bulk response
elif byte == '$':
length = int(response)
if length == -1:
return None
response = length and conn.read(length) or ''
conn.read(2) # read the \r\n delimiter
return response
# multi-bulk response
elif byte == '*':
length = int(response)
if length == -1:
return None
if not catch_errors:
return [self._parse_response(command_name, catch_errors)
for i in range(length)]
else:
# for pipelines, we need to read everything,
# including response errors. otherwise we'd
# completely mess up the receive buffer
data = []
for i in range(length):
try:
data.append(
self._parse_response(command_name, catch_errors)
)
except Exception, e:
data.append(e)
return data
raise InvalidResponse("Unknown response type for: %s" % command_name)
def parse_response(self, command_name, catch_errors=False, **options):
"Parses a response from the Redis server"
response = self._parse_response(command_name, catch_errors)
if command_name in self.RESPONSE_CALLBACKS:
return self.RESPONSE_CALLBACKS[command_name](response, **options)
return response
def encode(self, value):
"Encode ``value`` using the instance's charset"
if isinstance(value, str):
return value
if isinstance(value, unicode):
return value.encode(self.encoding, self.errors)
# not a string or unicode, attempt to convert to a string
return str(value)
#### CONNECTION HANDLING ####
def get_connection(self, host, port, db, password, socket_timeout):
"Returns a connection object"
conn = self.connection_pool.get_connection(
host, port, db, password, socket_timeout)
# if for whatever reason the connection gets a bad password, make
# sure a subsequent attempt with the right password makes its way
# to the connection
conn.password = password
return conn
def _setup_connection(self):
"""
After successfully opening a socket to the Redis server, the
connection object calls this method to authenticate and select
the appropriate database.
"""
if self.connection.password:
if not self.execute_command('AUTH', self.connection.password):
raise AuthenticationError("Invalid Password")
self.execute_command('SELECT', self.connection.db)
def select(self, db, host=None, port=None, password=None,
socket_timeout=None):
"""
Switch to a different Redis connection.
If the host and port aren't provided and there's an existing
connection, use the existing connection's host and port instead.
Note this method actually replaces the underlying connection object
prior to issuing the SELECT command. This makes sure we protect
the thread-safe connections
"""
if host is None:
if self.connection is None:
raise RedisError("A valid hostname or IP address "
"must be specified")
host = self.connection.host
if port is None:
if self.connection is None:
raise RedisError("A valid port must be specified")
port = self.connection.port
self.connection = self.get_connection(
host, port, db, password, socket_timeout)
#### SERVER INFORMATION ####
def bgrewriteaof(self):
"Tell the Redis server to rewrite the AOF file from data in memory."
return self.execute_command('BGREWRITEAOF')
def bgsave(self):
"""
Tell the Redis server to save its data to disk. Unlike save(),
this method is asynchronous and returns immediately.
"""
return self.execute_command('BGSAVE')
def dbsize(self):
"Returns the number of keys in the current database"
return self.execute_command('DBSIZE')
def delete(self, *names):
"Delete one or more keys specified by ``names``"
return self.execute_command('DEL', *names)
__delitem__ = delete
def flush(self, all_dbs=False):
warnings.warn(DeprecationWarning(
"'flush' has been deprecated. "
"Use Redis.flushdb() or Redis.flushall() instead"))
if all_dbs:
return self.flushall()
return self.flushdb()
def flushall(self):
"Delete all keys in all databases on the current host"
return self.execute_command('FLUSHALL')
def flushdb(self):
"Delete all keys in the current database"
return self.execute_command('FLUSHDB')
def info(self):
"Returns a dictionary containing information about the Redis server"
return self.execute_command('INFO')
def lastsave(self):
"""
Return a Python datetime object representing the last time the
Redis database was saved to disk
"""
return self.execute_command('LASTSAVE')
def ping(self):
"Ping the Redis server"
return self.execute_command('PING')
def save(self):
"""
Tell the Redis server to save its data to disk,
blocking until the save is complete
"""
return self.execute_command('SAVE')
#### BASIC KEY COMMANDS ####
def append(self, key, value):
"""
Appends the string ``value`` to the value at ``key``. If ``key``
doesn't already exist, create it with a value of ``value``.
Returns the new length of the value at ``key``.
"""
return self.execute_command('APPEND', key, value)
def decr(self, name, amount=1):
"""
Decrements the value of ``key`` by ``amount``. If no key exists,
the value will be initialized as 0 - ``amount``
"""
return self.execute_command('DECRBY', name, amount)
def exists(self, name):
"Returns a boolean indicating whether key ``name`` exists"
return self.execute_command('EXISTS', name)
__contains__ = exists
def expire(self, name, time):
"Set an expire flag on key ``name`` for ``time`` seconds"
return self.execute_command('EXPIRE', name, time)
def expireat(self, name, when):
"""
Set an expire flag on key ``name``. ``when`` can be represented
as an integer indicating unix time or a Python datetime object.
"""
if isinstance(when, datetime.datetime):
when = int(time.mktime(when.timetuple()))
return self.execute_command('EXPIREAT', name, when)
def get(self, name):
"""
Return the value at key ``name``, or None of the key doesn't exist
"""
return self.execute_command('GET', name)
__getitem__ = get
def getset(self, name, value):
"""
Set the value at key ``name`` to ``value`` if key doesn't exist
Return the value at key ``name`` atomically
"""
return self.execute_command('GETSET', name, value)
def incr(self, name, amount=1):
"""
Increments the value of ``key`` by ``amount``. If no key exists,
the value will be initialized as ``amount``
"""
return self.execute_command('INCRBY', name, amount)
def keys(self, pattern='*'):
"Returns a list of keys matching ``pattern``"
return self.execute_command('KEYS', pattern)
def mget(self, keys, *args):
"""
Returns a list of values ordered identically to ``keys``
* Passing *args to this method has been deprecated *
"""
keys = list_or_args('mget', keys, args)
return self.execute_command('MGET', *keys)
def mset(self, mapping):
"Sets each key in the ``mapping`` dict to its corresponding value"
items = []
[items.extend(pair) for pair in mapping.iteritems()]
return self.execute_command('MSET', *items)
def msetnx(self, mapping):
"""
Sets each key in the ``mapping`` dict to its corresponding value if
none of the keys are already set
"""
items = []
[items.extend(pair) for pair in mapping.iteritems()]
return self.execute_command('MSETNX', *items)
def move(self, name, db):
"Moves the key ``name`` to a different Redis database ``db``"
return self.execute_command('MOVE', name, db)
def randomkey(self):
"Returns the name of a random key"
return self.execute_command('RANDOMKEY')
def rename(self, src, dst, **kwargs):
"""
Rename key ``src`` to ``dst``
* The following flags have been deprecated *
If ``preserve`` is True, rename the key only if the destination name
doesn't already exist
"""
if kwargs:
if 'preserve' in kwargs:
warnings.warn(DeprecationWarning(
"preserve option to 'rename' is deprecated, "
"use Redis.renamenx instead"))
if kwargs['preserve']:
return self.renamenx(src, dst)
return self.execute_command('RENAME', src, dst)
def renamenx(self, src, dst):
"Rename key ``src`` to ``dst`` if ``dst`` doesn't already exist"
return self.execute_command('RENAMENX', src, dst)
def set(self, name, value, **kwargs):
"""
Set the value at key ``name`` to ``value``
* The following flags have been deprecated *
If ``preserve`` is True, set the value only if key doesn't already
exist
If ``getset`` is True, set the value only if key doesn't already exist
and return the resulting value of key
"""
if kwargs:
if 'getset' in kwargs:
warnings.warn(DeprecationWarning(
"getset option to 'set' is deprecated, "
"use Redis.getset() instead"))
if kwargs['getset']:
return self.getset(name, value)
if 'preserve' in kwargs:
warnings.warn(DeprecationWarning(
"preserve option to 'set' is deprecated, "
"use Redis.setnx() instead"))
if kwargs['preserve']:
return self.setnx(name, value)
return self.execute_command('SET', name, value)
__setitem__ = set
def setex(self, name, value, time):
"""
Set the value of key ``name`` to ``value``
that expires in ``time`` seconds
"""
return self.execute_command('SETEX', name, time, value)
def setnx(self, name, value):
"Set the value of key ``name`` to ``value`` if key doesn't exist"
return self.execute_command('SETNX', name, value)
def substr(self, name, start, end=-1):
"""
Return a substring of the string at key ``name``. ``start`` and ``end``
are 0-based integers specifying the portion of the string to return.
"""
return self.execute_command('SUBSTR', name, start, end)
def ttl(self, name):
"Returns the number of seconds until the key ``name`` will expire"
return self.execute_command('TTL', name)
def type(self, name):
"Returns the type of key ``name``"
return self.execute_command('TYPE', name)
#### LIST COMMANDS ####
def blpop(self, keys, timeout=0):
"""
LPOP a value off of the first non-empty list
named in the ``keys`` list.
If none of the lists in ``keys`` has a value to LPOP, then block
for ``timeout`` seconds, or until a value gets pushed on to one
of the lists.
If timeout is 0, then block indefinitely.
"""
if isinstance(keys, basestring):
keys = [keys]
else:
keys = list(keys)
keys.append(timeout)
return self.execute_command('BLPOP', *keys)
def brpop(self, keys, timeout=0):
"""
RPOP a value off of the first non-empty list
named in the ``keys`` list.
If none of the lists in ``keys`` has a value to LPOP, then block
for ``timeout`` seconds, or until a value gets pushed on to one
of the lists.
If timeout is 0, then block indefinitely.
"""
if isinstance(keys, basestring):
keys = [keys]
else:
keys = list(keys)
keys.append(timeout)
return self.execute_command('BRPOP', *keys)
def lindex(self, name, index):
"""
Return the item from list ``name`` at position ``index``
Negative indexes are supported and will return an item at the
end of the list
"""
return self.execute_command('LINDEX', name, index)
def llen(self, name):
"Return the length of the list ``name``"
return self.execute_command('LLEN', name)
def lpop(self, name):
"Remove and return the first item of the list ``name``"
return self.execute_command('LPOP', name)
def lpush(self, name, value):
"Push ``value`` onto the head of the list ``name``"
return self.execute_command('LPUSH', name, value)
def lrange(self, name, start, end):
"""
Return a slice of the list ``name`` between
position ``start`` and ``end``
``start`` and ``end`` can be negative numbers just like
Python slicing notation
"""
return self.execute_command('LRANGE', name, start, end)
def lrem(self, name, value, num=0):
"""
Remove the first ``num`` occurrences of ``value`` from list ``name``
If ``num`` is 0, then all occurrences will be removed
"""
return self.execute_command('LREM', name, num, value)
def lset(self, name, index, value):
"Set ``position`` of list ``name`` to ``value``"
return self.execute_command('LSET', name, index, value)
def ltrim(self, name, start, end):
"""
Trim the list ``name``, removing all values not within the slice
between ``start`` and ``end``
``start`` and ``end`` can be negative numbers just like
Python slicing notation
"""
return self.execute_command('LTRIM', name, start, end)
def pop(self, name, tail=False):
"""
Pop and return the first or last element of list ``name``
* This method has been deprecated,
use Redis.lpop or Redis.rpop instead *
"""
warnings.warn(DeprecationWarning(
"Redis.pop has been deprecated, "
"use Redis.lpop or Redis.rpop instead"))
if tail:
return self.rpop(name)
return self.lpop(name)
def push(self, name, value, head=False):
"""
Push ``value`` onto list ``name``.
* This method has been deprecated,
use Redis.lpush or Redis.rpush instead *
"""
warnings.warn(DeprecationWarning(
"Redis.push has been deprecated, "
"use Redis.lpush or Redis.rpush instead"))
if head:
return self.lpush(name, value)
return self.rpush(name, value)
def rpop(self, name):
"Remove and return the last item of the list ``name``"
return self.execute_command('RPOP', name)
def rpoplpush(self, src, dst):
"""
RPOP a value off of the ``src`` list and atomically LPUSH it
on to the ``dst`` list. Returns the value.
"""
return self.execute_command('RPOPLPUSH', src, dst)
def rpush(self, name, value):
"Push ``value`` onto the tail of the list ``name``"
return self.execute_command('RPUSH', name, value)
def sort(self, name, start=None, num=None, by=None, get=None,
desc=False, alpha=False, store=None):
"""
Sort and return the list, set or sorted set at ``name``.
``start`` and ``num`` allow for paging through the sorted data
``by`` allows using an external key to weight and sort the items.
Use an "*" to indicate where in the key the item value is located
``get`` allows for returning items from external keys rather than the
sorted data itself. Use an "*" to indicate where int he key
the item value is located
``desc`` allows for reversing the sort
``alpha`` allows for sorting lexicographically rather than numerically
``store`` allows for storing the result of the sort into
the key ``store``
"""
if (start is not None and num is None) or \
(num is not None and start is None):
raise RedisError("``start`` and ``num`` must both be specified")
pieces = [name]
if by is not None:
pieces.append('BY')
pieces.append(by)
if start is not None and num is not None:
pieces.append('LIMIT')
pieces.append(start)
pieces.append(num)
if get is not None:
pieces.append('GET')
pieces.append(get)
if desc:
pieces.append('DESC')
if alpha:
pieces.append('ALPHA')
if store is not None:
pieces.append('STORE')
pieces.append(store)
return self.execute_command('SORT', *pieces)
#### SET COMMANDS ####
def sadd(self, name, value):
"Add ``value`` to set ``name``"
return self.execute_command('SADD', name, value)
def scard(self, name):
"Return the number of elements in set ``name``"
return self.execute_command('SCARD', name)
def sdiff(self, keys, *args):
"Return the difference of sets specified by ``keys``"
keys = list_or_args('sdiff', keys, args)
return self.execute_command('SDIFF', *keys)
def sdiffstore(self, dest, keys, *args):
"""
Store the difference of sets specified by ``keys`` into a new
set named ``dest``. Returns the number of keys in the new set.
"""
keys = list_or_args('sdiffstore', keys, args)
return self.execute_command('SDIFFSTORE', dest, *keys)
def sinter(self, keys, *args):
"Return the intersection of sets specified by ``keys``"
keys = list_or_args('sinter', keys, args)
return self.execute_command('SINTER', *keys)
def sinterstore(self, dest, keys, *args):
"""
Store the intersection of sets specified by ``keys`` into a new
set named ``dest``. Returns the number of keys in the new set.
"""
keys = list_or_args('sinterstore', keys, args)
return self.execute_command('SINTERSTORE', dest, *keys)
def sismember(self, name, value):
"Return a boolean indicating if ``value`` is a member of set ``name``"
return self.execute_command('SISMEMBER', name, value)
def smembers(self, name):
"Return all members of the set ``name``"
return self.execute_command('SMEMBERS', name)
def smove(self, src, dst, value):
"Move ``value`` from set ``src`` to set ``dst`` atomically"
return self.execute_command('SMOVE', src, dst, value)
def spop(self, name):
"Remove and return a random member of set ``name``"
return self.execute_command('SPOP', name)
def srandmember(self, name):
"Return a random member of set ``name``"
return self.execute_command('SRANDMEMBER', name)
def srem(self, name, value):
"Remove ``value`` from set ``name``"
return self.execute_command('SREM', name, value)
def sunion(self, keys, *args):
"Return the union of sets specifiued by ``keys``"
keys = list_or_args('sunion', keys, args)
return self.execute_command('SUNION', *keys)
def sunionstore(self, dest, keys, *args):
"""
Store the union of sets specified by ``keys`` into a new
set named ``dest``. Returns the number of keys in the new set.
"""
keys = list_or_args('sunionstore', keys, args)
return self.execute_command('SUNIONSTORE', dest, *keys)
#### SORTED SET COMMANDS ####
def zadd(self, name, value, score):
"Add member ``value`` with score ``score`` to sorted set ``name``"
return self.execute_command('ZADD', name, score, value)
def zcard(self, name):
"Return the number of elements in the sorted set ``name``"
return self.execute_command('ZCARD', name)
def zincr(self, key, member, value=1):
"This has been deprecated, use zincrby instead"
warnings.warn(DeprecationWarning(
"Redis.zincr has been deprecated, use Redis.zincrby instead"
))
return self.zincrby(key, member, value)
def zincrby(self, name, value, amount=1):
"Increment the score of ``value`` in sorted set ``name`` by ``amount``"
return self.execute_command('ZINCRBY', name, amount, value)
def zinter(self, dest, keys, aggregate=None):
warnings.warn(DeprecationWarning(
"Redis.zinter has been deprecated, use Redis.zinterstore instead"
))
return self.zinterstore(dest, keys, aggregate)
def zinterstore(self, dest, keys, aggregate=None):
"""
Intersect multiple sorted sets specified by ``keys`` into
a new sorted set, ``dest``. Scores in the destination will be
aggregated based on the ``aggregate``, or SUM if none is provided.
"""
return self._zaggregate('ZINTERSTORE', dest, keys, aggregate)
def zrange(self, name, start, end, desc=False, withscores=False):
"""
Return a range of values from sorted set ``name`` between
``start`` and ``end`` sorted in ascending order.
``start`` and ``end`` can be negative, indicating the end of the range.
``desc`` indicates to sort in descending order.
``withscores`` indicates to return the scores along with the values.
The return type is a list of (value, score) pairs
"""
if desc:
return self.zrevrange(name, start, end, withscores)
pieces = ['ZRANGE', name, start, end]
if withscores:
pieces.append('withscores')
return self.execute_command(*pieces, **{'withscores': withscores})
def zrangebyscore(self, name, min, max,
start=None, num=None, withscores=False):
"""
Return a range of values from the sorted set ``name`` with scores
between ``min`` and ``max``.
If ``start`` and ``num`` are specified, then return a slice of the range.
``withscores`` indicates to return the scores along with the values.
The return type is a list of (value, score) pairs
"""
if (start is not None and num is None) or \
(num is not None and start is None):
raise RedisError("``start`` and ``num`` must both be specified")
pieces = ['ZRANGEBYSCORE', name, min, max]
if start is not None and num is not None:
pieces.extend(['LIMIT', start, num])
if withscores:
pieces.append('withscores')
return self.execute_command(*pieces, **{'withscores': withscores})
def zrank(self, name, value):
"""
Returns a 0-based value indicating the rank of ``value`` in sorted set
``name``
"""
return self.execute_command('ZRANK', name, value)
def zrem(self, name, value):
"Remove member ``value`` from sorted set ``name``"
return self.execute_command('ZREM', name, value)
def zremrangebyrank(self, name, min, max):
"""
Remove all elements in the sorted set ``name`` with ranks between
``min`` and ``max``. Values are 0-based, ordered from smallest score
to largest. Values can be negative indicating the highest scores.
Returns the number of elements removed
"""
return self.execute_command('ZREMRANGEBYRANK', name, min, max)
def zremrangebyscore(self, name, min, max):
"""
Remove all elements in the sorted set ``name`` with scores
between ``min`` and ``max``. Returns the number of elements removed.
"""
return self.execute_command('ZREMRANGEBYSCORE', name, min, max)
def zrevrange(self, name, start, num, withscores=False):
"""
Return a range of values from sorted set ``name`` between
``start`` and ``num`` sorted in descending order.
``start`` and ``num`` can be negative, indicating the end of the range.
``withscores`` indicates to return the scores along with the values
as a dictionary of value => score
"""
pieces = ['ZREVRANGE', name, start, num]
if withscores:
pieces.append('withscores')
return self.execute_command(*pieces, **{'withscores': withscores})
def zrevrank(self, name, value):
"""
Returns a 0-based value indicating the descending rank of
``value`` in sorted set ``name``
"""
return self.execute_command('ZREVRANK', name, value)
def zscore(self, name, value):
"Return the score of element ``value`` in sorted set ``name``"
return self.execute_command('ZSCORE', name, value)
def zunion(self, dest, keys, aggregate=None):
warnings.warn(DeprecationWarning(
"Redis.zunion has been deprecated, use Redis.zunionstore instead"
))
return self.zunionstore(dest, keys, aggregate)
def zunionstore(self, dest, keys, aggregate=None):
"""
Union multiple sorted sets specified by ``keys`` into
a new sorted set, ``dest``. Scores in the destination will be
aggregated based on the ``aggregate``, or SUM if none is provided.
"""
return self._zaggregate('ZUNIONSTORE', dest, keys, aggregate)
def _zaggregate(self, command, dest, keys, aggregate=None):
pieces = [command, dest, len(keys)]
if isinstance(keys, dict):
items = keys.items()
keys = [i[0] for i in items]
weights = [i[1] for i in items]
else:
weights = None
pieces.extend(keys)
if weights:
pieces.append('WEIGHTS')
pieces.extend(weights)
if aggregate:
pieces.append('AGGREGATE')
pieces.append(aggregate)
return self.execute_command(*pieces)
#### HASH COMMANDS ####
def hdel(self, name, key):
"Delete ``key`` from hash ``name``"
return self.execute_command('HDEL', name, key)
def hexists(self, name, key):
"Returns a boolean indicating if ``key`` exists within hash ``name``"
return self.execute_command('HEXISTS', name, key)
def hget(self, name, key):
"Return the value of ``key`` within the hash ``name``"
return self.execute_command('HGET', name, key)
def hgetall(self, name):
"Return a Python dict of the hash's name/value pairs"
return self.execute_command('HGETALL', name)
def hincrby(self, name, key, amount=1):
"Increment the value of ``key`` in hash ``name`` by ``amount``"
return self.execute_command('HINCRBY', name, key, amount)
def hkeys(self, name):
"Return the list of keys within hash ``name``"
return self.execute_command('HKEYS', name)
def hlen(self, name):
"Return the number of elements in hash ``name``"
return self.execute_command('HLEN', name)
def hset(self, name, key, value):
"""
Set ``key`` to ``value`` within hash ``name``
Returns 1 if HSET created a new field, otherwise 0
"""
return self.execute_command('HSET', name, key, value)
def hsetnx(self, name, key, value):
"""
Set ``key`` to ``value`` within hash ``name`` if ``key`` does not
exist. Returns 1 if HSETNX created a field, otherwise 0.
"""
return self.execute_command("HSETNX", name, key, value)
def hmset(self, name, mapping):
"""
Sets each key in the ``mapping`` dict to its corresponding value
in the hash ``name``
"""
items = []
[items.extend(pair) for pair in mapping.iteritems()]
return self.execute_command('HMSET', name, *items)
def hmget(self, name, keys):
"Returns a list of values ordered identically to ``keys``"
return self.execute_command('HMGET', name, *keys)
def hvals(self, name):
"Return the list of values within hash ``name``"
return self.execute_command('HVALS', name)
# channels
def psubscribe(self, patterns):
"Subscribe to all channels matching any pattern in ``patterns``"
if isinstance(patterns, basestring):
patterns = [patterns]
response = self.execute_command('PSUBSCRIBE', *patterns)
# this is *after* the SUBSCRIBE in order to allow for lazy and broken
# connections that need to issue AUTH and SELECT commands
self.subscribed = True
return response
def punsubscribe(self, patterns=[]):
"""
Unsubscribe from any channel matching any pattern in ``patterns``.
If empty, unsubscribe from all channels.
"""
if isinstance(patterns, basestring):
patterns = [patterns]
return self.execute_command('PUNSUBSCRIBE', *patterns)
def subscribe(self, channels):
"Subscribe to ``channels``, waiting for messages to be published"
if isinstance(channels, basestring):
channels = [channels]
response = self.execute_command('SUBSCRIBE', *channels)
# this is *after* the SUBSCRIBE in order to allow for lazy and broken
# connections that need to issue AUTH and SELECT commands
self.subscribed = True
return response
def unsubscribe(self, channels=[]):
"""
Unsubscribe from ``channels``. If empty, unsubscribe
from all channels
"""
if isinstance(channels, basestring):
channels = [channels]
return self.execute_command('UNSUBSCRIBE', *channels)
def publish(self, channel, message):
"""
Publish ``message`` on ``channel``.
Returns the number of subscribers the message was delivered to.
"""
return self.execute_command('PUBLISH', channel, message)
def listen(self):
"Listen for messages on channels this client has been subscribed to"
while self.subscribed:
r = self.parse_response('LISTEN')
if r[0] == 'pmessage':
msg = {
'type': r[0],
'pattern': r[1],
'channel': r[2],
'data': r[3]
}
else:
msg = {
'type': r[0],
'pattern': None,
'channel': r[1],
'data': r[2]
}
if r[0] == 'unsubscribe' and r[2] == 0:
self.subscribed = False
yield msg
class Pipeline(Redis):
"""
Pipelines provide a way to transmit multiple commands to the Redis server
in one transmission. This is convenient for batch processing, such as
saving all the values in a list to Redis.
All commands executed within a pipeline are wrapped with MULTI and EXEC
calls. This guarantees all commands executed in the pipeline will be
executed atomically.
Any command raising an exception does *not* halt the execution of
subsequent commands in the pipeline. Instead, the exception is caught
and its instance is placed into the response list returned by execute().
Code iterating over the response list should be able to deal with an
instance of an exception as a potential value. In general, these will be
ResponseError exceptions, such as those raised when issuing a command
on a key of a different datatype.
"""
def __init__(self, connection, transaction, charset, errors):
self.connection = connection
self.transaction = transaction
self.encoding = charset
self.errors = errors
self.subscribed = False # NOTE not in use, but necessary
self.reset()
def reset(self):
self.command_stack = []
def _execute_command(self, command_name, command, **options):
"""
Stage a command to be executed when execute() is next called
Returns the current Pipeline object back so commands can be
chained together, such as:
pipe = pipe.set('foo', 'bar').incr('baz').decr('bang')
At some other point, you can then run: pipe.execute(),
which will execute all commands queued in the pipe.
"""
# if the command_name is 'AUTH' or 'SELECT', then this command
# must have originated after a socket connection and a call to
# _setup_connection(). run these commands immediately without
# buffering them.
if command_name in ('AUTH', 'SELECT'):
return super(Pipeline, self)._execute_command(
command_name, command, **options)
else:
self.command_stack.append((command_name, command, options))
return self
def _execute_transaction(self, commands):
# wrap the commands in MULTI ... EXEC statements to indicate an
# atomic operation
all_cmds = ''.join([c for _1, c, _2 in chain(
(('', 'MULTI\r\n', ''),),
commands,
(('', 'EXEC\r\n', ''),)
)])
self.connection.send(all_cmds, self)
# parse off the response for MULTI and all commands prior to EXEC
for i in range(len(commands)+1):
_ = self.parse_response('_')
# parse the EXEC. we want errors returned as items in the response
response = self.parse_response('_', catch_errors=True)
if len(response) != len(commands):
raise ResponseError("Wrong number of response items from "
"pipeline execution")
# Run any callbacks for the commands run in the pipeline
data = []
for r, cmd in zip(response, commands):
if not isinstance(r, Exception):
if cmd[0] in self.RESPONSE_CALLBACKS:
r = self.RESPONSE_CALLBACKS[cmd[0]](r, **cmd[2])
data.append(r)
return data
def _execute_pipeline(self, commands):
# build up all commands into a single request to increase network perf
all_cmds = ''.join([c for _1, c, _2 in commands])
self.connection.send(all_cmds, self)
data = []
for command_name, _, options in commands:
data.append(
self.parse_response(command_name, catch_errors=True, **options)
)
return data
def execute(self):
"Execute all the commands in the current pipeline"
stack = self.command_stack
self.reset()
if self.transaction:
execute = self._execute_transaction
else:
execute = self._execute_pipeline
try:
return execute(stack)
except ConnectionError:
self.connection.disconnect()
return execute(stack)
def select(self, *args, **kwargs):
raise RedisError("Cannot select a different database from a pipeline")
class Lock(object):
"""
A shared, distributed Lock. Using Redis for locking allows the Lock
to be shared across processes and/or machines.
It's left to the user to resolve deadlock issues and make sure
multiple clients play nicely together.
"""
LOCK_FOREVER = 2**31+1 # 1 past max unix time
def __init__(self, redis, name, timeout=None, sleep=0.1):
"""
Create a new Lock instnace named ``name`` using the Redis client
supplied by ``redis``.
``timeout`` indicates a maximum life for the lock.
By default, it will remain locked until release() is called.
``sleep`` indicates the amount of time to sleep per loop iteration
when the lock is in blocking mode and another client is currently
holding the lock.
Note: If using ``timeout``, you should make sure all the hosts
that are running clients are within the same timezone and are using
a network time service like ntp.
"""
self.redis = redis
self.name = name
self.acquired_until = None
self.timeout = timeout
self.sleep = sleep
def __enter__(self):
return self.acquire()
def __exit__(self, exc_type, exc_value, traceback):
self.release()
def acquire(self, blocking=True):
"""
Use Redis to hold a shared, distributed lock named ``name``.
Returns True once the lock is acquired.
If ``blocking`` is False, always return immediately. If the lock
was acquired, return True, otherwise return False.
"""
sleep = self.sleep
timeout = self.timeout
while 1:
unixtime = int(time.time())
if timeout:
timeout_at = unixtime + timeout
else:
timeout_at = Lock.LOCK_FOREVER
if self.redis.setnx(self.name, timeout_at):
self.acquired_until = timeout_at
return True
# We want blocking, but didn't acquire the lock
# check to see if the current lock is expired
existing = long(self.redis.get(self.name) or 1)
if existing < unixtime:
# the previous lock is expired, attempt to overwrite it
existing = long(self.redis.getset(self.name, timeout_at) or 1)
if existing < unixtime:
# we successfully acquired the lock
self.acquired_until = timeout_at
return True
if not blocking:
return False
time.sleep(sleep)
def release(self):
"Releases the already acquired lock"
if self.acquired_until is None:
raise ValueError("Cannot release an unlocked lock")
existing = long(self.redis.get(self.name) or 1)
# if the lock time is in the future, delete the lock
if existing >= self.acquired_until:
self.redis.delete(self.name)
self.acquired_until = None
| mit | -3,229,847,986,337,731,600 | 35.470085 | 86 | 0.585716 | false |
SPlanzer/QGIS-AIMS-Plugin | AimsUI/AimsClient/Gui/Ui_QueueEditorWidget.py | 2 | 32692 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'AimsUI/AimsClient/Gui/Ui_QueueEditorWidget.ui'
#
# Created: Fri Sep 16 08:58:25 2016
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_QueueEditorWidget(object):
def setupUi(self, QueueEditorWidget):
QueueEditorWidget.setObjectName(_fromUtf8("QueueEditorWidget"))
QueueEditorWidget.resize(400, 952)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(QueueEditorWidget.sizePolicy().hasHeightForWidth())
QueueEditorWidget.setSizePolicy(sizePolicy)
self.verticalLayout = QtGui.QVBoxLayout(QueueEditorWidget)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.scrollArea = QtGui.QScrollArea(QueueEditorWidget)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName(_fromUtf8("scrollArea"))
self.scrollAreaWidgetContents = QtGui.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, -6, 364, 1122))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.scrollAreaWidgetContents.sizePolicy().hasHeightForWidth())
self.scrollAreaWidgetContents.setSizePolicy(sizePolicy)
self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents"))
self.verticalLayout_2 = QtGui.QVBoxLayout(self.scrollAreaWidgetContents)
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.splitter = QtGui.QSplitter(self.scrollAreaWidgetContents)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.splitter.sizePolicy().hasHeightForWidth())
self.splitter.setSizePolicy(sizePolicy)
self.splitter.setOrientation(QtCore.Qt.Vertical)
self.splitter.setObjectName(_fromUtf8("splitter"))
self.gridLayoutWidget_7 = QtGui.QWidget(self.splitter)
self.gridLayoutWidget_7.setObjectName(_fromUtf8("gridLayoutWidget_7"))
self.gridLayout_14 = QtGui.QGridLayout(self.gridLayoutWidget_7)
self.gridLayout_14.setSizeConstraint(QtGui.QLayout.SetNoConstraint)
self.gridLayout_14.setMargin(0)
self.gridLayout_14.setObjectName(_fromUtf8("gridLayout_14"))
self.lNotes = QtGui.QLabel(self.gridLayoutWidget_7)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lNotes.sizePolicy().hasHeightForWidth())
self.lNotes.setSizePolicy(sizePolicy)
self.lNotes.setMinimumSize(QtCore.QSize(0, 0))
self.lNotes.setMaximumSize(QtCore.QSize(75, 16777215))
self.lNotes.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.lNotes.setWordWrap(True)
self.lNotes.setObjectName(_fromUtf8("lNotes"))
self.gridLayout_14.addWidget(self.lNotes, 1, 0, 1, 1)
self.scrollArea_2 = QtGui.QScrollArea(self.gridLayoutWidget_7)
self.scrollArea_2.setWidgetResizable(True)
self.scrollArea_2.setObjectName(_fromUtf8("scrollArea_2"))
self.scrollAreaWidgetContents_2 = QtGui.QWidget()
self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 261, 76))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.scrollAreaWidgetContents_2.sizePolicy().hasHeightForWidth())
self.scrollAreaWidgetContents_2.setSizePolicy(sizePolicy)
self.scrollAreaWidgetContents_2.setObjectName(_fromUtf8("scrollAreaWidgetContents_2"))
self.verticalLayout_4 = QtGui.QVBoxLayout(self.scrollAreaWidgetContents_2)
self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4"))
self.uWarning = QtGui.QLabel(self.scrollAreaWidgetContents_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.uWarning.sizePolicy().hasHeightForWidth())
self.uWarning.setSizePolicy(sizePolicy)
self.uWarning.setText(_fromUtf8(""))
self.uWarning.setWordWrap(True)
self.uWarning.setObjectName(_fromUtf8("uWarning"))
self.verticalLayout_4.addWidget(self.uWarning)
self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2)
self.gridLayout_14.addWidget(self.scrollArea_2, 0, 1, 1, 1)
self.scrollArea_4 = QtGui.QScrollArea(self.gridLayoutWidget_7)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.scrollArea_4.sizePolicy().hasHeightForWidth())
self.scrollArea_4.setSizePolicy(sizePolicy)
self.scrollArea_4.setMaximumSize(QtCore.QSize(16777215, 40))
self.scrollArea_4.setWidgetResizable(True)
self.scrollArea_4.setObjectName(_fromUtf8("scrollArea_4"))
self.scrollAreaWidgetContents_7 = QtGui.QWidget()
self.scrollAreaWidgetContents_7.setGeometry(QtCore.QRect(0, 0, 261, 38))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.scrollAreaWidgetContents_7.sizePolicy().hasHeightForWidth())
self.scrollAreaWidgetContents_7.setSizePolicy(sizePolicy)
self.scrollAreaWidgetContents_7.setObjectName(_fromUtf8("scrollAreaWidgetContents_7"))
self.verticalLayout_7 = QtGui.QVBoxLayout(self.scrollAreaWidgetContents_7)
self.verticalLayout_7.setObjectName(_fromUtf8("verticalLayout_7"))
self.uNotes = QtGui.QLabel(self.scrollAreaWidgetContents_7)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.uNotes.sizePolicy().hasHeightForWidth())
self.uNotes.setSizePolicy(sizePolicy)
self.uNotes.setText(_fromUtf8(""))
self.uNotes.setWordWrap(True)
self.uNotes.setObjectName(_fromUtf8("uNotes"))
self.verticalLayout_7.addWidget(self.uNotes)
self.scrollArea_4.setWidget(self.scrollAreaWidgetContents_7)
self.gridLayout_14.addWidget(self.scrollArea_4, 1, 1, 1, 1)
self.lWarning = QtGui.QLabel(self.gridLayoutWidget_7)
self.lWarning.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lWarning.sizePolicy().hasHeightForWidth())
self.lWarning.setSizePolicy(sizePolicy)
self.lWarning.setMinimumSize(QtCore.QSize(0, 0))
self.lWarning.setMaximumSize(QtCore.QSize(75, 16777215))
self.lWarning.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.lWarning.setObjectName(_fromUtf8("lWarning"))
self.gridLayout_14.addWidget(self.lWarning, 0, 0, 1, 1)
self.gridLayoutWidget_8 = QtGui.QWidget(self.splitter)
self.gridLayoutWidget_8.setObjectName(_fromUtf8("gridLayoutWidget_8"))
self.gridLayout_15 = QtGui.QGridLayout(self.gridLayoutWidget_8)
self.gridLayout_15.setMargin(0)
self.gridLayout_15.setObjectName(_fromUtf8("gridLayout_15"))
self.lWaterRoute = QtGui.QLabel(self.gridLayoutWidget_8)
self.lWaterRoute.setObjectName(_fromUtf8("lWaterRoute"))
self.gridLayout_15.addWidget(self.lWaterRoute, 17, 0, 1, 1)
self.lNumberPrefix = QtGui.QLabel(self.gridLayoutWidget_8)
self.lNumberPrefix.setObjectName(_fromUtf8("lNumberPrefix"))
self.gridLayout_15.addWidget(self.lNumberPrefix, 6, 0, 1, 1)
self.uPrefix = QtGui.QLineEdit(self.gridLayoutWidget_8)
self.uPrefix.setMinimumSize(QtCore.QSize(0, 0))
self.uPrefix.setText(_fromUtf8(""))
self.uPrefix.setObjectName(_fromUtf8("uPrefix"))
self.gridLayout_15.addWidget(self.uPrefix, 6, 1, 1, 1)
self.uUnitType = QtGui.QComboBox(self.gridLayoutWidget_8)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.uUnitType.sizePolicy().hasHeightForWidth())
self.uUnitType.setSizePolicy(sizePolicy)
self.uUnitType.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToMinimumContentsLength)
self.uUnitType.setObjectName(_fromUtf8("uUnitType"))
self.gridLayout_15.addWidget(self.uUnitType, 4, 1, 1, 1)
self.lLevelType = QtGui.QLabel(self.gridLayoutWidget_8)
self.lLevelType.setObjectName(_fromUtf8("lLevelType"))
self.gridLayout_15.addWidget(self.lLevelType, 2, 0, 1, 1)
self.lBaseNumber = QtGui.QLabel(self.gridLayoutWidget_8)
self.lBaseNumber.setObjectName(_fromUtf8("lBaseNumber"))
self.gridLayout_15.addWidget(self.lBaseNumber, 7, 0, 1, 1)
self.uRoadPrefix = QtGui.QLineEdit(self.gridLayoutWidget_8)
self.uRoadPrefix.setText(_fromUtf8(""))
self.uRoadPrefix.setReadOnly(True)
self.uRoadPrefix.setObjectName(_fromUtf8("uRoadPrefix"))
self.gridLayout_15.addWidget(self.uRoadPrefix, 13, 1, 1, 1)
self.uAlpha = QtGui.QLineEdit(self.gridLayoutWidget_8)
self.uAlpha.setMinimumSize(QtCore.QSize(0, 0))
self.uAlpha.setText(_fromUtf8(""))
self.uAlpha.setObjectName(_fromUtf8("uAlpha"))
self.gridLayout_15.addWidget(self.uAlpha, 8, 1, 1, 1)
self.uWaterRouteName = QtGui.QLineEdit(self.gridLayoutWidget_8)
self.uWaterRouteName.setText(_fromUtf8(""))
self.uWaterRouteName.setReadOnly(True)
self.uWaterRouteName.setObjectName(_fromUtf8("uWaterRouteName"))
self.gridLayout_15.addWidget(self.uWaterRouteName, 17, 1, 1, 1)
self.lNumberHigh = QtGui.QLabel(self.gridLayoutWidget_8)
self.lNumberHigh.setObjectName(_fromUtf8("lNumberHigh"))
self.gridLayout_15.addWidget(self.lNumberHigh, 9, 0, 1, 1)
self.lLevelValue = QtGui.QLabel(self.gridLayoutWidget_8)
self.lLevelValue.setObjectName(_fromUtf8("lLevelValue"))
self.gridLayout_15.addWidget(self.lLevelValue, 3, 0, 1, 1)
self.lAddressType = QtGui.QLabel(self.gridLayoutWidget_8)
self.lAddressType.setMaximumSize(QtCore.QSize(175, 16777215))
self.lAddressType.setObjectName(_fromUtf8("lAddressType"))
self.gridLayout_15.addWidget(self.lAddressType, 0, 0, 1, 1)
self.lRoadType = QtGui.QLabel(self.gridLayoutWidget_8)
self.lRoadType.setObjectName(_fromUtf8("lRoadType"))
self.gridLayout_15.addWidget(self.lRoadType, 15, 0, 1, 1)
self.uRoadSuffix = QtGui.QLineEdit(self.gridLayoutWidget_8)
self.uRoadSuffix.setText(_fromUtf8(""))
self.uRoadSuffix.setReadOnly(True)
self.uRoadSuffix.setObjectName(_fromUtf8("uRoadSuffix"))
self.gridLayout_15.addWidget(self.uRoadSuffix, 16, 1, 1, 1)
self.uRoadName = QtGui.QLineEdit(self.gridLayoutWidget_8)
self.uRoadName.setText(_fromUtf8(""))
self.uRoadName.setReadOnly(True)
self.uRoadName.setObjectName(_fromUtf8("uRoadName"))
self.gridLayout_15.addWidget(self.uRoadName, 14, 1, 1, 1)
self.uLevelValue = QtGui.QLineEdit(self.gridLayoutWidget_8)
self.uLevelValue.setMinimumSize(QtCore.QSize(0, 0))
self.uLevelValue.setText(_fromUtf8(""))
self.uLevelValue.setObjectName(_fromUtf8("uLevelValue"))
self.gridLayout_15.addWidget(self.uLevelValue, 3, 1, 1, 1)
self.lRoadPrefix = QtGui.QLabel(self.gridLayoutWidget_8)
self.lRoadPrefix.setMaximumSize(QtCore.QSize(175, 16777215))
self.lRoadPrefix.setObjectName(_fromUtf8("lRoadPrefix"))
self.gridLayout_15.addWidget(self.lRoadPrefix, 13, 0, 1, 1)
self.lAplha = QtGui.QLabel(self.gridLayoutWidget_8)
self.lAplha.setObjectName(_fromUtf8("lAplha"))
self.gridLayout_15.addWidget(self.lAplha, 8, 0, 1, 1)
self.uUnit = QtGui.QLineEdit(self.gridLayoutWidget_8)
self.uUnit.setMinimumSize(QtCore.QSize(0, 0))
self.uUnit.setText(_fromUtf8(""))
self.uUnit.setObjectName(_fromUtf8("uUnit"))
self.gridLayout_15.addWidget(self.uUnit, 5, 1, 1, 1)
self.lUnitValue = QtGui.QLabel(self.gridLayoutWidget_8)
self.lUnitValue.setMaximumSize(QtCore.QSize(175, 16777215))
self.lUnitValue.setObjectName(_fromUtf8("lUnitValue"))
self.gridLayout_15.addWidget(self.lUnitValue, 5, 0, 1, 1)
self.uLevelType = QtGui.QComboBox(self.gridLayoutWidget_8)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.uLevelType.sizePolicy().hasHeightForWidth())
self.uLevelType.setSizePolicy(sizePolicy)
self.uLevelType.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToMinimumContentsLength)
self.uLevelType.setObjectName(_fromUtf8("uLevelType"))
self.gridLayout_15.addWidget(self.uLevelType, 2, 1, 1, 1)
self.lWaterName = QtGui.QLabel(self.gridLayoutWidget_8)
self.lWaterName.setObjectName(_fromUtf8("lWaterName"))
self.gridLayout_15.addWidget(self.lWaterName, 18, 0, 1, 1)
self.uBase = QtGui.QLineEdit(self.gridLayoutWidget_8)
self.uBase.setMinimumSize(QtCore.QSize(0, 0))
self.uBase.setText(_fromUtf8(""))
self.uBase.setObjectName(_fromUtf8("uBase"))
self.gridLayout_15.addWidget(self.uBase, 7, 1, 1, 1)
self.uHigh = QtGui.QLineEdit(self.gridLayoutWidget_8)
self.uHigh.setMinimumSize(QtCore.QSize(0, 0))
self.uHigh.setText(_fromUtf8(""))
self.uHigh.setObjectName(_fromUtf8("uHigh"))
self.gridLayout_15.addWidget(self.uHigh, 9, 1, 1, 1)
self.lRclId = QtGui.QLabel(self.gridLayoutWidget_8)
self.lRclId.setObjectName(_fromUtf8("lRclId"))
self.gridLayout_15.addWidget(self.lRclId, 12, 0, 1, 1)
self.lRoadSuffix = QtGui.QLabel(self.gridLayoutWidget_8)
self.lRoadSuffix.setObjectName(_fromUtf8("lRoadSuffix"))
self.gridLayout_15.addWidget(self.lRoadSuffix, 16, 0, 1, 1)
self.lRoadName = QtGui.QLabel(self.gridLayoutWidget_8)
self.lRoadName.setMaximumSize(QtCore.QSize(175, 16777215))
self.lRoadName.setObjectName(_fromUtf8("lRoadName"))
self.gridLayout_15.addWidget(self.lRoadName, 14, 0, 1, 1)
self.uAddressType = QtGui.QComboBox(self.gridLayoutWidget_8)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.uAddressType.sizePolicy().hasHeightForWidth())
self.uAddressType.setSizePolicy(sizePolicy)
self.uAddressType.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToMinimumContentsLength)
self.uAddressType.setObjectName(_fromUtf8("uAddressType"))
self.gridLayout_15.addWidget(self.uAddressType, 0, 1, 1, 1)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.uRclId = QtGui.QLineEdit(self.gridLayoutWidget_8)
self.uRclId.setReadOnly(True)
self.uRclId.setObjectName(_fromUtf8("uRclId"))
self.horizontalLayout.addWidget(self.uRclId)
self.uGetRclToolButton = QtGui.QToolButton(self.gridLayoutWidget_8)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.uGetRclToolButton.sizePolicy().hasHeightForWidth())
self.uGetRclToolButton.setSizePolicy(sizePolicy)
self.uGetRclToolButton.setMinimumSize(QtCore.QSize(0, 0))
self.uGetRclToolButton.setMaximumSize(QtCore.QSize(24, 16777215))
self.uGetRclToolButton.setText(_fromUtf8(""))
self.uGetRclToolButton.setObjectName(_fromUtf8("uGetRclToolButton"))
self.horizontalLayout.addWidget(self.uGetRclToolButton)
self.gridLayout_15.addLayout(self.horizontalLayout, 12, 1, 1, 1)
self.uExternalAddId = QtGui.QLineEdit(self.gridLayoutWidget_8)
self.uExternalAddId.setMaxLength(15)
self.uExternalAddId.setObjectName(_fromUtf8("uExternalAddId"))
self.gridLayout_15.addWidget(self.uExternalAddId, 11, 1, 1, 1)
self.lExtAddIdScheme = QtGui.QLabel(self.gridLayoutWidget_8)
self.lExtAddIdScheme.setObjectName(_fromUtf8("lExtAddIdScheme"))
self.gridLayout_15.addWidget(self.lExtAddIdScheme, 10, 0, 1, 1)
self.uExternalAddressIdScheme = QtGui.QLineEdit(self.gridLayoutWidget_8)
self.uExternalAddressIdScheme.setText(_fromUtf8(""))
self.uExternalAddressIdScheme.setObjectName(_fromUtf8("uExternalAddressIdScheme"))
self.gridLayout_15.addWidget(self.uExternalAddressIdScheme, 10, 1, 1, 1)
self.lExtAddId = QtGui.QLabel(self.gridLayoutWidget_8)
self.lExtAddId.setObjectName(_fromUtf8("lExtAddId"))
self.gridLayout_15.addWidget(self.lExtAddId, 11, 0, 1, 1)
self.uRoadTypeName = QtGui.QLineEdit(self.gridLayoutWidget_8)
self.uRoadTypeName.setText(_fromUtf8(""))
self.uRoadTypeName.setReadOnly(True)
self.uRoadTypeName.setObjectName(_fromUtf8("uRoadTypeName"))
self.gridLayout_15.addWidget(self.uRoadTypeName, 15, 1, 1, 1)
self.uWaterName = QtGui.QLineEdit(self.gridLayoutWidget_8)
self.uWaterName.setText(_fromUtf8(""))
self.uWaterName.setReadOnly(True)
self.uWaterName.setObjectName(_fromUtf8("uWaterName"))
self.gridLayout_15.addWidget(self.uWaterName, 18, 1, 1, 1)
self.ulifeCycle = QtGui.QComboBox(self.gridLayoutWidget_8)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.ulifeCycle.sizePolicy().hasHeightForWidth())
self.ulifeCycle.setSizePolicy(sizePolicy)
self.ulifeCycle.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToMinimumContentsLength)
self.ulifeCycle.setObjectName(_fromUtf8("ulifeCycle"))
self.gridLayout_15.addWidget(self.ulifeCycle, 1, 1, 1, 1)
self.lLifeCycle = QtGui.QLabel(self.gridLayoutWidget_8)
self.lLifeCycle.setObjectName(_fromUtf8("lLifeCycle"))
self.gridLayout_15.addWidget(self.lLifeCycle, 1, 0, 1, 1)
self.lUnitType = QtGui.QLabel(self.gridLayoutWidget_8)
self.lUnitType.setMaximumSize(QtCore.QSize(175, 16777215))
self.lUnitType.setObjectName(_fromUtf8("lUnitType"))
self.gridLayout_15.addWidget(self.lUnitType, 4, 0, 1, 1)
self.verticalLayout_2.addWidget(self.splitter)
self.line = QtGui.QFrame(self.scrollAreaWidgetContents)
self.line.setFrameShape(QtGui.QFrame.HLine)
self.line.setFrameShadow(QtGui.QFrame.Sunken)
self.line.setObjectName(_fromUtf8("line"))
self.verticalLayout_2.addWidget(self.line)
self.label_121 = QtGui.QLabel(self.scrollAreaWidgetContents)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_121.sizePolicy().hasHeightForWidth())
self.label_121.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_121.setFont(font)
self.label_121.setObjectName(_fromUtf8("label_121"))
self.verticalLayout_2.addWidget(self.label_121)
spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem)
self.gridLayout_13 = QtGui.QGridLayout()
self.gridLayout_13.setSizeConstraint(QtGui.QLayout.SetNoConstraint)
self.gridLayout_13.setObjectName(_fromUtf8("gridLayout_13"))
self.lPositionType = QtGui.QLabel(self.scrollAreaWidgetContents)
self.lPositionType.setObjectName(_fromUtf8("lPositionType"))
self.gridLayout_13.addWidget(self.lPositionType, 2, 0, 1, 1)
self.uObjectType = QtGui.QComboBox(self.scrollAreaWidgetContents)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.uObjectType.sizePolicy().hasHeightForWidth())
self.uObjectType.setSizePolicy(sizePolicy)
self.uObjectType.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToMinimumContentsLength)
self.uObjectType.setObjectName(_fromUtf8("uObjectType"))
self.gridLayout_13.addWidget(self.uObjectType, 0, 1, 1, 1)
self.uObjectName = QtGui.QLineEdit(self.scrollAreaWidgetContents)
self.uObjectName.setText(_fromUtf8(""))
self.uObjectName.setObjectName(_fromUtf8("uObjectName"))
self.gridLayout_13.addWidget(self.uObjectName, 1, 1, 1, 1)
self.lExternalObjectId = QtGui.QLabel(self.scrollAreaWidgetContents)
self.lExternalObjectId.setObjectName(_fromUtf8("lExternalObjectId"))
self.gridLayout_13.addWidget(self.lExternalObjectId, 4, 0, 1, 1)
self.lExtObjectIdScheme = QtGui.QLabel(self.scrollAreaWidgetContents)
self.lExtObjectIdScheme.setObjectName(_fromUtf8("lExtObjectIdScheme"))
self.gridLayout_13.addWidget(self.lExtObjectIdScheme, 3, 0, 1, 1)
self.lMblk = QtGui.QLabel(self.scrollAreaWidgetContents)
self.lMblk.setObjectName(_fromUtf8("lMblk"))
self.gridLayout_13.addWidget(self.lMblk, 8, 0, 1, 1)
self.uAppellation = QtGui.QLineEdit(self.scrollAreaWidgetContents)
self.uAppellation.setText(_fromUtf8(""))
self.uAppellation.setObjectName(_fromUtf8("uAppellation"))
self.gridLayout_13.addWidget(self.uAppellation, 7, 1, 1, 1)
self.lAppellation = QtGui.QLabel(self.scrollAreaWidgetContents)
self.lAppellation.setObjectName(_fromUtf8("lAppellation"))
self.gridLayout_13.addWidget(self.lAppellation, 7, 0, 1, 1)
self.lValref = QtGui.QLabel(self.scrollAreaWidgetContents)
self.lValref.setObjectName(_fromUtf8("lValref"))
self.gridLayout_13.addWidget(self.lValref, 5, 0, 1, 1)
self.uExtObjectIdScheme = QtGui.QLineEdit(self.scrollAreaWidgetContents)
self.uExtObjectIdScheme.setObjectName(_fromUtf8("uExtObjectIdScheme"))
self.gridLayout_13.addWidget(self.uExtObjectIdScheme, 3, 1, 1, 1)
self.lCertTitle = QtGui.QLabel(self.scrollAreaWidgetContents)
self.lCertTitle.setObjectName(_fromUtf8("lCertTitle"))
self.gridLayout_13.addWidget(self.lCertTitle, 6, 0, 1, 1)
self.uExternalObjectId = QtGui.QLineEdit(self.scrollAreaWidgetContents)
self.uExternalObjectId.setText(_fromUtf8(""))
self.uExternalObjectId.setObjectName(_fromUtf8("uExternalObjectId"))
self.gridLayout_13.addWidget(self.uExternalObjectId, 4, 1, 1, 1)
self.uValuationReference = QtGui.QLineEdit(self.scrollAreaWidgetContents)
self.uValuationReference.setText(_fromUtf8(""))
self.uValuationReference.setObjectName(_fromUtf8("uValuationReference"))
self.gridLayout_13.addWidget(self.uValuationReference, 5, 1, 1, 1)
self.lObjType = QtGui.QLabel(self.scrollAreaWidgetContents)
self.lObjType.setMinimumSize(QtCore.QSize(130, 0))
self.lObjType.setObjectName(_fromUtf8("lObjType"))
self.gridLayout_13.addWidget(self.lObjType, 0, 0, 1, 1)
self.uMblkOverride = QtGui.QLineEdit(self.scrollAreaWidgetContents)
self.uMblkOverride.setMaxLength(7)
self.uMblkOverride.setObjectName(_fromUtf8("uMblkOverride"))
self.gridLayout_13.addWidget(self.uMblkOverride, 8, 1, 1, 1)
self.uCertificateOfTitle = QtGui.QLineEdit(self.scrollAreaWidgetContents)
self.uCertificateOfTitle.setText(_fromUtf8(""))
self.uCertificateOfTitle.setObjectName(_fromUtf8("uCertificateOfTitle"))
self.gridLayout_13.addWidget(self.uCertificateOfTitle, 6, 1, 1, 1)
self.lObjName = QtGui.QLabel(self.scrollAreaWidgetContents)
self.lObjName.setObjectName(_fromUtf8("lObjName"))
self.gridLayout_13.addWidget(self.lObjName, 1, 0, 1, 1)
self.horizontalLayout_3 = QtGui.QHBoxLayout()
self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
self.uPositionType = QtGui.QComboBox(self.scrollAreaWidgetContents)
self.uPositionType.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToMinimumContentsLength)
self.uPositionType.setObjectName(_fromUtf8("uPositionType"))
self.horizontalLayout_3.addWidget(self.uPositionType)
self.uUpdatePosButton = QtGui.QPushButton(self.scrollAreaWidgetContents)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.uUpdatePosButton.sizePolicy().hasHeightForWidth())
self.uUpdatePosButton.setSizePolicy(sizePolicy)
self.uUpdatePosButton.setMinimumSize(QtCore.QSize(24, 0))
self.uUpdatePosButton.setMaximumSize(QtCore.QSize(24, 16777215))
self.uUpdatePosButton.setText(_fromUtf8(""))
self.uUpdatePosButton.setObjectName(_fromUtf8("uUpdatePosButton"))
self.horizontalLayout_3.addWidget(self.uUpdatePosButton)
self.gridLayout_13.addLayout(self.horizontalLayout_3, 2, 1, 1, 1)
self.verticalLayout_2.addLayout(self.gridLayout_13)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.verticalLayout.addWidget(self.scrollArea)
self.retranslateUi(QueueEditorWidget)
QtCore.QMetaObject.connectSlotsByName(QueueEditorWidget)
QueueEditorWidget.setTabOrder(self.uAddressType, self.ulifeCycle)
QueueEditorWidget.setTabOrder(self.ulifeCycle, self.uLevelType)
QueueEditorWidget.setTabOrder(self.uLevelType, self.uLevelValue)
QueueEditorWidget.setTabOrder(self.uLevelValue, self.uUnitType)
QueueEditorWidget.setTabOrder(self.uUnitType, self.uUnit)
QueueEditorWidget.setTabOrder(self.uUnit, self.uPrefix)
QueueEditorWidget.setTabOrder(self.uPrefix, self.uBase)
QueueEditorWidget.setTabOrder(self.uBase, self.uAlpha)
QueueEditorWidget.setTabOrder(self.uAlpha, self.uHigh)
QueueEditorWidget.setTabOrder(self.uHigh, self.uExternalAddressIdScheme)
QueueEditorWidget.setTabOrder(self.uExternalAddressIdScheme, self.uExternalAddId)
QueueEditorWidget.setTabOrder(self.uExternalAddId, self.uRclId)
QueueEditorWidget.setTabOrder(self.uRclId, self.uRoadPrefix)
QueueEditorWidget.setTabOrder(self.uRoadPrefix, self.uRoadName)
QueueEditorWidget.setTabOrder(self.uRoadName, self.uRoadTypeName)
QueueEditorWidget.setTabOrder(self.uRoadTypeName, self.uRoadSuffix)
QueueEditorWidget.setTabOrder(self.uRoadSuffix, self.uWaterRouteName)
QueueEditorWidget.setTabOrder(self.uWaterRouteName, self.uWaterName)
QueueEditorWidget.setTabOrder(self.uWaterName, self.uObjectType)
QueueEditorWidget.setTabOrder(self.uObjectType, self.uObjectName)
QueueEditorWidget.setTabOrder(self.uObjectName, self.uExtObjectIdScheme)
QueueEditorWidget.setTabOrder(self.uExtObjectIdScheme, self.uExternalObjectId)
QueueEditorWidget.setTabOrder(self.uExternalObjectId, self.uValuationReference)
QueueEditorWidget.setTabOrder(self.uValuationReference, self.uCertificateOfTitle)
QueueEditorWidget.setTabOrder(self.uCertificateOfTitle, self.uAppellation)
QueueEditorWidget.setTabOrder(self.uAppellation, self.uMblkOverride)
QueueEditorWidget.setTabOrder(self.uMblkOverride, self.uGetRclToolButton)
QueueEditorWidget.setTabOrder(self.uGetRclToolButton, self.scrollArea_2)
QueueEditorWidget.setTabOrder(self.scrollArea_2, self.scrollArea)
QueueEditorWidget.setTabOrder(self.scrollArea, self.scrollArea_4)
def retranslateUi(self, QueueEditorWidget):
QueueEditorWidget.setWindowTitle(_translate("QueueEditorWidget", "Form", None))
self.lNotes.setText(_translate("QueueEditorWidget", "Source Notes:", None))
self.lWarning.setText(_translate("QueueEditorWidget", "Warnings:", None))
self.lWaterRoute.setText(_translate("QueueEditorWidget", "Water Route:", None))
self.lNumberPrefix.setText(_translate("QueueEditorWidget", "Number Prefix:", None))
self.lLevelType.setText(_translate("QueueEditorWidget", "Level Type:", None))
self.lBaseNumber.setText(_translate("QueueEditorWidget", "Base Number:", None))
self.lNumberHigh.setText(_translate("QueueEditorWidget", "Number High:", None))
self.lLevelValue.setText(_translate("QueueEditorWidget", "Level Value:", None))
self.lAddressType.setText(_translate("QueueEditorWidget", "Address Type:", None))
self.lRoadType.setText(_translate("QueueEditorWidget", "Road Type:", None))
self.lRoadPrefix.setText(_translate("QueueEditorWidget", "Road Prefix:", None))
self.lAplha.setText(_translate("QueueEditorWidget", "Alpha:", None))
self.lUnitValue.setText(_translate("QueueEditorWidget", "Unit Value:", None))
self.lWaterName.setText(_translate("QueueEditorWidget", "Water Name:", None))
self.lRclId.setText(_translate("QueueEditorWidget", "RCL Id:", None))
self.lRoadSuffix.setText(_translate("QueueEditorWidget", "Road Suffix:", None))
self.lRoadName.setText(_translate("QueueEditorWidget", "Road Name:", None))
self.lExtAddIdScheme.setText(_translate("QueueEditorWidget", "Ext. Add Id Scheme:", None))
self.lExtAddId.setText(_translate("QueueEditorWidget", "Ext. Add Id:", None))
self.lLifeCycle.setText(_translate("QueueEditorWidget", "Lifecycle:", None))
self.lUnitType.setText(_translate("QueueEditorWidget", "Unit Type:", None))
self.label_121.setText(_translate("QueueEditorWidget", "Addressable Object:", None))
self.lPositionType.setText(_translate("QueueEditorWidget", "Position Type:", None))
self.lExternalObjectId.setText(_translate("QueueEditorWidget", "Ext. Obj Id:", None))
self.lExtObjectIdScheme.setText(_translate("QueueEditorWidget", "Ext. Obj Id Scheme:", None))
self.lMblk.setText(_translate("QueueEditorWidget", "Mblk Override:", None))
self.lAppellation.setText(_translate("QueueEditorWidget", "Appellation:", None))
self.lValref.setText(_translate("QueueEditorWidget", "Val Ref:", None))
self.lCertTitle.setText(_translate("QueueEditorWidget", "Cert. of Title:", None))
self.lObjType.setText(_translate("QueueEditorWidget", "Object Type:", None))
self.lObjName.setText(_translate("QueueEditorWidget", "Object Name:", None))
| bsd-3-clause | 467,091,103,275,577,150 | 63.227898 | 102 | 0.726172 | false |
Qalthos/ansible | lib/ansible/modules/cloud/azure/azure_rm_resource_facts.py | 14 | 7926 | #!/usr/bin/python
#
# Copyright (c) 2018 Zim Kalinowski, <[email protected]>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: azure_rm_resource_facts
version_added: "2.6"
short_description: Generic facts of Azure resources.
description:
- Obtain facts of any resource using Azure REST API.
- This module gives access to resources that are not supported via Ansible modules.
- Refer to https://docs.microsoft.com/en-us/rest/api/ regarding details related to specific resource REST API.
options:
url:
description:
- Azure RM Resource URL.
api_version:
description:
- Specific API version to be used.
provider:
description:
- Provider type, should be specified in no URL is given
resource_group:
description:
- Resource group to be used.
- Required if URL is not specified.
resource_type:
description:
- Resource type.
resource_name:
description:
- Resource name.
subresource:
description:
- List of subresources
suboptions:
namespace:
description:
- Subresource namespace
type:
description:
- Subresource type
name:
description:
- Subresource name
extends_documentation_fragment:
- azure
author:
- "Zim Kalinowski (@zikalino)"
'''
EXAMPLES = '''
- name: Get scaleset info
azure_rm_resource_facts:
resource_group: myResourceGroup
provider: compute
resource_type: virtualmachinescalesets
resource_name: myVmss
api_version: "2017-12-01"
- name: Query all the resources in the resource group
azure_rm_resource_facts:
resource_group: "{{ resource_group }}"
resource_type: resources
'''
RETURN = '''
response:
description: Response specific to resource type.
returned: always
type: dict
'''
from ansible.module_utils.azure_rm_common import AzureRMModuleBase
from ansible.module_utils.azure_rm_common_rest import GenericRestClient
try:
from msrestazure.azure_exceptions import CloudError
from msrest.service_client import ServiceClient
from msrestazure.tools import resource_id, is_valid_resource_id
import json
except ImportError:
# This is handled in azure_rm_common
pass
class AzureRMResourceFacts(AzureRMModuleBase):
def __init__(self):
# define user inputs into argument
self.module_arg_spec = dict(
url=dict(
type='str'
),
provider=dict(
type='str'
),
resource_group=dict(
type='str'
),
resource_type=dict(
type='str'
),
resource_name=dict(
type='str'
),
subresource=dict(
type='list',
default=[]
),
api_version=dict(
type='str'
)
)
# store the results of the module operation
self.results = dict(
response=[]
)
self.mgmt_client = None
self.url = None
self.api_version = None
self.provider = None
self.resource_group = None
self.resource_type = None
self.resource_name = None
self.subresource = []
super(AzureRMResourceFacts, self).__init__(self.module_arg_spec, supports_tags=False)
def exec_module(self, **kwargs):
for key in self.module_arg_spec:
setattr(self, key, kwargs[key])
self.mgmt_client = self.get_mgmt_svc_client(GenericRestClient,
base_url=self._cloud_environment.endpoints.resource_manager)
if self.url is None:
orphan = None
rargs = dict()
rargs['subscription'] = self.subscription_id
rargs['resource_group'] = self.resource_group
if not (self.provider is None or self.provider.lower().startswith('.microsoft')):
rargs['namespace'] = "Microsoft." + self.provider
else:
rargs['namespace'] = self.provider
if self.resource_type is not None and self.resource_name is not None:
rargs['type'] = self.resource_type
rargs['name'] = self.resource_name
for i in range(len(self.subresource)):
resource_ns = self.subresource[i].get('namespace', None)
resource_type = self.subresource[i].get('type', None)
resource_name = self.subresource[i].get('name', None)
if resource_type is not None and resource_name is not None:
rargs['child_namespace_' + str(i + 1)] = resource_ns
rargs['child_type_' + str(i + 1)] = resource_type
rargs['child_name_' + str(i + 1)] = resource_name
else:
orphan = resource_type
else:
orphan = self.resource_type
self.url = resource_id(**rargs)
if orphan is not None:
self.url += '/' + orphan
# if api_version was not specified, get latest one
if not self.api_version:
try:
# extract provider and resource type
if "/providers/" in self.url:
provider = self.url.split("/providers/")[1].split("/")[0]
resourceType = self.url.split(provider + "/")[1].split("/")[0]
url = "/subscriptions/" + self.subscription_id + "/providers/" + provider
api_versions = json.loads(self.mgmt_client.query(url, "GET", {'api-version': '2015-01-01'}, None, None, [200], 0, 0).text)
for rt in api_versions['resourceTypes']:
if rt['resourceType'].lower() == resourceType.lower():
self.api_version = rt['apiVersions'][0]
break
else:
# if there's no provider in API version, assume Microsoft.Resources
self.api_version = '2018-05-01'
if not self.api_version:
self.fail("Couldn't find api version for {0}/{1}".format(provider, resourceType))
except Exception as exc:
self.fail("Failed to obtain API version: {0}".format(str(exc)))
self.results['url'] = self.url
query_parameters = {}
query_parameters['api-version'] = self.api_version
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
skiptoken = None
while True:
if skiptoken:
query_parameters['skiptoken'] = skiptoken
response = self.mgmt_client.query(self.url, "GET", query_parameters, header_parameters, None, [200, 404], 0, 0)
try:
response = json.loads(response.text)
if isinstance(response, dict):
if response.get('value'):
self.results['response'] = self.results['response'] + response['value']
skiptoken = response.get('nextLink')
else:
self.results['response'] = self.results['response'] + [response]
except Exception as e:
self.fail('Failed to parse response: ' + str(e))
if not skiptoken:
break
return self.results
def main():
AzureRMResourceFacts()
if __name__ == '__main__':
main()
| gpl-3.0 | -113,347,264,151,722,940 | 32.584746 | 142 | 0.556901 | false |
huntxu/neutron | neutron/agent/metadata/driver.py | 1 | 12383 | # Copyright 2014 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import errno
import grp
import os
import pwd
from neutron_lib.callbacks import events
from neutron_lib.callbacks import registry
from neutron_lib.callbacks import resources
from oslo_config import cfg
from oslo_log import log as logging
from neutron._i18n import _
from neutron.agent.l3 import ha_router
from neutron.agent.l3 import namespaces
from neutron.agent.linux import external_process
from neutron.common import constants
from neutron.common import exceptions
LOG = logging.getLogger(__name__)
METADATA_SERVICE_NAME = 'metadata-proxy'
PROXY_CONFIG_DIR = "ns-metadata-proxy"
_HAPROXY_CONFIG_TEMPLATE = """
global
log /dev/log local0 %(log_level)s
log-tag %(log_tag)s
user %(user)s
group %(group)s
maxconn 1024
pidfile %(pidfile)s
daemon
defaults
log global
mode http
option httplog
option dontlognull
option http-server-close
option forwardfor
retries 3
timeout http-request 30s
timeout connect 30s
timeout client 32s
timeout server 32s
timeout http-keep-alive 30s
listen listener
bind 0.0.0.0:%(port)s
server metadata %(unix_socket_path)s
http-request add-header X-Neutron-%(res_type)s-ID %(res_id)s
"""
class InvalidUserOrGroupException(Exception):
pass
class HaproxyConfigurator(object):
def __init__(self, network_id, router_id, unix_socket_path, port, user,
group, state_path, pid_file):
self.network_id = network_id
self.router_id = router_id
if network_id is None and router_id is None:
raise exceptions.NetworkIdOrRouterIdRequiredError()
self.port = port
self.user = user
self.group = group
self.state_path = state_path
self.unix_socket_path = unix_socket_path
self.pidfile = pid_file
self.log_level = (
'debug' if logging.is_debug_enabled(cfg.CONF) else 'info')
# log-tag will cause entries to have the string pre-pended, so use
# the uuid haproxy will be started with. Additionally, if it
# starts with "haproxy" then things will get logged to
# /var/log/haproxy.log on Debian distros, instead of to syslog.
uuid = network_id or router_id
self.log_tag = "haproxy-" + METADATA_SERVICE_NAME + "-" + uuid
def create_config_file(self):
"""Create the config file for haproxy."""
# Need to convert uid/gid into username/group
try:
username = pwd.getpwuid(int(self.user)).pw_name
except (ValueError, KeyError):
try:
username = pwd.getpwnam(self.user).pw_name
except KeyError:
raise InvalidUserOrGroupException(
_("Invalid user/uid: '%s'") % self.user)
try:
groupname = grp.getgrgid(int(self.group)).gr_name
except (ValueError, KeyError):
try:
groupname = grp.getgrnam(self.group).gr_name
except KeyError:
raise InvalidUserOrGroupException(
_("Invalid group/gid: '%s'") % self.group)
cfg_info = {
'port': self.port,
'unix_socket_path': self.unix_socket_path,
'user': username,
'group': groupname,
'pidfile': self.pidfile,
'log_level': self.log_level,
'log_tag': self.log_tag
}
if self.network_id:
cfg_info['res_type'] = 'Network'
cfg_info['res_id'] = self.network_id
else:
cfg_info['res_type'] = 'Router'
cfg_info['res_id'] = self.router_id
haproxy_cfg = _HAPROXY_CONFIG_TEMPLATE % cfg_info
LOG.debug("haproxy_cfg = %s", haproxy_cfg)
cfg_dir = self.get_config_path(self.state_path)
# uuid has to be included somewhere in the command line so that it can
# be tracked by process_monitor.
self.cfg_path = os.path.join(cfg_dir, "%s.conf" % cfg_info['res_id'])
if not os.path.exists(cfg_dir):
os.makedirs(cfg_dir)
with open(self.cfg_path, "w") as cfg_file:
cfg_file.write(haproxy_cfg)
@staticmethod
def get_config_path(state_path):
return os.path.join(state_path or cfg.CONF.state_path,
PROXY_CONFIG_DIR)
@staticmethod
def cleanup_config_file(uuid, state_path):
"""Delete config file created when metadata proxy was spawned."""
# Delete config file if it exists
cfg_path = os.path.join(
HaproxyConfigurator.get_config_path(state_path),
"%s.conf" % uuid)
try:
os.unlink(cfg_path)
except OSError as ex:
# It can happen that this function is called but metadata proxy
# was never spawned so its config file won't exist
if ex.errno != errno.ENOENT:
raise
class MetadataDriver(object):
monitors = {}
def __init__(self, l3_agent):
self.metadata_port = l3_agent.conf.metadata_port
self.metadata_access_mark = l3_agent.conf.metadata_access_mark
registry.subscribe(
after_router_added, resources.ROUTER, events.AFTER_CREATE)
registry.subscribe(
after_router_updated, resources.ROUTER, events.AFTER_UPDATE)
registry.subscribe(
before_router_removed, resources.ROUTER, events.BEFORE_DELETE)
@classmethod
def metadata_filter_rules(cls, port, mark):
return [('INPUT', '-m mark --mark %s/%s -j ACCEPT' %
(mark, constants.ROUTER_MARK_MASK)),
('INPUT', '-p tcp -m tcp --dport %s '
'-j DROP' % port)]
@classmethod
def metadata_nat_rules(cls, port):
return [('PREROUTING', '-d 169.254.169.254/32 '
'-i %(interface_name)s '
'-p tcp -m tcp --dport 80 -j REDIRECT '
'--to-ports %(port)s' %
{'interface_name': namespaces.INTERNAL_DEV_PREFIX + '+',
'port': port})]
@classmethod
def metadata_checksum_rules(cls, port):
return [('POSTROUTING', '-o %(interface_name)s '
'-p tcp -m tcp --sport %(port)s -j CHECKSUM '
'--checksum-fill' %
{'interface_name': namespaces.INTERNAL_DEV_PREFIX + '+',
'port': port})]
@classmethod
def _get_metadata_proxy_user_group(cls, conf):
user = conf.metadata_proxy_user or str(os.geteuid())
group = conf.metadata_proxy_group or str(os.getegid())
return user, group
@classmethod
def _get_metadata_proxy_callback(cls, port, conf, network_id=None,
router_id=None):
def callback(pid_file):
metadata_proxy_socket = conf.metadata_proxy_socket
user, group = (
cls._get_metadata_proxy_user_group(conf))
haproxy = HaproxyConfigurator(network_id,
router_id,
metadata_proxy_socket,
port,
user,
group,
conf.state_path,
pid_file)
haproxy.create_config_file()
proxy_cmd = ['haproxy',
'-f', haproxy.cfg_path]
return proxy_cmd
return callback
@classmethod
def spawn_monitored_metadata_proxy(cls, monitor, ns_name, port, conf,
network_id=None, router_id=None):
uuid = network_id or router_id
callback = cls._get_metadata_proxy_callback(
port, conf, network_id=network_id, router_id=router_id)
pm = cls._get_metadata_proxy_process_manager(uuid, conf,
ns_name=ns_name,
callback=callback)
# TODO(dalvarez): Remove in Q cycle. This will kill running instances
# of old ns-metadata-proxy Python version in order to be replaced by
# haproxy. This will help with upgrading and shall be removed in next
# cycle.
cls._migrate_python_ns_metadata_proxy_if_needed(pm)
pm.enable()
monitor.register(uuid, METADATA_SERVICE_NAME, pm)
cls.monitors[router_id] = pm
@staticmethod
def _migrate_python_ns_metadata_proxy_if_needed(pm):
"""Kill running Python version of ns-metadata-proxy.
This function will detect if the current metadata proxy process is
running the old Python version and kill it so that the new haproxy
version is spawned instead.
"""
# Read cmdline to a local var to avoid reading twice from /proc file
cmdline = pm.cmdline
if cmdline and 'haproxy' not in cmdline:
LOG.debug("Migrating old instance of python ns-metadata proxy to "
"new one based on haproxy (%s)", cmdline)
pm.disable()
@classmethod
def destroy_monitored_metadata_proxy(cls, monitor, uuid, conf, ns_name):
monitor.unregister(uuid, METADATA_SERVICE_NAME)
pm = cls._get_metadata_proxy_process_manager(uuid, conf,
ns_name=ns_name)
pm.disable()
# Delete metadata proxy config file
HaproxyConfigurator.cleanup_config_file(uuid, cfg.CONF.state_path)
cls.monitors.pop(uuid, None)
@classmethod
def _get_metadata_proxy_process_manager(cls, router_id, conf, ns_name=None,
callback=None):
return external_process.ProcessManager(
conf=conf,
uuid=router_id,
namespace=ns_name,
default_cmd_callback=callback)
def after_router_added(resource, event, l3_agent, **kwargs):
router = kwargs['router']
proxy = l3_agent.metadata_driver
for c, r in proxy.metadata_filter_rules(proxy.metadata_port,
proxy.metadata_access_mark):
router.iptables_manager.ipv4['filter'].add_rule(c, r)
for c, r in proxy.metadata_nat_rules(proxy.metadata_port):
router.iptables_manager.ipv4['nat'].add_rule(c, r)
for c, r in proxy.metadata_checksum_rules(proxy.metadata_port):
router.iptables_manager.ipv4['mangle'].add_rule(c, r)
router.iptables_manager.apply()
if not isinstance(router, ha_router.HaRouter):
proxy.spawn_monitored_metadata_proxy(
l3_agent.process_monitor,
router.ns_name,
proxy.metadata_port,
l3_agent.conf,
router_id=router.router_id)
def after_router_updated(resource, event, l3_agent, **kwargs):
router = kwargs['router']
proxy = l3_agent.metadata_driver
if (not proxy.monitors.get(router.router_id) and
not isinstance(router, ha_router.HaRouter)):
proxy.spawn_monitored_metadata_proxy(
l3_agent.process_monitor,
router.ns_name,
proxy.metadata_port,
l3_agent.conf,
router_id=router.router_id)
def before_router_removed(resource, event, l3_agent, payload=None):
router = payload.latest_state
proxy = l3_agent.metadata_driver
proxy.destroy_monitored_metadata_proxy(l3_agent.process_monitor,
router.router['id'],
l3_agent.conf,
router.ns_name)
| apache-2.0 | -837,369,826,572,829,700 | 36.524242 | 79 | 0.579827 | false |
sbidoul/pip | src/pip/_internal/utils/packaging.py | 6 | 2900 | import logging
from email.message import Message
from email.parser import FeedParser
from typing import Optional, Tuple
from pip._vendor import pkg_resources
from pip._vendor.packaging import specifiers, version
from pip._vendor.pkg_resources import Distribution
from pip._internal.exceptions import NoneMetadataError
from pip._internal.utils.misc import display_path
logger = logging.getLogger(__name__)
def check_requires_python(requires_python, version_info):
# type: (Optional[str], Tuple[int, ...]) -> bool
"""
Check if the given Python version matches a "Requires-Python" specifier.
:param version_info: A 3-tuple of ints representing a Python
major-minor-micro version to check (e.g. `sys.version_info[:3]`).
:return: `True` if the given Python version satisfies the requirement.
Otherwise, return `False`.
:raises InvalidSpecifier: If `requires_python` has an invalid format.
"""
if requires_python is None:
# The package provides no information
return True
requires_python_specifier = specifiers.SpecifierSet(requires_python)
python_version = version.parse(".".join(map(str, version_info)))
return python_version in requires_python_specifier
def get_metadata(dist):
# type: (Distribution) -> Message
"""
:raises NoneMetadataError: if the distribution reports `has_metadata()`
True but `get_metadata()` returns None.
"""
metadata_name = "METADATA"
if isinstance(dist, pkg_resources.DistInfoDistribution) and dist.has_metadata(
metadata_name
):
metadata = dist.get_metadata(metadata_name)
elif dist.has_metadata("PKG-INFO"):
metadata_name = "PKG-INFO"
metadata = dist.get_metadata(metadata_name)
else:
logger.warning("No metadata found in %s", display_path(dist.location))
metadata = ""
if metadata is None:
raise NoneMetadataError(dist, metadata_name)
feed_parser = FeedParser()
# The following line errors out if with a "NoneType" TypeError if
# passed metadata=None.
feed_parser.feed(metadata)
return feed_parser.close()
def get_requires_python(dist):
# type: (pkg_resources.Distribution) -> Optional[str]
"""
Return the "Requires-Python" metadata for a distribution, or None
if not present.
"""
pkg_info_dict = get_metadata(dist)
requires_python = pkg_info_dict.get("Requires-Python")
if requires_python is not None:
# Convert to a str to satisfy the type checker, since requires_python
# can be a Header object.
requires_python = str(requires_python)
return requires_python
def get_installer(dist):
# type: (Distribution) -> str
if dist.has_metadata("INSTALLER"):
for line in dist.get_metadata_lines("INSTALLER"):
if line.strip():
return line.strip()
return ""
| mit | 3,338,843,209,966,200,000 | 31.58427 | 82 | 0.682414 | false |
ydkhatri/mac_apt | plugins/helpers/ccl_bplist.py | 1 | 20731 | """
Copyright (c) 2012-2014, CCL Forensics
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 CCL Forensics 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 CCL FORENSICS 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.
Some modifications have been made to fix errors.- Yogesh Khatri
"""
import sys
import os
import struct
import datetime
__version__ = "0.16"
__description__ = "Converts Apple binary PList files into a native Python data structure"
__contact__ = "Alex Caithness"
_object_converter = None
def set_object_converter(function):
"""Sets the object converter function to be used when retrieving objects from the bplist.
default is None (which will return objects in their raw form).
A built in converter (ccl_bplist.NSKeyedArchiver_common_objects_convertor) which is geared
toward dealling with common types in NSKeyedArchiver is available which can simplify code greatly
when dealling with these types of files."""
if not hasattr(function, "__call__"):
raise TypeError("function is not a function")
global _object_converter
_object_converter = function
class BplistError(Exception):
pass
class BplistUID:
def __init__(self, value):
self.value = value
def __repr__(self):
return "UID: {0}".format(self.value)
def __str__(self):
return self.__repr__()
def __decode_multibyte_int_val(b):
if len(b) == 1:
fmt = ">B"
elif len(b) == 2:
fmt = ">H"
elif len(b) == 4:
fmt = ">I"
elif len(b) == 8:
fmt = ">q" # Always Signed?
elif len(b) == 16 and b[0:8] == b'\0\0\0\0\0\0\0\0':
fmt = '>Q'
b = b[8:]
else:
raise BplistError("Cannot decode multibyte int of length {0}".format(len(b)))
return struct.unpack(fmt, b)[0]
def __decode_multibyte_int(b, signed=True):
if len(b) == 1:
fmt = ">B" # Always unsigned?
elif len(b) == 2:
fmt = ">h"
elif len(b) == 3:
if signed:
return ((b[0] << 16) | struct.unpack(">H", b[1:])[0]) - ((b[0] >> 7) * 2 * 0x800000)
else:
return (b[0] << 16) | struct.unpack(">H", b[1:])[0]
elif len(b) == 4:
fmt = ">i"
elif len(b) == 8:
fmt = ">q"
else:
raise BplistError("Cannot decode multibyte int of length {0}".format(len(b)))
if signed and len(b) > 1:
return struct.unpack(fmt.lower(), b)[0]
else:
return struct.unpack(fmt.upper(), b)[0]
def __decode_float(b, signed=True):
if len(b) == 4:
fmt = ">f"
elif len(b) == 8:
fmt = ">d"
else:
raise BplistError("Cannot decode float of length {0}".format(len(b)))
if signed:
return struct.unpack(fmt.lower(), b)[0]
else:
return struct.unpack(fmt.upper(), b)[0]
def __decode_object(f, offset, collection_offset_size, offset_table):
# Move to offset and read type
#print("Decoding object at offset {0}".format(offset))
f.seek(offset)
# A little hack to keep the script portable between py2.x and py3k
if sys.version_info[0] < 3:
type_byte = ord(f.read(1)[0])
else:
type_byte = f.read(1)[0]
#print("Type byte: {0}".format(hex(type_byte)))
if type_byte == 0x00: # Null 0000 0000
return None
elif type_byte == 0x08: # False 0000 1000
return False
elif type_byte == 0x09: # True 0000 1001
return True
elif type_byte == 0x0F: # Fill 0000 1111
raise BplistError("Fill type not currently supported at offset {0}".format(f.tell())) # Not sure what to return really...
elif type_byte & 0xF0 == 0x10: # Int 0001 xxxx
int_length = 2 ** (type_byte & 0x0F)
int_bytes = f.read(int_length)
return __decode_multibyte_int_val(int_bytes)
elif type_byte & 0xF0 == 0x20: # Float 0010 nnnn
float_length = 2 ** (type_byte & 0x0F)
float_bytes = f.read(float_length)
return __decode_float(float_bytes)
elif type_byte & 0xFF == 0x33: # Date 0011 0011
date_bytes = f.read(8)
date_value = __decode_float(date_bytes)
try:
result = datetime.datetime(2001,1,1) + datetime.timedelta(seconds = date_value)
except OverflowError:
result = datetime.datetime.min
return result
elif type_byte & 0xF0 == 0x40: # Data 0100 nnnn
if type_byte & 0x0F != 0x0F:
# length in 4 lsb
data_length = type_byte & 0x0F
else:
# A little hack to keep the script portable between py2.x and py3k
if sys.version_info[0] < 3:
int_type_byte = ord(f.read(1)[0])
else:
int_type_byte = f.read(1)[0]
if int_type_byte & 0xF0 != 0x10:
raise BplistError("Long Data field definition not followed by int type at offset {0}".format(f.tell()))
int_length = 2 ** (int_type_byte & 0x0F)
int_bytes = f.read(int_length)
data_length = __decode_multibyte_int(int_bytes, False)
return f.read(data_length)
elif type_byte & 0xF0 == 0x50: # ASCII 0101 nnnn
if type_byte & 0x0F != 0x0F:
# length in 4 lsb
ascii_length = type_byte & 0x0F
else:
# A little hack to keep the script portable between py2.x and py3k
if sys.version_info[0] < 3:
int_type_byte = ord(f.read(1)[0])
else:
int_type_byte = f.read(1)[0]
if int_type_byte & 0xF0 != 0x10:
raise BplistError("Long ASCII field definition not followed by int type at offset {0}".format(f.tell()))
int_length = 2 ** (int_type_byte & 0x0F)
int_bytes = f.read(int_length)
ascii_length = __decode_multibyte_int(int_bytes, False)
return f.read(ascii_length).decode("ascii")
elif type_byte & 0xF0 == 0x60: # UTF-16 0110 nnnn
if type_byte & 0x0F != 0x0F:
# length in 4 lsb
utf16_length = (type_byte & 0x0F) * 2 # Length is characters - 16bit width
else:
# A little hack to keep the script portable between py2.x and py3k
if sys.version_info[0] < 3:
int_type_byte = ord(f.read(1)[0])
else:
int_type_byte = f.read(1)[0]
if int_type_byte & 0xF0 != 0x10:
raise BplistError("Long UTF-16 field definition not followed by int type at offset {0}".format(f.tell()))
int_length = 2 ** (int_type_byte & 0x0F)
int_bytes = f.read(int_length)
utf16_length = __decode_multibyte_int(int_bytes, False) * 2
return f.read(utf16_length).decode("utf_16_be")
elif type_byte & 0xF0 == 0x80: # UID 1000 nnnn
uid_length = (type_byte & 0x0F) + 1
uid_bytes = f.read(uid_length)
return BplistUID(__decode_multibyte_int(uid_bytes, signed=False))
elif type_byte & 0xF0 == 0xA0: # Array 1010 nnnn
if type_byte & 0x0F != 0x0F:
# length in 4 lsb
array_count = type_byte & 0x0F
else:
# A little hack to keep the script portable between py2.x and py3k
if sys.version_info[0] < 3:
int_type_byte = ord(f.read(1)[0])
else:
int_type_byte = f.read(1)[0]
if int_type_byte & 0xF0 != 0x10:
raise BplistError("Long Array field definition not followed by int type at offset {0}".format(f.tell()))
int_length = 2 ** (int_type_byte & 0x0F)
int_bytes = f.read(int_length)
array_count = __decode_multibyte_int(int_bytes, signed=False)
array_refs = []
for i in range(array_count):
array_refs.append(__decode_multibyte_int(f.read(collection_offset_size), False))
return [__decode_object(f, offset_table[obj_ref], collection_offset_size, offset_table) for obj_ref in array_refs]
elif type_byte & 0xF0 == 0xC0: # Set 1010 nnnn
if type_byte & 0x0F != 0x0F:
# length in 4 lsb
set_count = type_byte & 0x0F
else:
# A little hack to keep the script portable between py2.x and py3k
if sys.version_info[0] < 3:
int_type_byte = ord(f.read(1)[0])
else:
int_type_byte = f.read(1)[0]
if int_type_byte & 0xF0 != 0x10:
raise BplistError("Long Set field definition not followed by int type at offset {0}".format(f.tell()))
int_length = 2 ** (int_type_byte & 0x0F)
int_bytes = f.read(int_length)
set_count = __decode_multibyte_int(int_bytes, signed=False)
set_refs = []
for i in range(set_count):
set_refs.append(__decode_multibyte_int(f.read(collection_offset_size), False))
return [__decode_object(f, offset_table[obj_ref], collection_offset_size, offset_table) for obj_ref in set_refs]
elif type_byte & 0xF0 == 0xD0: # Dict 1011 nnnn
if type_byte & 0x0F != 0x0F:
# length in 4 lsb
dict_count = type_byte & 0x0F
else:
# A little hack to keep the script portable between py2.x and py3k
if sys.version_info[0] < 3:
int_type_byte = ord(f.read(1)[0])
else:
int_type_byte = f.read(1)[0]
#print("Dictionary length int byte: {0}".format(hex(int_type_byte)))
if int_type_byte & 0xF0 != 0x10:
raise BplistError("Long Dict field definition not followed by int type at offset {0}".format(f.tell()))
int_length = 2 ** (int_type_byte & 0x0F)
int_bytes = f.read(int_length)
dict_count = __decode_multibyte_int(int_bytes, signed=False)
key_refs = []
#print("Dictionary count: {0}".format(dict_count))
for i in range(dict_count):
key_refs.append(__decode_multibyte_int(f.read(collection_offset_size), False))
value_refs = []
for i in range(dict_count):
value_refs.append(__decode_multibyte_int(f.read(collection_offset_size), False))
dict_result = {}
for i in range(dict_count):
#print("Key ref: {0}\tVal ref: {1}".format(key_refs[i], value_refs[i]))
key = __decode_object(f, offset_table[key_refs[i]], collection_offset_size, offset_table)
val = __decode_object(f, offset_table[value_refs[i]], collection_offset_size, offset_table)
dict_result[key] = val
return dict_result
def load(f):
"""
Reads and converts a file-like object containing a binary property list.
Takes a file-like object (must support reading and seeking) as an argument
Returns a data structure representing the data in the property list
"""
# Check magic number
if f.read(8) != b"bplist00":
raise BplistError("Bad file header")
# Read trailer
f.seek(-32, os.SEEK_END)
trailer = f.read(32)
offset_int_size, collection_offset_size, object_count, top_level_object_index, offest_table_offset = struct.unpack(">6xbbQQQ", trailer)
# Read offset table
f.seek(offest_table_offset)
offset_table = []
for i in range(object_count):
offset_table.append(__decode_multibyte_int(f.read(offset_int_size), False))
return __decode_object(f, offset_table[top_level_object_index], collection_offset_size, offset_table)
def NSKeyedArchiver_common_objects_convertor(o):
"""Built in converter function (suitable for submission to set_object_converter()) which automatically
converts the following common data-types found in NSKeyedArchiver:
NSDictionary/NSMutableDictionary;
NSArray/NSMutableArray;
NSSet/NSMutableSet
NSString/NSMutableString
NSDate
$null strings"""
# Conversion: NSDictionary
if is_nsmutabledictionary(o):
return convert_NSMutableDictionary(o)
# Conversion: NSArray
elif is_nsarray(o):
return convert_NSArray(o)
elif is_isnsset(o):
return convert_NSSet(o)
# Conversion: NSString
elif is_nsstring(o):
return convert_NSString(o)
# Conversion: NSDate
elif is_nsdate(o):
return convert_NSDate(o)
# Conversion: "$null" string
elif isinstance(o, str) and o == "$null":
return None
# Fallback:
else:
return o
def NSKeyedArchiver_convert(o, object_table):
if isinstance(o, list):
#return NsKeyedArchiverList(o, object_table)
result = NsKeyedArchiverList(o, object_table)
elif isinstance(o, dict):
#return NsKeyedArchiverDictionary(o, object_table)
result = NsKeyedArchiverDictionary(o, object_table)
elif isinstance(o, BplistUID):
#return NSKeyedArchiver_convert(object_table[o.value], object_table)
result = NSKeyedArchiver_convert(object_table[o.value], object_table)
else:
#return o
result = o
if _object_converter:
return _object_converter(result)
else:
return result
class NsKeyedArchiverDictionary(dict):
def __init__(self, original_dict, object_table):
super(NsKeyedArchiverDictionary, self).__init__(original_dict)
self.object_table = object_table
def __getitem__(self, index):
o = super(NsKeyedArchiverDictionary, self).__getitem__(index)
return NSKeyedArchiver_convert(o, self.object_table)
def get(self, key, default=None):
return self[key] if key in self else default
class NsKeyedArchiverList(list):
def __init__(self, original_iterable, object_table):
super(NsKeyedArchiverList, self).__init__(original_iterable)
self.object_table = object_table
def __getitem__(self, index):
o = super(NsKeyedArchiverList, self).__getitem__(index)
return NSKeyedArchiver_convert(o, self.object_table)
def __iter__(self):
for o in super(NsKeyedArchiverList, self).__iter__():
yield NSKeyedArchiver_convert(o, self.object_table)
def deserialise_NsKeyedArchiver(obj, parse_whole_structure=False):
"""Deserialises an NSKeyedArchiver bplist rebuilding the structure.
obj should usually be the top-level object returned by the load()
function."""
# Check that this is an archiver and version we understand
if not isinstance(obj, dict):
raise TypeError("obj must be a dict")
if "$archiver" not in obj or obj["$archiver"] != "NSKeyedArchiver":
raise ValueError("obj does not contain an '$archiver' key or the '$archiver' is unrecognised")
if "$version" not in obj or obj["$version"] != 100000:
raise ValueError("obj does not contain a '$version' key or the '$version' is unrecognised")
object_table = obj["$objects"]
if "root" in obj["$top"] and not parse_whole_structure:
return NSKeyedArchiver_convert(obj["$top"]["root"], object_table)
else:
return NSKeyedArchiver_convert(obj["$top"], object_table)
# NSMutableDictionary convenience functions
def is_nsmutabledictionary(obj):
if not isinstance(obj, dict):
return False
if "$class" not in obj.keys():
return False
if obj["$class"].get("$classname") not in ("NSMutableDictionary", "NSDictionary"):
return False
if "NS.keys" not in obj.keys():
return False
if "NS.objects" not in obj.keys():
return False
return True
def convert_NSMutableDictionary(obj):
"""Converts a NSKeyedArchiver serialised NSMutableDictionary into
a straight dictionary (rather than two lists as it is serialised
as)"""
# The dictionary is serialised as two lists (one for keys and one
# for values) which obviously removes all convenience afforded by
# dictionaries. This function converts this structure to an
# actual dictionary so that values can be accessed by key.
if not is_nsmutabledictionary(obj):
raise ValueError("obj does not have the correct structure for a NSDictionary/NSMutableDictionary serialised to a NSKeyedArchiver")
keys = obj["NS.keys"]
vals = obj["NS.objects"]
# sense check the keys and values:
if not isinstance(keys, list):
raise TypeError("The 'NS.keys' value is an unexpected type (expected list; actual: {0}".format(type(keys)))
if not isinstance(vals, list):
raise TypeError("The 'NS.objects' value is an unexpected type (expected list; actual: {0}".format(type(vals)))
if len(keys) != len(vals):
raise ValueError("The length of the 'NS.keys' list ({0}) is not equal to that of the 'NS.objects ({1})".format(len(keys), len(vals)))
result = {}
for i,k in enumerate(keys):
try:
if k in result:
raise ValueError("The 'NS.keys' list contains duplicate entries")
result[k] = vals[i]
except (ValueError, TypeError) as ex:
# Sometimes k is a dict, just silently ignore the TypeError about not being able to hash..
print (ex)
return result
# NSArray convenience functions
def is_nsarray(obj):
if not isinstance(obj, dict):
return False
if "$class" not in obj.keys():
return False
if obj["$class"].get("$classname") not in ("NSArray", "NSMutableArray"):
return False
if "NS.objects" not in obj.keys():
return False
return True
def convert_NSArray(obj):
if not is_nsarray(obj):
raise ValueError("obj does not have the correct structure for a NSArray/NSMutableArray serialised to a NSKeyedArchiver")
return obj["NS.objects"]
# NSSet convenience functions
def is_isnsset(obj):
if not isinstance(obj, dict):
return False
if "$class" not in obj.keys():
return False
if obj["$class"].get("$classname") not in ("NSSet", "NSMutableSet"):
return False
if "NS.objects" not in obj.keys():
return False
return True
def convert_NSSet(obj):
if not is_isnsset(obj):
raise ValueError("obj does not have the correct structure for a NSSet/NSMutableSet serialised to a NSKeyedArchiver")
return list(obj["NS.objects"]) # set(obj["NS.objects"]) # Changed Set to List (YK)
# NSString convenience functions
def is_nsstring(obj):
if not isinstance(obj, dict):
return False
if "$class" not in obj.keys():
return False
if obj["$class"].get("$classname") not in ("NSString", "NSMutableString"):
return False
if "NS.string" not in obj.keys():
return False
return True
def convert_NSString(obj):
if not is_nsstring(obj):
raise ValueError("obj does not have the correct structure for a NSString/NSMutableString serialised to a NSKeyedArchiver")
return obj["NS.string"]
# NSDate convenience functions
def is_nsdate(obj):
if not isinstance(obj, dict):
return False
if "$class" not in obj.keys():
return False
if obj["$class"].get("$classname") not in ("NSDate"):
return False
if "NS.time" not in obj.keys():
return False
return True
def convert_NSDate(obj):
if not is_nsdate(obj):
raise ValueError("obj does not have the correct structure for a NSDate serialised to a NSKeyedArchiver")
try:
return datetime.datetime(2001, 1, 1) + datetime.timedelta(seconds=obj["NS.time"])
except (OverflowError, ValueError) as ex:
print(ex)
return None | mit | 692,396,399,724,710,300 | 39.023166 | 141 | 0.623607 | false |
p1c2u/k2 | profiles/migrations/0001_initial.py | 2 | 6853 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'UserProfile'
db.create_table('profiles_userprofile', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.OneToOneField')(related_name='profile', unique=True, to=orm['auth.User'])),
('gg', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True)),
('jabber', self.gf('k2.utils.django.db.models.fields.JabberField')(max_length=75, null=True, blank=True)),
('skype', self.gf('django.db.models.fields.CharField')(max_length=50, null=True, blank=True)),
('website', self.gf('django.db.models.fields.URLField')(max_length=200, null=True, blank=True)),
('about', self.gf('django.db.models.fields.TextField')(blank=True)),
('location', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
('avatar', self.gf('k2.utils.django.db.models.fields.files.ImageWithThumbsField')(default=None, max_length=100, null=True, blank=True, sizes=((16, 16), (48, 48), (64, 64)))),
('gender', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=0)),
('email_show', self.gf('django.db.models.fields.BooleanField')(default=False)),
('rank', self.gf('django.db.models.fields.PositiveIntegerField')(null=True)),
('karma_updated', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
('karma', self.gf('django.db.models.fields.IntegerField')(default=0, null=True)),
))
db.send_create_signal('profiles', ['UserProfile'])
def backwards(self, orm):
# Deleting model 'UserProfile'
db.delete_table('profiles_userprofile')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'profiles.userprofile': {
'Meta': {'object_name': 'UserProfile'},
'about': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'avatar': ('k2.utils.django.db.models.fields.files.ImageWithThumbsField', [], {'default': 'None', 'max_length': '100', 'null': 'True', 'blank': 'True', 'sizes': '((16, 16), (48, 48), (64, 64))'}),
'email_show': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'gender': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}),
'gg': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'jabber': ('k2.utils.django.db.models.fields.JabberField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}),
'karma': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True'}),
'karma_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'location': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'rank': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),
'skype': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'profile'", 'unique': 'True', 'to': "orm['auth.User']"}),
'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'})
}
}
complete_apps = ['profiles']
| gpl-2.0 | 709,852,805,476,221,700 | 72.688172 | 208 | 0.573471 | false |
OpenSourcePolicyCenter/webapp-public | webapp/apps/register/forms.py | 2 | 1891 | from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.core.mail import send_mail
from .models import Subscriber
class SubscribeForm(forms.ModelForm):
class Meta:
model = Subscriber
fields = ('email',)
widgets = {
'email': forms.EmailInput(
attrs={
'class': 'form-control',
'placeholder': 'Enter email to subscribe'})}
class MyRegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
def save(self, commit=True):
user = super(MyRegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
self.send_registration_confirm_email()
return user
def send_registration_confirm_email(self):
username = self.cleaned_data['username']
password = self.cleaned_data['password1']
email = self.cleaned_data['email']
send_mail(
subject=("Thank you for joining the conversation on American tax "
"policy"),
message="""Welcome!
Thank you for registering with ospc.org. This is the best way to stay
up to date on the latest news from the Open Source Policy Center. We
also invite you to try the TaxBrain webapp.
Username: {username}
Password: {password}
""".format(
username=username,
password=password),
from_email="Open Source Policy Center <[email protected]>",
recipient_list=[email])
class LoginForm(AuthenticationForm):
class Meta:
fields = ('username', 'password')
| mit | -1,846,669,447,826,067,700 | 29.5 | 78 | 0.60973 | false |
rajathkumarmp/BinPy | BinPy/examples/source/ic/Series_7400/IC7425.py | 5 | 1310 | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <headingcell level=2>
# Usage of IC 7425
# <codecell>
from __future__ import print_function
from BinPy import *
# <codecell>
# Usage of IC 7425:
ic = IC_7425()
print(ic.__doc__)
# <codecell>
# The Pin configuration is:
inp = {
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
7: 0,
9: 1,
10: 1,
11: 1,
12: 1,
13: 1,
14: 1}
# Pin initinalization
# Powering up the IC - using -- ic.setIC({14: 1, 7: 0})
ic.setIC({14: 1, 7: 0})
# Setting the inputs of the ic
ic.setIC(inp)
# Draw the IC with the current configuration\n
ic.drawIC()
# <codecell>
# Run the IC with the current configuration using -- print ic.run() --
# Note that the ic.run() returns a dict of pin configuration similar to
print (ic.run())
# <codecell>
# Seting the outputs to the current IC configuration using --
# ic.setIC(ic.run()) --\n
ic.setIC(ic.run())
# Draw the final configuration
ic.drawIC()
# <codecell>
# Seting the outputs to the current IC configuration using --
# ic.setIC(ic.run()) --
ic.setIC(ic.run())
# Draw the final configuration
ic.drawIC()
# Run the IC
print (ic.run())
# <codecell>
# Connector Outputs
c = Connector()
# Set the output connector to a particular pin of the ic
ic.setOutput(8, c)
print(c)
| bsd-3-clause | 4,339,075,906,525,357,000 | 12.789474 | 71 | 0.622137 | false |
OBIGOGIT/etch | binding-python/runtime/src/main/python/etch/binding/support/Validator_RuntimeException.py | 2 | 1676 | """
# 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 __future__ import absolute_import
import types
from ...python.Exceptions import *
from ...python.Types import *
from .TypeValidator import *
from ..transport.fmt.TypeCode import *
class Validator_RuntimeException(ScalarOnlyTypeValidator):
"""
Validator for RuntimeException
"""
def __init__(self):
self.description = "RuntimeException"
def elementValidator(self):
raise IllegalArgumentException, "Not an array"
def validate(self, value):
return isinstance(value, Exception)
def checkValue(self, value):
if self.validate(value):
return TypeCode.CUSTOM
return None
| apache-2.0 | 2,989,908,079,206,309,400 | 36.244444 | 65 | 0.628878 | false |
aocks/ox_herd | ox_herd/ui/flask_web_ui/ox_herd/web_tasks.py | 1 | 10743 | """Classes to help automate web tasks.
"""
import re
import logging
import urllib.parse
import requests
from ox_herd.core.plugins import base
from ox_herd.core import ox_tasks
class SimpleTaskResult:
"""Class to hold task result.
Clairfying the expected return values for a task makes it easier to display
and inspect task results with other tools.
"""
def __init__(self, return_value: str, full_text: str = None,
status_code: int = 0, reason: str = 'OK',
extras: dict = None):
"""Initializer.
:param return_value:str: String return value to display as task
status.
:param full_text:str: Full text of result/response. This is typically
the full response to an HTTP request. You can
provide '' if you want to save space. If you
provide None, then we use return_value.
:param status_code:int: Status code from an HTTP request. Use 0 if
was not an HTTP request.
:param reason:str='OK': String reason provided for HTTP response. Use
'NA' if not an HTTP response.
:param extras=None: Optional dict of additional data.
"""
self.return_value = return_value
self.full_text = full_text if full_text is not None else return_value
self.status_code = status_code
self.reason = reason
self.extras = extras if extras else {}
@classmethod
def fields(cls) -> list:
"""Return list of strings describing main fields in self.
Sub-classes can override if they want additional fields to showup
in to_dict.
"""
_ = cls
return ['return_value', 'full_text', 'status_code',
'reason', 'extras']
def to_dict(self) -> dict:
"Return dict with data in self.fields()"
return {n: getattr(self, n) for n in self.fields()}
class SimpleWebTask(ox_tasks.OxHerdTask, base.OxPluginComponent):
"""Generic command that can be sub-classed for automation.
"""
def __init__(self, *args, base_url=None, base_port='', **kwargs):
"""Initializer.
:arg base_url=None: String url for where your server lives (or
where the version you want to use lives).
"""
if not args and 'name' not in kwargs:
kwargs['name'] = self.__class__.__name__
ox_tasks.OxHerdTask.__init__(self, *args, **kwargs)
# Never use base_url/base_port directly. Instead call
# set_base_url and make_url so we handle ports correctly.
self.__base_url = ''
self.__base_port = None
self.set_base_url(base_url, base_port)
def set_base_url(self, base_url: str, base_port: str = None):
"""Set the base_url (and optinally base_port).
:param base_url: String like http://foo or http://bar:9999
:param base_port=None: Optional base_port if not in base_url.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
PURPOSE: Set base URL and port to use in connections.
"""
self.__base_url = base_url if base_url else self.make_base_url()
if not self.__base_url:
return
my_base, my_port = urllib.parse.splitport(self.__base_url)
if my_port:
self.__base_url = my_base # take off port and store in base_port
if base_port:
raise ValueError('base_url=%s has port and base_port=%s' % (
self.__base_url, base_port))
base_port = my_port
self.__base_port = base_port
def make_url(self, path: str = '') -> str:
"""Make url with given path.
:param path='': Optional relative path.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
:return: Full string URL.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
PURPOSE: Combine base URL and port set with set_base_url with path.
"""
result = self.__base_url
if not result:
logging.error('self.__dict__: %s', str(self.__dict__))
raise ValueError('Must have base_url set to call make_url')
if self.__base_port:
result += ':' + str(self.__base_port)
result += '/' + path.lstrip('/')
return result
@classmethod
def make_base_url(cls) -> str:
"""Return string indicating base URL or None if not known.
Sub-classes can override if they know a good default. Otherwise,
should call set_base_url when they have the url to use.
"""
return None
def get_login_info(self) -> (str, str):
"""Return string login field and login value
Sub-classes may want to override.
"""
return 'username', getattr(self, 'username', 'test_user')
def get_password(self, login_name: str) -> str:
"Get password for given login name"
return self.get_secret(login_name, 'test_passwords')
@classmethod
def get_login_route(cls) -> str:
"Return path to login route."
_ = cls
return '/login'
@classmethod
def get_secret(cls, name: str, category: str = 'root') -> str:
"""Lookup a secret like a password or something.
:param name: Name of secret to lookup
:param category='root': Category of secret.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
:return: A string reprsenting the secret you want to get.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
PURPOSE: Provide a way to lookup secrets like passwords, etc.
"""
raise NotImplementedError
def setup_session(self):
"""Setup a requests.session and return it.
This sets up a session so we are logged in to whatever we get
from self.make_url(self.get_login_route()) using the login from
get_login_info().
"""
session = requests.session()
my_url = self.make_url(self.get_login_route())
csrf_field, csrf = None, None
try:
csrf_field, csrf = self.get_csrf_from_form(session, my_url)
except Exception as problem:
logging.error('Failed to get csrf due to exception: %s', str(
problem))
logging.error('Maybe override get_csrf_from_form?')
raise
login_field, login_name = self.get_login_info()
password = self.get_password(login_name)
data = {login_field: login_name, 'password': password}
if csrf:
data[csrf_field] = csrf
post_resp = session.post(my_url, data, verify=False)
if post_resp.status_code != 200:
raise ValueError('Got unexpected status/reason: %s/%s in login' % (
post_resp.status_code, post_resp.reason))
return session
def do_main(self, session) -> SimpleTaskResult:
"""Sub-classes should override this to do the main work.
Sub-classes should override this to return an instance of SimpleTaskResult
describing the result of running the task. See docs for SimpleTaskResult
for more details.
"""
raise NotImplementedError
@classmethod
def main_call(cls, ox_herd_task):
logging.info('Starting main_call for %s', cls.__name__)
session = ox_herd_task.setup_session()
result = ox_herd_task.do_main(session)
msg = 'Go return_value %s' % (result.return_value)
cls.note_comment(ox_herd_task, msg)
return result
@classmethod
def note_comment(cls, ox_herd_task: ox_tasks.OxHerdTask,
comment: str):
"""Note a comment for a task we ran.
:param ox_herd_task: Task we ran.
:param comment: Comment to note.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
PURPOSE: Mainly a placeholder in case sub-classes want
to do some kind of logging for comments.
"""
_ = cls
logging.info('Comment for task %s: %s', ox_herd_task.name,
comment)
@staticmethod
def get_csrf_from_form(
session, url: str, csrf_field: str = 'csrf_token',
csrf_re: str = None) -> (str, str):
"""Do a get request for the given url and extract CSRF token.
:param session: Session we have to the web site.
:param url: String URL for form with CSRF token.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
:return: String name for CSRF field and string for CSRF token.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
PURPOSE: Flask WTForms provides a CSRF token to prevent CSRF
attacks. We need to hit the url with a GET request to
get the csrf_token and include that as a parameter of
our POST request. This function gets the csrf_token.
"""
result = session.get(url)
csrf_re = csrf_re if csrf_re else ' *'.join([
'id="%s"' % csrf_field, 'name="%s"' % csrf_field,
'type="hidden"', 'value="(?P<csrf>[^"]*)">'])
if isinstance(csrf_re, str):
csrf_re = re.compile(csrf_re)
match = csrf_re.search(result.text)
if not match:
raise ValueError('Could not extract csrf from url "%s"' % url)
return csrf_field, match.group('csrf')
def raise_on_bad_status(self, result):
"""Raise ValueError if http response looks like an error.
:param result: Response from an HTTP command such as what
do_main might report.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
:return: False if no problems, otherwise raises an exception.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
PURPOSE: Raise an exception if result looks like an error.
"""
if result.status_code != 200:
msg = 'Problem in task %s with reason: "%s"' % (
self.__class__.__name__, result.reason)
logging.error(msg)
raise ValueError(msg)
if ' error' in result.text.lower():
self.note_comment(self, 'Saw error in result: ' + str(result))
if isinstance(result.reason, str):
my_reason = result.reason
else:
my_reason = result.reason.text
msg = 'Saw "error" in result for task %s: "%s"' % (
self.__class__.__name__, my_reason)
logging.error(msg)
raise ValueError(msg)
return False
| bsd-2-clause | -2,642,499,308,341,380,000 | 33.654839 | 79 | 0.542958 | false |
cdrage/kedge | vendor/k8s.io/kubernetes/examples/selenium/selenium-test.py | 7 | 1088 | #!/usr/bin/env python
# Copyright 2015 The Kubernetes Authors.
#
# 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 selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
def check_browser(browser):
driver = webdriver.Remote(
command_executor='http://selenium-hub:4444/wd/hub',
desired_capabilities=getattr(DesiredCapabilities, browser)
)
driver.get("http://google.com")
assert "google" in driver.page_source
driver.close()
print("Browser %s checks out!" % browser)
check_browser("FIREFOX")
check_browser("CHROME")
| apache-2.0 | 6,258,468,533,772,548,000 | 33 | 78 | 0.758272 | false |
Goldmund-Wyldebeast-Wunderliebe/django-diazo | django_diazo/views/generic.py | 1 | 2786 | from django.http import HttpResponse
from django.views.generic import View, RedirectView
#from django.views.generic.base import ContextMixin # Django 1.5 only
from django_diazo.utils.dict2xml import dict2xml
class DiazoEnableThemeView(View):
def dispatch(self, request, *args, **kwargs):
if 'django_diazo_theme_enabled' in request.session:
request.session.pop('django_diazo_theme_enabled')
return super(DiazoEnableThemeView, self).dispatch(request, *args, **kwargs)
class DiazoDisableThemeView(View):
def dispatch(self, request, *args, **kwargs):
request.session['django_diazo_theme_enabled'] = False
return super(DiazoDisableThemeView, self).dispatch(request, *args, **kwargs)
class DiazoEnableThemeRedirectView(DiazoEnableThemeView, RedirectView):
pass
class DiazoDisableThemeRedirectView(DiazoDisableThemeView, RedirectView):
pass
class ContextMixin(object):
"""
Copied from Django 1.5.
A default context mixin that passes the keyword arguments received by
get_context_data as the template context.
"""
def get_context_data(self, **kwargs):
if 'view' not in kwargs:
kwargs['view'] = self
return kwargs
class DiazoGenericXmlHtmlResponse(ContextMixin, View):
"""
Clased based view to output XML as Html. By default, id's and classes are attributes of the tags.
It uses the context data that is defined by get_context_data() from ContextMixin.
Example usage:
class IndexView(DiazoGenericXmlHtmlResponse):
def get_context_data(self, **kwargs):
context = {
'id': 'test',
'class': 'test',
'title': 'Title',
'list': [1, 2, 3, 4, 5],
'dict': {
'a': 'b'
}
}
return dict(super(IndexView, self).get_context_data(**kwargs).items() + context.items())
"""
def __init__(self):
super(DiazoGenericXmlHtmlResponse, self).__init__()
self._attributenames = ['id', 'class']
@property
def attributenames(self):
return self._attributenames
@attributenames.setter
def attributenames(self, value):
self._attributenames = value
def dispatch(self, request, *args, **kwargs):
"""
Invoke the initial handler but don't return the reponse, we create our own response.
"""
ret = super(DiazoGenericXmlHtmlResponse, self).dispatch(request, *args, **kwargs)
context = self.get_context_data(**kwargs)
content = '<?xml version="1.0" encoding="UTF-8"?>' +\
dict2xml(context, 'context', attributenames=self.attributenames)
return HttpResponse(content, content_type="text/html")
| gpl-2.0 | -617,850,640,237,872,900 | 33.825 | 101 | 0.64178 | false |
kylewray/nova | tests/grid_world/grid_world.py | 1 | 5960 | """ The MIT License (MIT)
Copyright (c) 2016 Kyle Hollins Wray, University of Massachusetts
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 os
import sys
import itertools as it
thisFilePath = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(thisFilePath, "..", "..", "python"))
from nova.mdp import *
from nova.mdp_vi import *
from nova.ssp_lao_star import *
from nova.ssp_rtdp import *
trials = [
{'name': "VI CPU", 'filename': "domains/grid_world_mdp.raw", 'filetype': "raw", 'algorithm': "vi", 'process': "cpu", 'w': 4, 'h': 3},
{'name': "VI GPU", 'filename': "domains/grid_world_mdp.raw", 'filetype': "raw", 'algorithm': "vi", 'process': "gpu", 'w': 4, 'h': 3},
{'name': "LAO* CPU", 'filename': "domains/grid_world_ssp.raw", 'filetype': "raw", 'algorithm': "lao*", 'process': "cpu", 'w': 4, 'h': 3},
{'name': "RTDP CPU", 'filename': "domains/grid_world_ssp.raw", 'filetype': "raw", 'algorithm': "rtdp", 'process': "cpu", 'w': 4, 'h': 3},
{'name': "VI CPU (Another)", 'filename': "domains/another_grid_world_mdp.raw", 'filetype': "raw", 'algorithm': "vi", 'process': "cpu", 'w': 10, 'h': 10},
{'name': "VI GPU (Another)", 'filename': "domains/another_grid_world_mdp.raw", 'filetype': "raw", 'algorithm': "vi", 'process': "gpu", 'w': 10, 'h': 10},
{'name': "LAO* CPU (Another)", 'filename': "domains/another_grid_world_ssp.raw", 'filetype': "raw", 'algorithm': "lao*", 'process': "cpu", 'w': 10, 'h': 10},
{'name': "RTDP CPU (Another)", 'filename': "domains/another_grid_world_ssp.raw", 'filetype': "raw", 'algorithm': "rtdp", 'process': "cpu", 'w': 10, 'h': 10},
{'name': "VI CPU (Intense)", 'filename': "domains/intense_grid_world_mdp.raw", 'filetype': "raw", 'algorithm': "vi", 'process': "cpu", 'w': 50, 'h': 50},
{'name': "VI GPU (Intense)", 'filename': "domains/intense_grid_world_mdp.raw", 'filetype': "raw", 'algorithm': "vi", 'process': "gpu", 'w': 50, 'h': 50},
{'name': "LAO* CPU (Intense)", 'filename': "domains/intense_grid_world_ssp.raw", 'filetype': "raw", 'algorithm': "lao*", 'process': "cpu", 'w': 50, 'h': 50},
{'name': "RTDP CPU (Intense)", 'filename': "domains/intense_grid_world_ssp.raw", 'filetype': "raw", 'algorithm': "rtdp", 'process': "cpu", 'w': 50, 'h': 50},
#{'name': "VI CPU (Massive)", 'filename': "domains/massive_grid_world_mdp.raw", 'filetype': "raw", 'algorithm': "vi", 'process': "cpu", 'w': 75, 'h': 75},
#{'name': "VI GPU (Massive)", 'filename': "domains/massive_grid_world_mdp.raw", 'filetype': "raw", 'algorithm': "vi", 'process': "gpu", 'w': 75, 'h': 75},
#{'name': "LAO* CPU (Massive)", 'filename': "domains/massive_grid_world_ssp.raw", 'filetype': "raw", 'algorithm': "lao*", 'process': "cpu", 'w': 75, 'h': 75},
#{'name': "RTDP CPU (Massive)", 'filename': "domains/massive_grid_world_ssp.raw", 'filetype': "raw", 'algorithm': "rtdp", 'process': "cpu", 'w': 75, 'h': 75},
]
for trial in trials:
print(trial['name'])
gridWorldFile = os.path.join(thisFilePath, trial['filename'])
gridWorld = MDP()
gridWorld.load(gridWorldFile, filetype=trial['filetype'])
gridWorld.horizon = 10000
gridWorld.epsilon = 0.001
if trial['process'] == "gpu":
gridWorld.initialize_gpu()
# The heuristic (admissible) is the manhattan distance to the goal, which is always the upper right corner.
#h = np.array([abs(y) + abs(trial['w'] - 1 - x) for y, x in it.product(range(trial['h']), range(trial['w']))] + [0.0]).flatten()
#h = np.array([0.0 for s in range(gridWorld.n)])
#policy, timing = gridWorld.solve(algorithm=trial['algorithm'], process=trial['process'], heuristic=h)
if trial['algorithm'] == "vi" and trial['process'] == "cpu":
algorithm = MDPValueIterationCPU(gridWorld)
elif trial['algorithm'] == "vi" and trial['process'] == "gpu":
algorithm = MDPValueIterationGPU(gridWorld)
elif trial['algorithm'] == "lao*" and trial['process'] == "cpu":
algorithm = SSPLAOStarCPU(gridWorld)
elif trial['algorithm'] == "rtdp" and trial['process'] == "cpu":
algorithm = SSPRTDPCPU(gridWorld)
algorithm.trials = 10000
policy = algorithm.solve()
#print(algorithm)
prettyActions = ["L", "U", "R", "D"]
if policy.r == 0:
for y in range(trial['h']):
for x in range(trial['w']):
print(prettyActions[policy.pi[y * trial['w'] + x]] + " ", end='')
print()
else:
S = [policy.S[i] for i in range(policy.r)]
for y in range(trial['h']):
for x in range(trial['w']):
try:
i = S.index(y * trial['w'] + x)
print(prettyActions[policy.pi[i]] + " ", end='')
except ValueError:
print(" ", end='')
print()
| mit | 7,687,294,150,454,753,000 | 52.693694 | 167 | 0.601846 | false |
BackupTheBerlios/kimchi | src/ui/util.py | 1 | 2258 | # coding: utf-8
'''
Copyright (c) 2010, Alexandru Dancu
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the project 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.
'''
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def makeSplitterVisible(splitter):
handle = splitter.handle(1)
layout = QVBoxLayout()
layout.setSpacing(0)
layout.setMargin(0)
line = QFrame()
line.setFrameShape(QFrame.HLine)
line.setFrameShadow(QFrame.Sunken)
layout.addWidget(line)
handle.setLayout(layout)
def setBackgroundColor(widget, color):
widget.setAutoFillBackground(True)
palette = QPalette()
palette.setColor(QPalette.Background, color)
widget.setPalette(palette)
def setGreenBackground(widget):
setBackgroundColor(widget, QColor.fromRgb(0, 255, 0))
def setRedBackground(widget):
setBackgroundColor(widget, QColor.fromRgb(255, 0, 0))
| bsd-3-clause | -5,801,539,120,365,157,000 | 38.631579 | 77 | 0.771036 | false |
daveinnyc/various | utilities/rename-random-number.py | 1 | 1044 | #! python3
''' rename files in local directory with random integer names.
windows screen saver isn't very good at randomizing fotos shown.
Change file names regularly to provide more variety
'''
import os
import re
import random
import time
random.seed()
new_names = set()
original_files = []
for entry in os.listdir():
if os.path.isfile(entry):
if re.match(".*jpg", entry):
original_files.append(entry)
for counter in range(0, len(original_files)):
new_value = random.randint(0,1000000000)
# Make sure the new names are unique
# -- note this is only the new set, the new name
# may still duplicate an old name. The set is
# to minimize this chance
while new_value in new_names:
new_value = random.randint(0,1000000000)
new_names.add(new_value)
for of in original_files:
nf = str(new_names.pop()).zfill(10) + ".jpg"
try:
os.rename(of, nf)
except Exception as e:
print("{}: {}".format(of, e))
time.sleep(5)
| mit | -621,701,033,835,631,900 | 22.727273 | 65 | 0.6341 | false |
peterfpeterson/mantid | Framework/PythonInterface/plugins/algorithms/ExportGeometry.py | 3 | 5753 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
#pylint: disable=no-init
from mantid.api import PythonAlgorithm, AlgorithmFactory, WorkspaceProperty, \
InstrumentValidator, FileProperty, FileAction
from mantid.kernel import Direction, StringArrayProperty, StringListValidator
SOURCE_XML = """ <!--SOURCE-->
<component type="moderator">
<location z="%(z)f"/>
</component>
<type is="Source" name="moderator"/>
"""
SAMPLE_XML = """ <!--SAMPLE-->
<component type="sample-position">
<location x="%(x)f" y="%(y)f" z="%(z)f"/>
</component>
<type is="SamplePos" name="sample-position"/>
"""
COMPONENT_XML_FULL = """ <location x="%(x)f" y="%(y)f" z="%(z)f" name="%(name)s">
<rot %(alpha_string)s">
<rot %(beta_string)s">
<rot %(gamma_string)s"/>
</rot>
</rot>
</location>
"""
# no rotation needs to be specified
COMPONENT_XML_MINIMAL = """ <location x="%(x)f" y="%(y)f" z="%(z)f" name="%(name)s">
</location>
"""
class ExportGeometry(PythonAlgorithm):
_eulerCon = None
_eulerXML={"X":'axis-x="1" axis-y="0" axis-z="0" val="',
"Y":'axis-x="0" axis-y="1" axis-z="0" val="',
"Z":'axis-x="0" axis-y="0" axis-z="1" val="'}
def category(self):
return "Utility\\Instrument"
def seeAlso(self):
return [ "LoadInstrument" ]
def name(self):
return "ExportGeometry"
def summary(self):
return "Extract components from larger in-memory instrument, save as IDF style xml"
def PyInit(self):
self.declareProperty(WorkspaceProperty("InputWorkspace", "",
validator=InstrumentValidator(),
direction=Direction.Input),
doc="Workspace containing the instrument to be exported")
eulerConventions = ["ZXZ", "XYX", "YZY", "ZYZ", "XZX", "YXY",
"XYZ", "YZX", "ZXY", "XZY", "ZYX", "YXZ"]
self.declareProperty(name="EulerConvention", defaultValue="YZY",
validator=StringListValidator(eulerConventions),
doc="Euler angles convention used when writing angles.")
self.declareProperty(StringArrayProperty("Components",
direction=Direction.Input),
doc="Comma separated list of instrument component names to export")
self.declareProperty(FileProperty(name="Filename",
defaultValue="",
action=FileAction.Save,
extensions=[".xml"]),
doc="Save file")
def validateInputs(self):
issues = {}
# get the input workspace
wksp = self.getProperty("InputWorkspace").value
# confirm that all of the requested components exist
components = self.getProperty("Components").value
if len(components) <= 0:
issues['Components'] = "Must supply components"
else:
components = [component for component in components
if wksp.getInstrument().getComponentByName(component) is None]
if len(components) > 0:
issues['Components'] = "Instrument has no component \"" \
+ ','.join(components) + "\""
return issues
def __updatePos(self, info, component):
pos = component.getPos()
info['x'] = pos.X()
info['y'] = pos.Y()
info['z'] = pos.Z()
angles = component.getRotation().getEulerAngles(self._eulerCon)
info['alpha'] = angles[0]
info['beta'] = angles[1]
info['gamma'] = angles[2]
info['alpha_string'] = self._eulerXML[self._eulerCon[0]] + str(angles[0])
info['beta_string'] = self._eulerXML[self._eulerCon[1]] + str(angles[1])
info['gamma_string'] = self._eulerXML[self._eulerCon[2]] + str(angles[2])
def __writexmlSource(self, handle, instrument):
source = {}
self.__updatePos(source, instrument.getSource())
handle.write(SOURCE_XML % source)
sample = {}
self.__updatePos(sample, instrument.getSample())
handle.write(SAMPLE_XML % sample)
def __writexml(self, handle, component):
info = {'name': component.getName()}
self.__updatePos(info, component)
if info['alpha'] == 0. and info['beta'] == 0. and info['gamma'] == 0.:
handle.write(COMPONENT_XML_MINIMAL % info)
else:
handle.write(COMPONENT_XML_FULL % info)
def PyExec(self):
wksp = self.getProperty("InputWorkspace").value
components = self.getProperty("Components").value
filename = self.getProperty("Filename").value
self._eulerCon = self.getProperty("EulerConvention").value
instrument = wksp.getInstrument()
with open(filename, 'w') as handle:
# write out the source and sample components
self.__writexmlSource(handle, instrument)
# write out the requested components
handle.write(""" <!--COMPONENTS-->\n""")
for component in components:
component = instrument.getComponentByName(component)
self.__writexml(handle, component)
AlgorithmFactory.subscribe(ExportGeometry)
| gpl-3.0 | -6,400,896,658,613,094,000 | 37.099338 | 96 | 0.56527 | false |
claudelee/git-cola | cola/settings.py | 9 | 4835 | # Copyright (c) 2008 David Aguilar
"""This handles saving complex settings such as bookmarks, etc.
"""
from __future__ import division, absolute_import, unicode_literals
import os
import sys
from cola import core
from cola import git
from cola import resources
import json
def mkdict(obj):
if type(obj) is dict:
return obj
else:
return {}
def mklist(obj):
if type(obj) is list:
return obj
else:
return []
def read_json(path):
try:
with core.xopen(path, 'rt') as fp:
return mkdict(json.load(fp))
except: # bad path or json
return {}
def write_json(values, path):
try:
parent = os.path.dirname(path)
if not core.isdir(parent):
core.makedirs(parent)
with core.xopen(path, 'wt') as fp:
json.dump(values, fp, indent=4)
except:
sys.stderr.write('git-cola: error writing "%s"\n' % path)
class Settings(object):
_file = resources.config_home('settings')
bookmarks = property(lambda self: mklist(self.values['bookmarks']))
gui_state = property(lambda self: mkdict(self.values['gui_state']))
recent = property(lambda self: mklist(self.values['recent']))
def __init__(self, verify=git.is_git_worktree):
"""Load existing settings if they exist"""
self.values = {
'bookmarks': [],
'gui_state': {},
'recent': [],
}
self.verify = verify
def remove_missing(self):
missing_bookmarks = []
missing_recent = []
for bookmark in self.bookmarks:
if not self.verify(bookmark):
missing_bookmarks.append(bookmark)
for bookmark in missing_bookmarks:
try:
self.bookmarks.remove(bookmark)
except:
pass
for recent in self.recent:
if not self.verify(recent):
missing_recent.append(recent)
for recent in missing_recent:
try:
self.recent.remove(recent)
except:
pass
def add_bookmark(self, bookmark):
"""Adds a bookmark to the saved settings"""
if bookmark not in self.bookmarks:
self.bookmarks.append(bookmark)
def remove_bookmark(self, bookmark):
"""Remove a bookmark"""
if bookmark in self.bookmarks:
self.bookmarks.remove(bookmark)
def remove_recent(self, entry):
"""Removes an item from the recent items list"""
if entry in self.recent:
self.recent.remove(entry)
def add_recent(self, entry):
if entry in self.recent:
self.recent.remove(entry)
self.recent.insert(0, entry)
if len(self.recent) >= 8:
self.recent.pop()
def path(self):
return self._file
def save(self):
write_json(self.values, self.path())
def load(self):
self.values.update(self.asdict())
self.remove_missing()
def asdict(self):
path = self.path()
if core.exists(path):
return read_json(path)
# We couldn't find ~/.config/git-cola, try ~/.cola
values = {}
path = os.path.join(core.expanduser('~'), '.cola')
if core.exists(path):
json_values = read_json(path)
# Keep only the entries we care about
for key in self.values:
try:
values[key] = json_values[key]
except KeyError:
pass
return values
def reload_recent(self):
values = self.asdict()
self.values['recent'] = mklist(values.get('recent', []))
def save_gui_state(self, gui):
"""Saves settings for a cola view"""
name = gui.name()
self.gui_state[name] = mkdict(gui.export_state())
self.save()
def get_gui_state(self, gui):
"""Returns the saved state for a gui"""
try:
state = mkdict(self.gui_state[gui.name()])
except KeyError:
state = self.gui_state[gui.name()] = {}
return state
class Session(Settings):
"""Store per-session settings"""
_sessions_dir = resources.config_home('sessions')
repo = property(lambda self: self.values['repo'])
def __init__(self, session_id, repo=None):
Settings.__init__(self)
self.session_id = session_id
self.values.update({'repo': repo})
def path(self):
return os.path.join(self._sessions_dir, self.session_id)
def load(self):
path = self.path()
if core.exists(path):
self.values.update(read_json(path))
try:
os.unlink(path)
except:
pass
return True
return False
| gpl-2.0 | -7,268,508,707,475,079,000 | 26.011173 | 71 | 0.55636 | false |
aosprey/rose | lib/python/rose/config_editor/valuewidget/intspin.py | 1 | 4131 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2012-8 Met Office.
#
# This file is part of Rose, a framework for meteorological suites.
#
# Rose 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.
#
# Rose 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 Rose. If not, see <http://www.gnu.org/licenses/>.
# -----------------------------------------------------------------------------
import sys
import pygtk
pygtk.require('2.0')
import gtk
import rose.config_editor
class IntSpinButtonValueWidget(gtk.HBox):
"""This is a class to represent an integer with a spin button."""
WARNING_MESSAGE = 'Warning:\n variable value: {0}\n widget value: {1}'
def __init__(self, value, metadata, set_value, hook, arg_str=None):
super(IntSpinButtonValueWidget, self).__init__(homogeneous=False,
spacing=0)
self.value = value
self.metadata = metadata
self.set_value = set_value
self.hook = hook
self.upper = sys.maxint
self.lower = -sys.maxint - 1
tooltip_text = None
try:
int_value = int(value)
except (TypeError, ValueError):
int_value = 0
tooltip_text = self.WARNING_MESSAGE.format(value,
int_value)
if int_value > self.upper or int_value < self.lower:
acceptable = False
else:
acceptable = True
if acceptable:
entry = self.make_spinner(int_value)
signal = 'changed'
else:
entry = gtk.Entry()
entry.set_text(self.value)
signal = 'activate'
self.change_id = entry.connect(signal, self.setter)
entry.set_tooltip_text(tooltip_text)
entry.show()
self.pack_start(entry, False, False, 0)
self.warning_img = gtk.Image()
if not acceptable:
self.warning_img = gtk.Image()
self.warning_img.set_from_stock(gtk.STOCK_DIALOG_WARNING,
gtk.ICON_SIZE_MENU)
self.warning_img.set_tooltip_text(
rose.config_editor.WARNING_INTEGER_OUT_OF_BOUNDS)
self.warning_img.show()
self.pack_start(self.warning_img, False, False, 0)
self.grab_focus = lambda: self.hook.get_focus(entry)
def make_spinner(self, int_value):
my_adj = gtk.Adjustment(value=int_value,
upper=self.upper,
lower=self.lower,
step_incr=1)
spin_button = gtk.SpinButton(adjustment=my_adj, digits=0)
spin_button.connect('focus-in-event',
self.hook.trigger_scroll)
spin_button.set_numeric(True)
return spin_button
def setter(self, widget):
if isinstance(widget, gtk.Entry):
if widget.get_text != self.value:
self.value = widget.get_text()
self.set_value(self.value)
if (not widget.get_text().isdigit() or
int(widget.get_text()) > self.upper or
int(widget.get_text()) < self.lower):
self.warning_img.show()
else:
self.warning_img.hide()
else:
if str(widget.get_value_as_int()) != self.value:
self.value = str(widget.get_value_as_int())
self.set_value(self.value)
widget.set_tooltip_text(None)
return False
| gpl-3.0 | -1,833,023,984,379,527,700 | 34.307692 | 79 | 0.542484 | false |
15Dkatz/pants | tests/python/pants_test/option/test_quiet_option_integration.py | 4 | 1718 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import json
from pants.util.contextutil import temporary_file
from pants_test.pants_run_integration_test import PantsRunIntegrationTest
class TestOptionsQuietIntegration(PantsRunIntegrationTest):
def test_pants_default_quietness(self):
pants_run = self.run_pants(['export'])
self.assert_success(pants_run)
json.loads(pants_run.stdout_data)
def test_pants_no_quiet_cli(self):
pants_run = self.run_pants(['--no-quiet', 'export'])
self.assert_success(pants_run)
# Since pants progress will show up in stdout, therefore, json parsing should fail.
with self.assertRaises(ValueError):
json.loads(pants_run.stdout_data)
def test_pants_no_quiet_env(self):
pants_run = self.run_pants(['export'], extra_env={'PANTS_QUIET': 'FALSE'})
self.assert_success(pants_run)
# Since pants progress will show up in stdout, therefore, json parsing should fail.
with self.assertRaises(ValueError):
json.loads(pants_run.stdout_data)
def test_pants_no_quiet_output_file(self):
with temporary_file() as f:
pants_run = self.run_pants(['--no-quiet', 'export', '--output-file={}'.format(f.name)])
self.assert_success(pants_run)
json_string = f.read()
# Make sure the json is valid from the file read.
json.loads(json_string)
# Make sure json string does not appear in stdout.
self.assertNotIn(json_string, pants_run.stdout_data)
| apache-2.0 | 5,521,126,413,603,720,000 | 37.177778 | 93 | 0.704889 | false |
cryptobanana/ansible | test/runner/lib/config.py | 12 | 7856 | """Configuration classes."""
from __future__ import absolute_import, print_function
import os
import sys
from lib.util import (
CommonConfig,
is_shippable,
docker_qualify_image,
)
from lib.metadata import (
Metadata,
)
class EnvironmentConfig(CommonConfig):
"""Configuration common to all commands which execute in an environment."""
def __init__(self, args, command):
"""
:type args: any
"""
super(EnvironmentConfig, self).__init__(args)
self.command = command
self.local = args.local is True
if args.tox is True or args.tox is False or args.tox is None:
self.tox = args.tox is True
self.tox_args = 0
self.python = args.python if 'python' in args else None # type: str
else:
self.tox = True
self.tox_args = 1
self.python = args.tox # type: str
self.docker = docker_qualify_image(args.docker) # type: str
self.remote = args.remote # type: str
self.docker_privileged = args.docker_privileged if 'docker_privileged' in args else False # type: bool
self.docker_util = docker_qualify_image(args.docker_util if 'docker_util' in args else '') # type: str
self.docker_pull = args.docker_pull if 'docker_pull' in args else False # type: bool
self.docker_keep_git = args.docker_keep_git if 'docker_keep_git' in args else False # type: bool
self.tox_sitepackages = args.tox_sitepackages # type: bool
self.remote_stage = args.remote_stage # type: str
self.remote_provider = args.remote_provider # type: str
self.remote_aws_region = args.remote_aws_region # type: str
self.remote_terminate = args.remote_terminate # type: str
if self.remote_provider == 'default':
self.remote_provider = None
self.requirements = args.requirements # type: bool
if self.python == 'default':
self.python = None
self.python_version = self.python or '.'.join(str(i) for i in sys.version_info[:2])
self.delegate = self.tox or self.docker or self.remote
if self.delegate:
self.requirements = True
class TestConfig(EnvironmentConfig):
"""Configuration common to all test commands."""
def __init__(self, args, command):
"""
:type args: any
:type command: str
"""
super(TestConfig, self).__init__(args, command)
self.coverage = args.coverage # type: bool
self.coverage_label = args.coverage_label # type: str
self.include = args.include # type: list [str]
self.exclude = args.exclude # type: list [str]
self.require = args.require # type: list [str]
self.changed = args.changed # type: bool
self.tracked = args.tracked # type: bool
self.untracked = args.untracked # type: bool
self.committed = args.committed # type: bool
self.staged = args.staged # type: bool
self.unstaged = args.unstaged # type: bool
self.changed_from = args.changed_from # type: str
self.changed_path = args.changed_path # type: list [str]
self.lint = args.lint if 'lint' in args else False # type: bool
self.junit = args.junit if 'junit' in args else False # type: bool
self.failure_ok = args.failure_ok if 'failure_ok' in args else False # type: bool
self.metadata = Metadata.from_file(args.metadata) if args.metadata else Metadata()
self.metadata_path = None
class ShellConfig(EnvironmentConfig):
"""Configuration for the shell command."""
def __init__(self, args):
"""
:type args: any
"""
super(ShellConfig, self).__init__(args, 'shell')
class SanityConfig(TestConfig):
"""Configuration for the sanity command."""
def __init__(self, args):
"""
:type args: any
"""
super(SanityConfig, self).__init__(args, 'sanity')
self.test = args.test # type: list [str]
self.skip_test = args.skip_test # type: list [str]
self.list_tests = args.list_tests # type: bool
if args.base_branch:
self.base_branch = args.base_branch # str
elif is_shippable():
self.base_branch = os.environ.get('BASE_BRANCH', '') # str
if self.base_branch:
self.base_branch = 'origin/%s' % self.base_branch
else:
self.base_branch = ''
class IntegrationConfig(TestConfig):
"""Configuration for the integration command."""
def __init__(self, args, command):
"""
:type args: any
:type command: str
"""
super(IntegrationConfig, self).__init__(args, command)
self.start_at = args.start_at # type: str
self.start_at_task = args.start_at_task # type: str
self.allow_destructive = args.allow_destructive if 'allow_destructive' in args else False # type: bool
self.retry_on_error = args.retry_on_error # type: bool
self.continue_on_error = args.continue_on_error # type: bool
self.debug_strategy = args.debug_strategy # type: bool
self.changed_all_target = args.changed_all_target # type: str
self.list_targets = args.list_targets # type: bool
self.tags = args.tags
self.skip_tags = args.skip_tags
self.diff = args.diff
if self.list_targets:
self.explain = True
class PosixIntegrationConfig(IntegrationConfig):
"""Configuration for the posix integration command."""
def __init__(self, args):
"""
:type args: any
"""
super(PosixIntegrationConfig, self).__init__(args, 'integration')
class WindowsIntegrationConfig(IntegrationConfig):
"""Configuration for the windows integration command."""
def __init__(self, args):
"""
:type args: any
"""
super(WindowsIntegrationConfig, self).__init__(args, 'windows-integration')
self.windows = args.windows # type: list [str]
if self.windows:
self.allow_destructive = True
class NetworkIntegrationConfig(IntegrationConfig):
"""Configuration for the network integration command."""
def __init__(self, args):
"""
:type args: any
"""
super(NetworkIntegrationConfig, self).__init__(args, 'network-integration')
self.platform = args.platform # type: list [str]
self.inventory = args.inventory # type: str
class UnitsConfig(TestConfig):
"""Configuration for the units command."""
def __init__(self, args):
"""
:type args: any
"""
super(UnitsConfig, self).__init__(args, 'units')
self.collect_only = args.collect_only # type: bool
class CompileConfig(TestConfig):
"""Configuration for the compile command."""
def __init__(self, args):
"""
:type args: any
"""
super(CompileConfig, self).__init__(args, 'compile')
class CoverageConfig(EnvironmentConfig):
"""Configuration for the coverage command."""
def __init__(self, args):
"""
:type args: any
"""
super(CoverageConfig, self).__init__(args, 'coverage')
self.group_by = frozenset(args.group_by) if 'group_by' in args and args.group_by else set() # type: frozenset [str]
self.all = args.all if 'all' in args else False # type: bool
self.stub = args.stub if 'stub' in args else False # type: bool
class CoverageReportConfig(CoverageConfig):
"""Configuration for the coverage report command."""
def __init__(self, args):
"""
:type args: any
"""
super(CoverageReportConfig, self).__init__(args)
self.show_missing = args.show_missing # type: bool
| gpl-3.0 | -4,211,226,779,298,906,600 | 31.870293 | 124 | 0.602851 | false |
andmos/ansible | lib/ansible/playbook/attribute.py | 14 | 4395 | # (c) 2012-2014, Michael DeHaan <[email protected]>
#
# 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/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from copy import copy, deepcopy
_CONTAINERS = frozenset(('list', 'dict', 'set'))
class Attribute:
def __init__(
self,
isa=None,
private=False,
default=None,
required=False,
listof=None,
priority=0,
class_type=None,
always_post_validate=False,
inherit=True,
alias=None,
extend=False,
prepend=False,
static=False,
):
"""
:class:`Attribute` specifies constraints for attributes of objects which
derive from playbook data. The attributes of the object are basically
a schema for the yaml playbook.
:kwarg isa: The type of the attribute. Allowable values are a string
representation of any yaml basic datatype, python class, or percent.
(Enforced at post-validation time).
:kwarg private: (not used)
:kwarg default: Default value if unspecified in the YAML document.
:kwarg required: Whether or not the YAML document must contain this field.
If the attribute is None when post-validated, an error will be raised.
:kwarg listof: If isa is set to "list", this can optionally be set to
ensure that all elements in the list are of the given type. Valid
values here are the same as those for isa.
:kwarg priority: The order in which the fields should be parsed. Generally
this does not need to be set, it is for rare situations where another
field depends on the fact that another field was parsed first.
:kwarg class_type: If isa is set to "class", this can be optionally set to
a class (not a string name). The YAML data for this field will be
passed to the __init__ method of that class during post validation and
the field will be an instance of that class.
:kwarg always_post_validate: Controls whether a field should be post
validated or not (default: False).
:kwarg inherit: A boolean value, which controls whether the object
containing this field should attempt to inherit the value from its
parent object if the local value is None.
:kwarg alias: An alias to use for the attribute name, for situations where
the attribute name may conflict with a Python reserved word.
"""
self.isa = isa
self.private = private
self.default = default
self.required = required
self.listof = listof
self.priority = priority
self.class_type = class_type
self.always_post_validate = always_post_validate
self.inherit = inherit
self.alias = alias
self.extend = extend
self.prepend = prepend
self.static = static
if default is not None and self.isa in _CONTAINERS and not callable(default):
raise TypeError('defaults for FieldAttribute may not be mutable, please provide a callable instead')
def __eq__(self, other):
return other.priority == self.priority
def __ne__(self, other):
return other.priority != self.priority
# NB: higher priority numbers sort first
def __lt__(self, other):
return other.priority < self.priority
def __gt__(self, other):
return other.priority > self.priority
def __le__(self, other):
return other.priority <= self.priority
def __ge__(self, other):
return other.priority >= self.priority
class FieldAttribute(Attribute):
pass
| gpl-3.0 | 5,660,113,194,690,378,000 | 36.564103 | 112 | 0.656655 | false |
jmcarp/marshmallow-sqlalchemy | marshmallow_sqlalchemy/convert.py | 1 | 9093 | # -*- coding: utf-8 -*-
import inspect
import marshmallow as ma
from marshmallow import validate, fields
from marshmallow.compat import text_type
from sqlalchemy.dialects import postgresql, mysql
from sqlalchemy.orm.util import identity_key
import sqlalchemy as sa
from .exceptions import ModelConversionError
def get_pk_from_identity(obj):
"""Get primary key for `obj`. If `obj` has a compound primary key,
return a string of keys separated by ``":"``. This is the default keygetter for
used by `ModelSchema <marshmallow_sqlalchemy.ModelSchema>`.
"""
_, key = identity_key(instance=obj)
if len(key) == 1:
return key[0]
else: # Compund primary key
return ':'.join(text_type(x) for x in key)
class ModelConverter(object):
"""Class that converts a SQLAlchemy model into a dictionary of corresponding
marshmallow `Fields <marshmallow.fields.Field>`.
"""
SQLA_TYPE_MAPPING = {
sa.String: fields.String,
sa.Unicode: fields.String,
sa.Boolean: fields.Boolean,
sa.Unicode: fields.String,
sa.Binary: fields.String,
sa.Enum: fields.Field,
sa.Numeric: fields.Decimal,
sa.Float: fields.Decimal,
sa.Date: fields.Date,
postgresql.UUID: fields.UUID,
postgresql.MACADDR: fields.String,
postgresql.INET: fields.String,
mysql.BIT: fields.Integer,
mysql.TINYINT: fields.Integer,
mysql.SMALLINT: fields.Integer,
mysql.INTEGER: fields.Integer,
mysql.BIGINT: fields.Integer,
mysql.NUMERIC: fields.Decimal,
mysql.DECIMAL: fields.Decimal,
mysql.DATETIME: fields.DateTime,
mysql.DATE: fields.Date,
mysql.TIME: fields.Time,
mysql.YEAR: fields.Integer,
mysql.TEXT: fields.String,
mysql.TINYTEXT: fields.String,
mysql.MEDIUMTEXT: fields.String,
mysql.LONGTEXT: fields.String,
mysql.BLOB: fields.String,
mysql.TINYBLOB: fields.String,
mysql.MEDIUMBLOB: fields.String,
mysql.LONGBLOB: fields.String,
mysql.SET: fields.List,
mysql.ENUM: fields.Field,
}
DIRECTION_MAPPING = {
'MANYTOONE': fields.QuerySelect,
'MANYTOMANY': fields.QuerySelectList,
'ONETOMANY': fields.QuerySelectList,
}
def fields_for_model(self, model, session=None, include_fk=False, keygetter=None, fields=None):
result = {}
for prop in model.__mapper__.iterate_properties:
if fields and prop.key not in fields:
continue
if hasattr(prop, 'columns'):
if not include_fk and prop.columns[0].foreign_keys:
continue
field = self.property2field(prop, session=session, keygetter=keygetter)
if field:
result[prop.key] = field
return result
def property2field(self, prop, session=None, keygetter=None, instance=True, **kwargs):
field_class = self._get_field_class_for_property(prop)
if not instance:
return field_class
field_kwargs = self._get_field_kwargs_for_property(
prop, session=session, keygetter=keygetter
)
field_kwargs.update(kwargs)
return field_class(**field_kwargs)
def column2field(self, column, instance=True, **kwargs):
field_class = self._get_field_class_for_column(column)
if not instance:
return field_class
field_kwargs = self.get_base_kwargs()
self._add_column_kwargs(field_kwargs, column)
field_kwargs.update(kwargs)
return field_class(**field_kwargs)
def field_for(self, model, property_name, **kwargs):
prop = model.__mapper__.get_property(property_name)
return self.property2field(prop, **kwargs)
def _get_field_class_for_column(self, column):
field_cls = None
types = inspect.getmro(type(column.type))
# First search for a field class from self.SQLA_TYPE_MAPPING
for col_type in types:
if col_type in self.SQLA_TYPE_MAPPING:
field_cls = self.SQLA_TYPE_MAPPING[col_type]
break
else:
# Try to find a field class based on the column's python_type
if column.type.python_type in ma.Schema.TYPE_MAPPING:
field_cls = ma.Schema.TYPE_MAPPING[column.type.python_type]
else:
raise ModelConversionError(
'Could not find field column of type {0}.'.format(types[0]))
return field_cls
def _get_field_class_for_property(self, prop):
if hasattr(prop, 'direction'):
field_cls = self.DIRECTION_MAPPING[prop.direction.name]
else:
column = prop.columns[0]
field_cls = self._get_field_class_for_column(column)
return field_cls
def _get_field_kwargs_for_property(self, prop, session=None, keygetter=None):
kwargs = self.get_base_kwargs()
if hasattr(prop, 'columns'):
column = prop.columns[0]
self._add_column_kwargs(kwargs, column)
if hasattr(prop, 'direction'): # Relationship property
self._add_relationship_kwargs(kwargs, prop, session=session, keygetter=keygetter)
if getattr(prop, 'doc', None): # Useful for documentation generation
kwargs['description'] = prop.doc
return kwargs
def _add_column_kwargs(self, kwargs, column):
"""Add keyword arguments to kwargs (in-place) based on the passed in
`Column <sqlalchemy.schema.Column>`.
"""
if column.nullable:
kwargs['allow_none'] = True
if hasattr(column.type, 'enums'):
kwargs['validate'].append(validate.OneOf(choices=column.type.enums))
# Add a length validator if a max length is set on the column
if hasattr(column.type, 'length'):
kwargs['validate'].append(validate.Length(max=column.type.length))
if hasattr(column.type, 'scale'):
kwargs['places'] = getattr(column.type, 'scale', None)
# Primary keys are dump_only ("read-only")
if getattr(column, 'primary_key', False):
kwargs['dump_only'] = True
def _add_relationship_kwargs(self, kwargs, prop, session, keygetter=None):
"""Add keyword arguments to kwargs (in-place) based on the passed in
relationship `Property`.
"""
# Get field class based on python type
if not session:
raise ModelConversionError(
'Cannot convert field {0}, need DB session.'.format(prop.key)
)
foreign_model = prop.mapper.class_
nullable = True
for pair in prop.local_remote_pairs:
if not pair[0].nullable:
nullable = False
kwargs.update({
'allow_none': nullable,
'query': lambda: session.query(foreign_model).all(),
'keygetter': keygetter or get_pk_from_identity,
})
def get_base_kwargs(self):
return {
'validate': []
}
default_converter = ModelConverter()
fields_for_model = default_converter.fields_for_model
"""Generate a dict of field_name: `marshmallow.fields.Field` pairs for the
given model.
:param model: The SQLAlchemy model
:param Session session: SQLAlchemy session. Required if the model includes
foreign key relationships.
:param bool include_fk: Whether to include foreign key fields in the output.
:return: dict of field_name: Field instance pairs
"""
property2field = default_converter.property2field
"""Convert a SQLAlchemy `Property` to a field instance or class.
:param Property prop: SQLAlchemy Property.
:param Session session: SQLALchemy session.
:param keygetter: See `marshmallow.fields.QuerySelect` for documenation on the
keygetter parameter.
:param bool instance: If `True`, return `Field` instance, computing relevant kwargs
from the given property. If `False`, return the `Field` class.
:param kwargs: Additional keyword arguments to pass to the field constructor.
:return: A `marshmallow.fields.Field` class or instance.
"""
column2field = default_converter.column2field
"""Convert a SQLAlchemy `Column <sqlalchemy.schema.Column>` to a field instance or class.
:param sqlalchemy.schema.Column column: SQLAlchemy Column.
:param bool instance: If `True`, return `Field` instance, computing relevant kwargs
from the given property. If `False`, return the `Field` class.
:return: A `marshmallow.fields.Field` class or instance.
"""
field_for = default_converter.field_for
"""Convert a property for a mapped SQLAlchemy class to a marshmallow `Field`.
Example: ::
date_created = field_for(Author, 'date_created', dump_only=True)
author = field_for(Book, 'author', session=session)
:param type model: A SQLAlchemy mapped class.
:param str property_name: The name of the property to convert.
:param kwargs: Extra keyword arguments to pass to `property2field`
:return: A `marshmallow.fields.Field` class or instance.
"""
| mit | 2,606,464,342,441,194,000 | 36.419753 | 99 | 0.646431 | false |
WillisXChen/django-oscar | oscar/lib/python2.7/site-packages/django/template/backends/django.py | 44 | 3018 | # Since this package contains a "django" module, this is required on Python 2.
from __future__ import absolute_import
import warnings
from django.conf import settings
from django.template.context import Context, RequestContext, make_context
from django.template.engine import Engine, _dirs_undefined
from django.utils.deprecation import RemovedInDjango110Warning
from .base import BaseEngine
class DjangoTemplates(BaseEngine):
app_dirname = 'templates'
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
options.setdefault('debug', settings.DEBUG)
options.setdefault('file_charset', settings.FILE_CHARSET)
super(DjangoTemplates, self).__init__(params)
self.engine = Engine(self.dirs, self.app_dirs, **options)
def from_string(self, template_code):
return Template(self.engine.from_string(template_code))
def get_template(self, template_name, dirs=_dirs_undefined):
return Template(self.engine.get_template(template_name, dirs))
class Template(object):
def __init__(self, template):
self.template = template
@property
def origin(self):
# TODO: define the Origin API. For now simply forwarding to the
# underlying Template preserves backwards-compatibility.
return self.template.origin
def render(self, context=None, request=None):
# A deprecation path is required here to cover the following usage:
# >>> from django.template import Context
# >>> from django.template.loader import get_template
# >>> template = get_template('hello.html')
# >>> template.render(Context({'name': 'world'}))
# In Django 1.7 get_template() returned a django.template.Template.
# In Django 1.8 it returns a django.template.backends.django.Template.
# In Django 1.10 the isinstance checks should be removed. If passing a
# Context or a RequestContext works by accident, it won't be an issue
# per se, but it won't be officially supported either.
if isinstance(context, RequestContext):
if request is not None and request is not context.request:
raise ValueError(
"render() was called with a RequestContext and a request "
"argument which refer to different requests. Make sure "
"that the context argument is a dict or at least that "
"the two arguments refer to the same request.")
warnings.warn(
"render() must be called with a dict, not a RequestContext.",
RemovedInDjango110Warning, stacklevel=2)
elif isinstance(context, Context):
warnings.warn(
"render() must be called with a dict, not a Context.",
RemovedInDjango110Warning, stacklevel=2)
else:
context = make_context(context, request)
return self.template.render(context)
| bsd-3-clause | -5,517,403,807,810,914,000 | 39.783784 | 78 | 0.656064 | false |
letsencrypt/letsencrypt | certbot-postfix/certbot_postfix/tests/util_test.py | 1 | 8459 | """Tests for certbot_postfix.util."""
import subprocess
import unittest
import mock
from certbot import errors
class PostfixUtilBaseTest(unittest.TestCase):
"""Tests for certbot_postfix.util.PostfixUtilBase."""
@classmethod
def _create_object(cls, *args, **kwargs):
from certbot_postfix.util import PostfixUtilBase
return PostfixUtilBase(*args, **kwargs)
@mock.patch('certbot_postfix.util.verify_exe_exists')
def test_no_exe(self, mock_verify):
expected_error = errors.NoInstallationError
mock_verify.side_effect = expected_error
self.assertRaises(expected_error, self._create_object, 'nonexistent')
def test_object_creation(self):
with mock.patch('certbot_postfix.util.verify_exe_exists'):
self._create_object('existent')
@mock.patch('certbot_postfix.util.check_all_output')
def test_call_extends_args(self, mock_output):
# pylint: disable=protected-access
with mock.patch('certbot_postfix.util.verify_exe_exists'):
mock_output.return_value = 'expected'
postfix = self._create_object('executable')
postfix._call(['many', 'extra', 'args'])
mock_output.assert_called_with(['executable', 'many', 'extra', 'args'])
postfix._call()
mock_output.assert_called_with(['executable'])
def test_create_with_config(self):
# pylint: disable=protected-access
with mock.patch('certbot_postfix.util.verify_exe_exists'):
postfix = self._create_object('exec', 'config_dir')
self.assertEqual(postfix._base_command, ['exec', '-c', 'config_dir'])
class PostfixUtilTest(unittest.TestCase):
def setUp(self):
# pylint: disable=protected-access
from certbot_postfix.util import PostfixUtil
with mock.patch('certbot_postfix.util.verify_exe_exists'):
self.postfix = PostfixUtil()
self.postfix._call = mock.Mock()
self.mock_call = self.postfix._call
def test_test(self):
self.postfix.test()
self.mock_call.assert_called_with(['check'])
def test_test_raises_error_when_check_fails(self):
self.mock_call.side_effect = [subprocess.CalledProcessError(1, "")]
self.assertRaises(errors.MisconfigurationError, self.postfix.test)
self.mock_call.assert_called_with(['check'])
def test_restart_while_running(self):
self.mock_call.side_effect = [subprocess.CalledProcessError(1, ""), None]
self.postfix.restart()
self.mock_call.assert_called_with(['start'])
def test_restart_while_not_running(self):
self.postfix.restart()
self.mock_call.assert_called_with(['reload'])
def test_restart_raises_error_when_reload_fails(self):
self.mock_call.side_effect = [None, subprocess.CalledProcessError(1, "")]
self.assertRaises(errors.PluginError, self.postfix.restart)
self.mock_call.assert_called_with(['reload'])
def test_restart_raises_error_when_start_fails(self):
self.mock_call.side_effect = [
subprocess.CalledProcessError(1, ""),
subprocess.CalledProcessError(1, "")]
self.assertRaises(errors.PluginError, self.postfix.restart)
self.mock_call.assert_called_with(['start'])
class CheckAllOutputTest(unittest.TestCase):
"""Tests for certbot_postfix.util.check_all_output."""
@classmethod
def _call(cls, *args, **kwargs):
from certbot_postfix.util import check_all_output
return check_all_output(*args, **kwargs)
@mock.patch('certbot_postfix.util.logger')
@mock.patch('certbot_postfix.util.subprocess.Popen')
def test_command_error(self, mock_popen, mock_logger):
command = 'foo'
retcode = 42
output = 'bar'
err = 'baz'
mock_popen().communicate.return_value = (output, err)
mock_popen().poll.return_value = 42
self.assertRaises(subprocess.CalledProcessError, self._call, command)
log_args = mock_logger.debug.call_args[0]
for value in (command, retcode, output, err,):
self.assertTrue(value in log_args)
@mock.patch('certbot_postfix.util.subprocess.Popen')
def test_success(self, mock_popen):
command = 'foo'
expected = ('bar', '')
mock_popen().communicate.return_value = expected
mock_popen().poll.return_value = 0
self.assertEqual(self._call(command), expected)
def test_stdout_error(self):
self.assertRaises(ValueError, self._call, stdout=None)
def test_stderr_error(self):
self.assertRaises(ValueError, self._call, stderr=None)
def test_universal_newlines_error(self):
self.assertRaises(ValueError, self._call, universal_newlines=False)
class VerifyExeExistsTest(unittest.TestCase):
"""Tests for certbot_postfix.util.verify_exe_exists."""
@classmethod
def _call(cls, *args, **kwargs):
from certbot_postfix.util import verify_exe_exists
return verify_exe_exists(*args, **kwargs)
@mock.patch('certbot_postfix.util.certbot_util.exe_exists')
@mock.patch('certbot_postfix.util.plugins_util.path_surgery')
def test_failure(self, mock_exe_exists, mock_path_surgery):
mock_exe_exists.return_value = mock_path_surgery.return_value = False
self.assertRaises(errors.NoInstallationError, self._call, 'foo')
@mock.patch('certbot_postfix.util.certbot_util.exe_exists')
def test_simple_success(self, mock_exe_exists):
mock_exe_exists.return_value = True
self._call('foo')
@mock.patch('certbot_postfix.util.certbot_util.exe_exists')
@mock.patch('certbot_postfix.util.plugins_util.path_surgery')
def test_successful_surgery(self, mock_exe_exists, mock_path_surgery):
mock_exe_exists.return_value = False
mock_path_surgery.return_value = True
self._call('foo')
class TestUtils(unittest.TestCase):
""" Testing random utility functions in util.py
"""
def test_report_master_overrides(self):
from certbot_postfix.util import report_master_overrides
self.assertRaises(errors.PluginError, report_master_overrides, 'name',
[('service/type', 'value')])
# Shouldn't raise error
report_master_overrides('name', [('service/type', 'value')],
acceptable_overrides=('value',))
def test_no_acceptable_value(self):
from certbot_postfix.util import is_acceptable_value
self.assertFalse(is_acceptable_value('name', 'value', None))
def test_is_acceptable_value(self):
from certbot_postfix.util import is_acceptable_value
self.assertTrue(is_acceptable_value('name', 'value', ('value',)))
self.assertFalse(is_acceptable_value('name', 'bad', ('value',)))
def test_is_acceptable_tuples(self):
from certbot_postfix.util import is_acceptable_value
self.assertTrue(is_acceptable_value('name', 'value', ('value', 'value1')))
self.assertFalse(is_acceptable_value('name', 'bad', ('value', 'value1')))
def test_is_acceptable_protocols(self):
from certbot_postfix.util import is_acceptable_value
# SSLv2 and SSLv3 are both not supported, unambiguously
self.assertFalse(is_acceptable_value('tls_mandatory_protocols_lol',
'SSLv2, SSLv3', None))
self.assertFalse(is_acceptable_value('tls_protocols_lol',
'SSLv2, SSLv3', None))
self.assertFalse(is_acceptable_value('tls_protocols_lol',
'!SSLv2, !TLSv1', None))
self.assertFalse(is_acceptable_value('tls_protocols_lol',
'!SSLv2, SSLv3, !SSLv3, ', None))
self.assertTrue(is_acceptable_value('tls_protocols_lol',
'!SSLv2, !SSLv3', None))
self.assertTrue(is_acceptable_value('tls_protocols_lol',
'!SSLv3, !TLSv1, !SSLv2', None))
# TLSv1.2 is supported unambiguously
self.assertFalse(is_acceptable_value('tls_protocols_lol',
'TLSv1, TLSv1.1,', None))
self.assertFalse(is_acceptable_value('tls_protocols_lol',
'TLSv1.2, !TLSv1.2,', None))
self.assertTrue(is_acceptable_value('tls_protocols_lol',
'TLSv1.2, ', None))
self.assertTrue(is_acceptable_value('tls_protocols_lol',
'TLSv1, TLSv1.1, TLSv1.2', None))
if __name__ == '__main__': # pragma: no cover
unittest.main()
| apache-2.0 | 6,808,568,070,437,608,000 | 40.263415 | 83 | 0.650313 | false |
vitchyr/rlkit | rlkit/samplers/data_collector/joint_path_collector.py | 1 | 1496 | from collections import OrderedDict
from typing import Dict
from rlkit.core.logging import add_prefix
from rlkit.samplers.data_collector import PathCollector
class JointPathCollector(PathCollector):
def __init__(self, path_collectors: Dict[str, PathCollector]):
self.path_collectors = path_collectors
def collect_new_paths(self, max_path_length, num_steps,
discard_incomplete_paths):
paths = []
for collector in self.path_collectors.values():
collector.collect_new_paths(
max_path_length, num_steps, discard_incomplete_paths
)
return paths
def end_epoch(self, epoch):
for collector in self.path_collectors.values():
collector.end_epoch(epoch)
def get_diagnostics(self):
diagnostics = OrderedDict()
for name, collector in self.path_collectors.items():
diagnostics.update(
add_prefix(collector.get_diagnostics(), name, divider='/'),
)
return diagnostics
def get_snapshot(self):
snapshot = {}
for name, collector in self.path_collectors.items():
snapshot.update(
add_prefix(collector.get_snapshot(), name, divider='/'),
)
return snapshot
def get_epoch_paths(self):
paths = {}
for name, collector in self.path_collectors.items():
paths[name] = collector.get_epoch_paths()
return paths
| mit | 7,327,262,835,724,147,000 | 31.521739 | 75 | 0.614305 | false |
lyudmildrx/lymph | lymph/core/messages.py | 9 | 3538 | from lymph.serializers import msgpack_serializer
from lymph.utils import make_id
class Message(object):
ACK = b'ACK'
REP = b'REP'
REQ = b'REQ'
NACK = b'NACK'
ERROR = b'ERROR'
def __init__(self, msg_type, subject, packed_body=None, headers=None, packed_headers=None, msg_id=None, source=None, lazy=False, **kwargs):
self.id = msg_id if msg_id else make_id()
self.type = msg_type
self.subject = subject
self.source = source
if headers and packed_headers:
raise TypeError("Message takes either 'headers' or 'packed_headers' not both")
elif not headers and not packed_headers:
headers = {}
self._headers = headers
self._packed_headers = packed_headers
if 'body' in kwargs:
if packed_body is not None:
raise TypeError("Message takes either 'body' or 'packed_body' not both")
self._body = kwargs['body']
elif packed_body is None:
raise TypeError("Message requires either 'body' or 'packed_body'")
self._packed_body = packed_body
if not lazy:
self.body
self.packed_body
self.headers
self.packed_headers
def is_request(self):
return self.type == self.REQ
def is_reply(self):
return self.type in (self.REP, self.ACK, self.NACK, self.ERROR)
def is_idle_chatter(self):
return not self.is_request() or self.subject == '_ping'
@property
def body(self):
if not hasattr(self, '_body'):
self._body = msgpack_serializer.loads(self._packed_body)
return self._body
@property
def packed_body(self):
if self._packed_body is None:
self._packed_body = msgpack_serializer.dumps(self._body)
return self._packed_body
@property
def headers(self):
if self._headers is None:
self._headers = msgpack_serializer.loads(self._packed_headers)
return self._headers
@property
def packed_headers(self):
if self._packed_headers is None:
self._packed_headers = msgpack_serializer.dumps(self._headers)
return self._packed_headers
def pack_frames(self):
return [
self.id.encode('utf-8'),
self.type,
self.subject.encode('utf-8'),
self.packed_headers,
self.packed_body,
]
@classmethod
def unpack_frames(self, frames):
try:
source, msg_id, msg_type, subject, headers, body = frames
except ValueError:
raise ValueError('bad message frame count: got %s, expected 6' % len(frames))
try:
msg_id = msg_id.decode('utf-8')
subject = subject.decode('utf-8')
source = source.decode('utf-8')
except UnicodeDecodeError:
raise ValueError('message id, subject, and source must be utf-8 encoded.')
return Message(
msg_type=msg_type,
subject=subject,
msg_id=msg_id,
source=source,
packed_body=body,
packed_headers=headers,
)
def __str__(self):
return '{type=%s subject=%s id=%s..}' % (
self.type,
self.subject,
self.id[:10],
)
def __repr__(self):
return '<Message id=%s type=%s subject=%s body=%r>' % (
self.id,
self.type,
self.subject,
self.body,
)
| apache-2.0 | 3,347,379,366,710,842,400 | 29.239316 | 143 | 0.559073 | false |
itkovian/sqlalchemy | test/sql/test_quote.py | 28 | 30468 | from sqlalchemy import *
from sqlalchemy import sql, schema
from sqlalchemy.sql import compiler
from sqlalchemy.testing import fixtures, AssertsCompiledSQL, eq_
from sqlalchemy import testing
from sqlalchemy.sql.elements import quoted_name, _truncated_label, _anonymous_label
from sqlalchemy.testing.util import picklers
class QuoteExecTest(fixtures.TestBase):
__backend__ = True
@classmethod
def setup_class(cls):
# TODO: figure out which databases/which identifiers allow special
# characters to be used, such as: spaces, quote characters,
# punctuation characters, set up tests for those as well.
global table1, table2
metadata = MetaData(testing.db)
table1 = Table('WorstCase1', metadata,
Column('lowercase', Integer, primary_key=True),
Column('UPPERCASE', Integer),
Column('MixedCase', Integer),
Column('ASC', Integer, key='a123'))
table2 = Table('WorstCase2', metadata,
Column('desc', Integer, primary_key=True, key='d123'),
Column('Union', Integer, key='u123'),
Column('MixedCase', Integer))
table1.create()
table2.create()
def teardown(self):
table1.delete().execute()
table2.delete().execute()
@classmethod
def teardown_class(cls):
table1.drop()
table2.drop()
def test_reflect(self):
meta2 = MetaData(testing.db)
t2 = Table('WorstCase1', meta2, autoload=True, quote=True)
assert 'lowercase' in t2.c
# indicates the DB returns unquoted names as
# UPPERCASE, which we then assume are unquoted and go to
# lower case. So we cannot accurately reflect quoted UPPERCASE
# names from a "name normalize" backend, as they cannot be
# distinguished from case-insensitive/unquoted names.
if testing.db.dialect.requires_name_normalize:
assert 'uppercase' in t2.c
else:
assert 'UPPERCASE' in t2.c
# ASC OTOH is a reserved word, which is always quoted, so
# with that name we keep the quotes on and it stays uppercase
# regardless. Seems a little weird, though.
assert 'ASC' in t2.c
assert 'MixedCase' in t2.c
@testing.provide_metadata
def test_has_table_case_sensitive(self):
preparer = testing.db.dialect.identifier_preparer
if testing.db.dialect.requires_name_normalize:
testing.db.execute("CREATE TABLE TAB1 (id INTEGER)")
else:
testing.db.execute("CREATE TABLE tab1 (id INTEGER)")
testing.db.execute('CREATE TABLE %s (id INTEGER)' %
preparer.quote_identifier("tab2"))
testing.db.execute('CREATE TABLE %s (id INTEGER)' %
preparer.quote_identifier("TAB3"))
testing.db.execute('CREATE TABLE %s (id INTEGER)' %
preparer.quote_identifier("TAB4"))
t1 = Table('tab1', self.metadata,
Column('id', Integer, primary_key=True),
)
t2 = Table('tab2', self.metadata,
Column('id', Integer, primary_key=True),
quote=True
)
t3 = Table('TAB3', self.metadata,
Column('id', Integer, primary_key=True),
)
t4 = Table('TAB4', self.metadata,
Column('id', Integer, primary_key=True),
quote=True)
insp = inspect(testing.db)
assert testing.db.has_table(t1.name)
eq_([c['name'] for c in insp.get_columns(t1.name)], ['id'])
assert testing.db.has_table(t2.name)
eq_([c['name'] for c in insp.get_columns(t2.name)], ['id'])
assert testing.db.has_table(t3.name)
eq_([c['name'] for c in insp.get_columns(t3.name)], ['id'])
assert testing.db.has_table(t4.name)
eq_([c['name'] for c in insp.get_columns(t4.name)], ['id'])
def test_basic(self):
table1.insert().execute(
{'lowercase': 1, 'UPPERCASE': 2, 'MixedCase': 3, 'a123': 4},
{'lowercase': 2, 'UPPERCASE': 2, 'MixedCase': 3, 'a123': 4},
{'lowercase': 4, 'UPPERCASE': 3, 'MixedCase': 2, 'a123': 1})
table2.insert().execute(
{'d123': 1, 'u123': 2, 'MixedCase': 3},
{'d123': 2, 'u123': 2, 'MixedCase': 3},
{'d123': 4, 'u123': 3, 'MixedCase': 2})
columns = [
table1.c.lowercase,
table1.c.UPPERCASE,
table1.c.MixedCase,
table1.c.a123
]
result = select(columns).execute().fetchall()
assert(result == [(1, 2, 3, 4), (2, 2, 3, 4), (4, 3, 2, 1)])
columns = [
table2.c.d123,
table2.c.u123,
table2.c.MixedCase
]
result = select(columns).execute().fetchall()
assert(result == [(1, 2, 3), (2, 2, 3), (4, 3, 2)])
def test_use_labels(self):
table1.insert().execute(
{'lowercase': 1, 'UPPERCASE': 2, 'MixedCase': 3, 'a123': 4},
{'lowercase': 2, 'UPPERCASE': 2, 'MixedCase': 3, 'a123': 4},
{'lowercase': 4, 'UPPERCASE': 3, 'MixedCase': 2, 'a123': 1})
table2.insert().execute(
{'d123': 1, 'u123': 2, 'MixedCase': 3},
{'d123': 2, 'u123': 2, 'MixedCase': 3},
{'d123': 4, 'u123': 3, 'MixedCase': 2})
columns = [
table1.c.lowercase,
table1.c.UPPERCASE,
table1.c.MixedCase,
table1.c.a123
]
result = select(columns, use_labels=True).execute().fetchall()
assert(result == [(1, 2, 3, 4), (2, 2, 3, 4), (4, 3, 2, 1)])
columns = [
table2.c.d123,
table2.c.u123,
table2.c.MixedCase
]
result = select(columns, use_labels=True).execute().fetchall()
assert(result == [(1, 2, 3), (2, 2, 3), (4, 3, 2)])
class QuoteTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'default'
@classmethod
def setup_class(cls):
# TODO: figure out which databases/which identifiers allow special
# characters to be used, such as: spaces, quote characters,
# punctuation characters, set up tests for those as well.
global table1, table2
metadata = MetaData(testing.db)
table1 = Table('WorstCase1', metadata,
Column('lowercase', Integer, primary_key=True),
Column('UPPERCASE', Integer),
Column('MixedCase', Integer),
Column('ASC', Integer, key='a123'))
table2 = Table('WorstCase2', metadata,
Column('desc', Integer, primary_key=True, key='d123'),
Column('Union', Integer, key='u123'),
Column('MixedCase', Integer))
@testing.crashes('oracle', 'FIXME: unknown, verify not fails_on')
@testing.requires.subqueries
def test_labels(self):
"""test the quoting of labels.
If labels aren't quoted, a query in postgresql in particular will
fail since it produces:
SELECT
LaLa.lowercase, LaLa."UPPERCASE", LaLa."MixedCase", LaLa."ASC"
FROM (
SELECT DISTINCT
"WorstCase1".lowercase AS lowercase,
"WorstCase1"."UPPERCASE" AS UPPERCASE,
"WorstCase1"."MixedCase" AS MixedCase,
"WorstCase1"."ASC" AS ASC
FROM "WorstCase1"
) AS LaLa
where the "UPPERCASE" column of "LaLa" doesn't exist.
"""
self.assert_compile(
table1.select(distinct=True).alias('LaLa').select(),
'SELECT '
'"LaLa".lowercase, '
'"LaLa"."UPPERCASE", '
'"LaLa"."MixedCase", '
'"LaLa"."ASC" '
'FROM ('
'SELECT DISTINCT '
'"WorstCase1".lowercase AS lowercase, '
'"WorstCase1"."UPPERCASE" AS "UPPERCASE", '
'"WorstCase1"."MixedCase" AS "MixedCase", '
'"WorstCase1"."ASC" AS "ASC" '
'FROM "WorstCase1"'
') AS "LaLa"'
)
def test_lower_case_names(self):
# Create table with quote defaults
metadata = MetaData()
t1 = Table('t1', metadata,
Column('col1', Integer),
schema='foo')
# Note that the names are not quoted b/c they are all lower case
result = 'CREATE TABLE foo.t1 (col1 INTEGER)'
self.assert_compile(schema.CreateTable(t1), result)
# Create the same table with quotes set to True now
metadata = MetaData()
t1 = Table('t1', metadata,
Column('col1', Integer, quote=True),
schema='foo', quote=True, quote_schema=True)
# Note that the names are now quoted
result = 'CREATE TABLE "foo"."t1" ("col1" INTEGER)'
self.assert_compile(schema.CreateTable(t1), result)
def test_upper_case_names(self):
# Create table with quote defaults
metadata = MetaData()
t1 = Table('TABLE1', metadata,
Column('COL1', Integer),
schema='FOO')
# Note that the names are quoted b/c they are not all lower case
result = 'CREATE TABLE "FOO"."TABLE1" ("COL1" INTEGER)'
self.assert_compile(schema.CreateTable(t1), result)
# Create the same table with quotes set to False now
metadata = MetaData()
t1 = Table('TABLE1', metadata,
Column('COL1', Integer, quote=False),
schema='FOO', quote=False, quote_schema=False)
# Note that the names are now unquoted
result = 'CREATE TABLE FOO.TABLE1 (COL1 INTEGER)'
self.assert_compile(schema.CreateTable(t1), result)
def test_mixed_case_names(self):
# Create table with quote defaults
metadata = MetaData()
t1 = Table('Table1', metadata,
Column('Col1', Integer),
schema='Foo')
# Note that the names are quoted b/c they are not all lower case
result = 'CREATE TABLE "Foo"."Table1" ("Col1" INTEGER)'
self.assert_compile(schema.CreateTable(t1), result)
# Create the same table with quotes set to False now
metadata = MetaData()
t1 = Table('Table1', metadata,
Column('Col1', Integer, quote=False),
schema='Foo', quote=False, quote_schema=False)
# Note that the names are now unquoted
result = 'CREATE TABLE Foo.Table1 (Col1 INTEGER)'
self.assert_compile(schema.CreateTable(t1), result)
def test_numeric_initial_char(self):
# Create table with quote defaults
metadata = MetaData()
t1 = Table('35table', metadata,
Column('25column', Integer),
schema='45schema')
# Note that the names are quoted b/c the initial
# character is in ['$','0', '1' ... '9']
result = 'CREATE TABLE "45schema"."35table" ("25column" INTEGER)'
self.assert_compile(schema.CreateTable(t1), result)
# Create the same table with quotes set to False now
metadata = MetaData()
t1 = Table('35table', metadata,
Column('25column', Integer, quote=False),
schema='45schema', quote=False, quote_schema=False)
# Note that the names are now unquoted
result = 'CREATE TABLE 45schema.35table (25column INTEGER)'
self.assert_compile(schema.CreateTable(t1), result)
def test_illegal_initial_char(self):
# Create table with quote defaults
metadata = MetaData()
t1 = Table('$table', metadata,
Column('$column', Integer),
schema='$schema')
# Note that the names are quoted b/c the initial
# character is in ['$','0', '1' ... '9']
result = 'CREATE TABLE "$schema"."$table" ("$column" INTEGER)'
self.assert_compile(schema.CreateTable(t1), result)
# Create the same table with quotes set to False now
metadata = MetaData()
t1 = Table('$table', metadata,
Column('$column', Integer, quote=False),
schema='$schema', quote=False, quote_schema=False)
# Note that the names are now unquoted
result = 'CREATE TABLE $schema.$table ($column INTEGER)'
self.assert_compile(schema.CreateTable(t1), result)
def test_reserved_words(self):
# Create table with quote defaults
metadata = MetaData()
table = Table('foreign', metadata,
Column('col1', Integer),
Column('from', Integer),
Column('order', Integer),
schema='create')
# Note that the names are quoted b/c they are reserved words
x = select([table.c.col1, table.c['from'], table.c.order])
self.assert_compile(x,
'SELECT '
'"create"."foreign".col1, '
'"create"."foreign"."from", '
'"create"."foreign"."order" '
'FROM "create"."foreign"'
)
# Create the same table with quotes set to False now
metadata = MetaData()
table = Table('foreign', metadata,
Column('col1', Integer),
Column('from', Integer, quote=False),
Column('order', Integer, quote=False),
schema='create', quote=False, quote_schema=False)
# Note that the names are now unquoted
x = select([table.c.col1, table.c['from'], table.c.order])
self.assert_compile(x,
'SELECT '
'create.foreign.col1, '
'create.foreign.from, '
'create.foreign.order '
'FROM create.foreign'
)
def test_subquery_one(self):
# Lower case names, should not quote
metadata = MetaData()
t1 = Table('t1', metadata,
Column('col1', Integer),
schema='foo')
a = t1.select().alias('anon')
b = select([1], a.c.col1 == 2, from_obj=a)
self.assert_compile(b,
'SELECT 1 '
'FROM ('
'SELECT '
'foo.t1.col1 AS col1 '
'FROM '
'foo.t1'
') AS anon '
'WHERE anon.col1 = :col1_1'
)
def test_subquery_two(self):
# Lower case names, quotes on, should quote
metadata = MetaData()
t1 = Table('t1', metadata,
Column('col1', Integer, quote=True),
schema='foo', quote=True, quote_schema=True)
a = t1.select().alias('anon')
b = select([1], a.c.col1 == 2, from_obj=a)
self.assert_compile(b,
'SELECT 1 '
'FROM ('
'SELECT '
'"foo"."t1"."col1" AS "col1" '
'FROM '
'"foo"."t1"'
') AS anon '
'WHERE anon."col1" = :col1_1'
)
def test_subquery_three(self):
# Not lower case names, should quote
metadata = MetaData()
t1 = Table('T1', metadata,
Column('Col1', Integer),
schema='Foo')
a = t1.select().alias('Anon')
b = select([1], a.c.Col1 == 2, from_obj=a)
self.assert_compile(b,
'SELECT 1 '
'FROM ('
'SELECT '
'"Foo"."T1"."Col1" AS "Col1" '
'FROM '
'"Foo"."T1"'
') AS "Anon" '
'WHERE '
'"Anon"."Col1" = :Col1_1'
)
def test_subquery_four(self):
# Not lower case names, quotes off, should not quote
metadata = MetaData()
t1 = Table('T1', metadata,
Column('Col1', Integer, quote=False),
schema='Foo', quote=False, quote_schema=False)
a = t1.select().alias('Anon')
b = select([1], a.c.Col1 == 2, from_obj=a)
self.assert_compile(b,
'SELECT 1 '
'FROM ('
'SELECT '
'Foo.T1.Col1 AS Col1 '
'FROM '
'Foo.T1'
') AS "Anon" '
'WHERE '
'"Anon".Col1 = :Col1_1'
)
def test_simple_order_by_label(self):
m = MetaData()
t1 = Table('t1', m, Column('col1', Integer))
cl = t1.c.col1.label('ShouldQuote')
self.assert_compile(
select([cl]).order_by(cl),
'SELECT t1.col1 AS "ShouldQuote" FROM t1 ORDER BY "ShouldQuote"'
)
def test_join(self):
# Lower case names, should not quote
metadata = MetaData()
t1 = Table('t1', metadata,
Column('col1', Integer))
t2 = Table('t2', metadata,
Column('col1', Integer),
Column('t1col1', Integer, ForeignKey('t1.col1')))
self.assert_compile(t2.join(t1).select(),
'SELECT '
't2.col1, t2.t1col1, t1.col1 '
'FROM '
't2 '
'JOIN '
't1 ON t1.col1 = t2.t1col1'
)
# Lower case names, quotes on, should quote
metadata = MetaData()
t1 = Table('t1', metadata,
Column('col1', Integer, quote=True),
quote=True)
t2 = Table(
't2',
metadata,
Column(
'col1',
Integer,
quote=True),
Column(
't1col1',
Integer,
ForeignKey('t1.col1'),
quote=True),
quote=True)
self.assert_compile(t2.join(t1).select(),
'SELECT '
'"t2"."col1", "t2"."t1col1", "t1"."col1" '
'FROM '
'"t2" '
'JOIN '
'"t1" ON "t1"."col1" = "t2"."t1col1"'
)
# Not lower case names, should quote
metadata = MetaData()
t1 = Table('T1', metadata,
Column('Col1', Integer))
t2 = Table('T2', metadata,
Column('Col1', Integer),
Column('T1Col1', Integer, ForeignKey('T1.Col1')))
self.assert_compile(t2.join(t1).select(),
'SELECT '
'"T2"."Col1", "T2"."T1Col1", "T1"."Col1" '
'FROM '
'"T2" '
'JOIN '
'"T1" ON "T1"."Col1" = "T2"."T1Col1"'
)
# Not lower case names, quotes off, should not quote
metadata = MetaData()
t1 = Table('T1', metadata,
Column('Col1', Integer, quote=False),
quote=False)
t2 = Table(
'T2',
metadata,
Column(
'Col1',
Integer,
quote=False),
Column(
'T1Col1',
Integer,
ForeignKey('T1.Col1'),
quote=False),
quote=False)
self.assert_compile(t2.join(t1).select(),
'SELECT '
'T2.Col1, T2.T1Col1, T1.Col1 '
'FROM '
'T2 '
'JOIN '
'T1 ON T1.Col1 = T2.T1Col1'
)
def test_label_and_alias(self):
# Lower case names, should not quote
metadata = MetaData()
table = Table('t1', metadata,
Column('col1', Integer))
x = select([table.c.col1.label('label1')]).alias('alias1')
self.assert_compile(select([x.c.label1]),
'SELECT '
'alias1.label1 '
'FROM ('
'SELECT '
't1.col1 AS label1 '
'FROM t1'
') AS alias1'
)
# Not lower case names, should quote
metadata = MetaData()
table = Table('T1', metadata,
Column('Col1', Integer))
x = select([table.c.Col1.label('Label1')]).alias('Alias1')
self.assert_compile(select([x.c.Label1]),
'SELECT '
'"Alias1"."Label1" '
'FROM ('
'SELECT '
'"T1"."Col1" AS "Label1" '
'FROM "T1"'
') AS "Alias1"'
)
def test_literal_column_already_with_quotes(self):
# Lower case names
metadata = MetaData()
table = Table('t1', metadata,
Column('col1', Integer))
# Note that 'col1' is already quoted (literal_column)
columns = [sql.literal_column("'col1'").label('label1')]
x = select(columns, from_obj=[table]).alias('alias1')
x = x.select()
self.assert_compile(x,
'SELECT '
'alias1.label1 '
'FROM ('
'SELECT '
'\'col1\' AS label1 '
'FROM t1'
') AS alias1'
)
# Not lower case names
metadata = MetaData()
table = Table('T1', metadata,
Column('Col1', Integer))
# Note that 'Col1' is already quoted (literal_column)
columns = [sql.literal_column("'Col1'").label('Label1')]
x = select(columns, from_obj=[table]).alias('Alias1')
x = x.select()
self.assert_compile(x,
'SELECT '
'"Alias1"."Label1" '
'FROM ('
'SELECT '
'\'Col1\' AS "Label1" '
'FROM "T1"'
') AS "Alias1"'
)
def test_apply_labels_should_quote(self):
# Not lower case names, should quote
metadata = MetaData()
t1 = Table('T1', metadata,
Column('Col1', Integer),
schema='Foo')
self.assert_compile(t1.select().apply_labels(),
'SELECT '
'"Foo"."T1"."Col1" AS "Foo_T1_Col1" '
'FROM '
'"Foo"."T1"'
)
def test_apply_labels_shouldnt_quote(self):
# Not lower case names, quotes off
metadata = MetaData()
t1 = Table('T1', metadata,
Column('Col1', Integer, quote=False),
schema='Foo', quote=False, quote_schema=False)
# TODO: is this what we really want here ?
# what if table/schema *are* quoted?
self.assert_compile(t1.select().apply_labels(),
'SELECT '
'Foo.T1.Col1 AS Foo_T1_Col1 '
'FROM '
'Foo.T1'
)
def test_quote_flag_propagate_check_constraint(self):
m = MetaData()
t = Table('t', m, Column('x', Integer, quote=True))
CheckConstraint(t.c.x > 5)
self.assert_compile(
schema.CreateTable(t),
"CREATE TABLE t ("
'"x" INTEGER, '
'CHECK ("x" > 5)'
")"
)
def test_quote_flag_propagate_index(self):
m = MetaData()
t = Table('t', m, Column('x', Integer, quote=True))
idx = Index("foo", t.c.x)
self.assert_compile(
schema.CreateIndex(idx),
'CREATE INDEX foo ON t ("x")'
)
def test_quote_flag_propagate_anon_label(self):
m = MetaData()
t = Table('t', m, Column('x', Integer, quote=True))
self.assert_compile(
select([t.alias()]).apply_labels(),
'SELECT t_1."x" AS "t_1_x" FROM t AS t_1'
)
t2 = Table('t2', m, Column('x', Integer), quote=True)
self.assert_compile(
select([t2.c.x]).apply_labels(),
'SELECT "t2".x AS "t2_x" FROM "t2"'
)
class PreparerTest(fixtures.TestBase):
"""Test the db-agnostic quoting services of IdentifierPreparer."""
def test_unformat(self):
prep = compiler.IdentifierPreparer(None)
unformat = prep.unformat_identifiers
def a_eq(have, want):
if have != want:
print("Wanted %s" % want)
print("Received %s" % have)
self.assert_(have == want)
a_eq(unformat('foo'), ['foo'])
a_eq(unformat('"foo"'), ['foo'])
a_eq(unformat("'foo'"), ["'foo'"])
a_eq(unformat('foo.bar'), ['foo', 'bar'])
a_eq(unformat('"foo"."bar"'), ['foo', 'bar'])
a_eq(unformat('foo."bar"'), ['foo', 'bar'])
a_eq(unformat('"foo".bar'), ['foo', 'bar'])
a_eq(unformat('"foo"."b""a""r"."baz"'), ['foo', 'b"a"r', 'baz'])
def test_unformat_custom(self):
class Custom(compiler.IdentifierPreparer):
def __init__(self, dialect):
super(Custom, self).__init__(
dialect, initial_quote='`', final_quote='`')
def _escape_identifier(self, value):
return value.replace('`', '``')
def _unescape_identifier(self, value):
return value.replace('``', '`')
prep = Custom(None)
unformat = prep.unformat_identifiers
def a_eq(have, want):
if have != want:
print("Wanted %s" % want)
print("Received %s" % have)
self.assert_(have == want)
a_eq(unformat('foo'), ['foo'])
a_eq(unformat('`foo`'), ['foo'])
a_eq(unformat(repr('foo')), ["'foo'"])
a_eq(unformat('foo.bar'), ['foo', 'bar'])
a_eq(unformat('`foo`.`bar`'), ['foo', 'bar'])
a_eq(unformat('foo.`bar`'), ['foo', 'bar'])
a_eq(unformat('`foo`.bar'), ['foo', 'bar'])
a_eq(unformat('`foo`.`b``a``r`.`baz`'), ['foo', 'b`a`r', 'baz'])
class QuotedIdentTest(fixtures.TestBase):
def test_concat_quotetrue(self):
q1 = quoted_name("x", True)
self._assert_not_quoted("y" + q1)
def test_concat_quotefalse(self):
q1 = quoted_name("x", False)
self._assert_not_quoted("y" + q1)
def test_concat_quotenone(self):
q1 = quoted_name("x", None)
self._assert_not_quoted("y" + q1)
def test_rconcat_quotetrue(self):
q1 = quoted_name("x", True)
self._assert_not_quoted("y" + q1)
def test_rconcat_quotefalse(self):
q1 = quoted_name("x", False)
self._assert_not_quoted("y" + q1)
def test_rconcat_quotenone(self):
q1 = quoted_name("x", None)
self._assert_not_quoted("y" + q1)
def test_concat_anon(self):
q1 = _anonymous_label(quoted_name("x", True))
assert isinstance(q1, _anonymous_label)
value = q1 + "y"
assert isinstance(value, _anonymous_label)
self._assert_quoted(value, True)
def test_rconcat_anon(self):
q1 = _anonymous_label(quoted_name("x", True))
assert isinstance(q1, _anonymous_label)
value = "y" + q1
assert isinstance(value, _anonymous_label)
self._assert_quoted(value, True)
def test_coerce_quoted_switch(self):
q1 = quoted_name("x", False)
q2 = quoted_name(q1, True)
eq_(q2.quote, True)
def test_coerce_quoted_none(self):
q1 = quoted_name("x", False)
q2 = quoted_name(q1, None)
eq_(q2.quote, False)
def test_coerce_quoted_retain(self):
q1 = quoted_name("x", False)
q2 = quoted_name(q1, False)
eq_(q2.quote, False)
def test_coerce_none(self):
q1 = quoted_name(None, False)
eq_(q1, None)
def test_apply_map_quoted(self):
q1 = _anonymous_label(quoted_name("x%s", True))
q2 = q1.apply_map(('bar'))
eq_(q2, "xbar")
eq_(q2.quote, True)
def test_apply_map_plain(self):
q1 = _anonymous_label(quoted_name("x%s", None))
q2 = q1.apply_map(('bar'))
eq_(q2, "xbar")
self._assert_not_quoted(q2)
def test_pickle_quote(self):
q1 = quoted_name("x", True)
for loads, dumps in picklers():
q2 = loads(dumps(q1))
eq_(str(q1), str(q2))
eq_(q1.quote, q2.quote)
def test_pickle_anon_label(self):
q1 = _anonymous_label(quoted_name("x", True))
for loads, dumps in picklers():
q2 = loads(dumps(q1))
assert isinstance(q2, _anonymous_label)
eq_(str(q1), str(q2))
eq_(q1.quote, q2.quote)
def _assert_quoted(self, value, quote):
assert isinstance(value, quoted_name)
eq_(value.quote, quote)
def _assert_not_quoted(self, value):
assert not isinstance(value, quoted_name)
| mit | -6,763,621,555,474,009,000 | 35.886199 | 83 | 0.476401 | false |
leonsio/YAHM | share/tools/ubi_reader/ubifs_extract_files.py | 2 | 3501 | #!/usr/bin/env python
#############################################################
# ubi_reader
# (c) 2013 Jason Pruitt ([email protected])
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#############################################################
import os
import sys
import argparse
from ubi_io import ubi_file
from ubifs import ubifs, get_leb_size
from ui.common import extract_files, output_dir
if __name__ == '__main__':
description = """Extract file contents of UBIFS image."""
usage = 'ubifs_extract_files.py [options] filepath'
parser = argparse.ArgumentParser(usage=usage, description=description)
parser.add_argument('-l', '--log-file', dest='logpath',
help='Log output to file output/LOGPATH. (default: ubifs_output.log)')
parser.add_argument('-k', '--keep-permissions', action='store_true', dest='permissions',
help='Maintain file permissions, requires running as root. (default: False)')
parser.add_argument('-q', '--quiet', action='store_true', dest='quiet',
help='Suppress warnings and non-fatal errors. (default: False)')
parser.add_argument('-e', '--leb-size', type=int, dest='block_size',
help='Specify LEB size.')
parser.add_argument('-o', '--output-dir', dest='output_path',
help='Specify output directory path.')
parser.add_argument('filepath', help='File to extract file contents of.')
if len(sys.argv) == 1:
parser.print_help()
sys.exit()
args = parser.parse_args()
if args.filepath:
path = args.filepath
if not os.path.exists(path):
parser.error("File path doesn't exist.")
if args.output_path:
output_path = args.output_path
else:
img_name = os.path.splitext(os.path.basename(path))[0]
output_path = os.path.join(output_dir, img_name)
if args.logpath:
log_to_file = True
log_file = args.logpath
else:
log_to_file = None
log_file = None
# Determine block size if not provided
if args.block_size:
block_size = args.block_size
else:
block_size = get_leb_size(path)
if not os.path.exists(output_path):
os.makedirs(output_path)
perms = args.permissions
quiet = args.quiet
# Create file object
ufsfile = ubi_file(path, block_size)
# Create UBIFS object
uubifs = ubifs(ufsfile)
# Set up logging
uubifs.log.log_file = log_file
uubifs.log.log_to_file = log_to_file
uubifs.quiet = quiet
if not os.path.exists(output_path):
os.makedirs(output_path)
elif os.listdir(output_path):
parser.error('Volume output directory is not empty. %s' % output_path)
# Run extract all files
print 'Writing to: %s' % output_path
extract_files(uubifs, output_path, perms)
sys.exit()
| cc0-1.0 | -603,511,571,833,712,600 | 32.663462 | 99 | 0.622394 | false |
cmdunkers/DeeperMind | PythonEnv/lib/python2.7/site-packages/scipy/sparse/linalg/interface.py | 26 | 20931 | """Abstract linear algebra library.
This module defines a class hierarchy that implements a kind of "lazy"
matrix representation, called the ``LinearOperator``. It can be used to do
linear algebra with extremely large sparse or structured matrices, without
representing those explicitly in memory. Such matrices can be added,
multiplied, transposed, etc.
As a motivating example, suppose you want have a matrix where almost all of
the elements have the value one. The standard sparse matrix representation
skips the storage of zeros, but not ones. By contrast, a LinearOperator is
able to represent such matrices efficiently. First, we need a compact way to
represent an all-ones matrix::
>>> import numpy as np
>>> class Ones(LinearOperator):
... def __init__(self, shape):
... super(Ones, self).__init__(dtype=None, shape=shape)
... def _matvec(self, x):
... return np.repeat(x.sum(), self.shape[0])
Instances of this class emulate ``np.ones(shape)``, but using a constant
amount of storage, independent of ``shape``. The ``_matvec`` method specifies
how this linear operator multiplies with (operates on) a vector. We can now
add this operator to a sparse matrix that stores only offsets from one::
>>> from scipy.sparse import csr_matrix
>>> offsets = csr_matrix([[1, 0, 2], [0, -1, 0], [0, 0, 3]])
>>> A = aslinearoperator(offsets) + Ones(offsets.shape)
>>> A.dot([1, 2, 3])
array([13, 4, 15])
The result is the same as that given by its dense, explicitly-stored
counterpart::
>>> (np.ones(A.shape, A.dtype) + offsets.toarray()).dot([1, 2, 3])
array([13, 4, 15])
Several algorithms in the ``scipy.sparse`` library are able to operate on
``LinearOperator`` instances.
"""
from __future__ import division, print_function, absolute_import
import numpy as np
from scipy.sparse import isspmatrix
from scipy.sparse.sputils import isshape, isintlike
__all__ = ['LinearOperator', 'aslinearoperator']
class LinearOperator(object):
"""Common interface for performing matrix vector products
Many iterative methods (e.g. cg, gmres) do not need to know the
individual entries of a matrix to solve a linear system A*x=b.
Such solvers only require the computation of matrix vector
products, A*v where v is a dense vector. This class serves as
an abstract interface between iterative solvers and matrix-like
objects.
To construct a concrete LinearOperator, either pass appropriate
callables to the constructor of this class, or subclass it.
A subclass must implement either one of the methods ``_matvec``
and ``_matmat``, and the attributes/properties ``shape`` (pair of
integers) and ``dtype`` (may be None). It may call the ``__init__``
on this class to have these attributes validated. Implementing
``_matvec`` automatically implements ``_matmat`` (using a naive
algorithm) and vice-versa.
Optionally, a subclass may implement ``_rmatvec`` or ``_adjoint``
to implement the Hermitian adjoint (conjugate transpose). As with
``_matvec`` and ``_matmat``, implementing either ``_rmatvec`` or
``_adjoint`` implements the other automatically. Implementing
``_adjoint`` is preferable; ``_rmatvec`` is mostly there for
backwards compatibility.
Parameters
----------
shape : tuple
Matrix dimensions (M,N).
matvec : callable f(v)
Returns returns A * v.
rmatvec : callable f(v)
Returns A^H * v, where A^H is the conjugate transpose of A.
matmat : callable f(V)
Returns A * V, where V is a dense matrix with dimensions (N,K).
dtype : dtype
Data type of the matrix.
Attributes
----------
args : tuple
For linear operators describing products etc. of other linear
operators, the operands of the binary operation.
See Also
--------
aslinearoperator : Construct LinearOperators
Notes
-----
The user-defined matvec() function must properly handle the case
where v has shape (N,) as well as the (N,1) case. The shape of
the return type is handled internally by LinearOperator.
LinearOperator instances can also be multiplied, added with each
other and exponentiated, all lazily: the result of these operations
is always a new, composite LinearOperator, that defers linear
operations to the original operators and combines the results.
Examples
--------
>>> import numpy as np
>>> from scipy.sparse.linalg import LinearOperator
>>> def mv(v):
... return np.array([2*v[0], 3*v[1]])
...
>>> A = LinearOperator((2,2), matvec=mv)
>>> A
<2x2 LinearOperator with unspecified dtype>
>>> A.matvec(np.ones(2))
array([ 2., 3.])
>>> A * np.ones(2)
array([ 2., 3.])
"""
def __new__(cls, *args, **kwargs):
if cls is LinearOperator:
# Operate as _CustomLinearOperator factory.
return _CustomLinearOperator(*args, **kwargs)
else:
obj = super(LinearOperator, cls).__new__(cls)
if (type(obj)._matvec == LinearOperator._matvec
and type(obj)._matmat == LinearOperator._matmat):
raise TypeError("LinearOperator subclass should implement"
" at least one of _matvec and _matmat.")
obj.__init__(*args, **kwargs)
return obj
def __init__(self, dtype, shape):
"""Initialize this LinearOperator.
To be called by subclasses. ``dtype`` may be None; ``shape`` should
be convertible to a length-2 tuple.
"""
if dtype is not None:
dtype = np.dtype(dtype)
shape = tuple(shape)
if not isshape(shape):
raise ValueError("invalid shape %r (must be 2-d)" % shape)
self.dtype = dtype
self.shape = shape
def _init_dtype(self):
"""Called from subclasses at the end of the __init__ routine.
"""
if self.dtype is None:
v = np.zeros(self.shape[-1])
self.dtype = np.asarray(self.matvec(v)).dtype
def _matmat(self, X):
"""Default matrix-matrix multiplication handler.
Falls back on the user-defined _matvec method, so defining that will
define matrix multiplication (though in a very suboptimal way).
"""
return np.hstack([self.matvec(col.reshape(-1,1)) for col in X.T])
def _matvec(self, x):
"""Default matrix-vector multiplication handler.
If self is a linear operator of shape (M, N), then this method will
be called on a shape (N,) or (N, 1) ndarray, and should return a
shape (M,) or (M, 1) ndarray.
This default implementation falls back on _matmat, so defining that
will define matrix-vector multiplication as well.
"""
return self.matmat(x.reshape(-1, 1))
def matvec(self, x):
"""Matrix-vector multiplication.
Performs the operation y=A*x where A is an MxN linear
operator and x is a column vector or 1-d array.
Parameters
----------
x : {matrix, ndarray}
An array with shape (N,) or (N,1).
Returns
-------
y : {matrix, ndarray}
A matrix or ndarray with shape (M,) or (M,1) depending
on the type and shape of the x argument.
Notes
-----
This matvec wraps the user-specified matvec routine or overridden
_matvec method to ensure that y has the correct shape and type.
"""
x = np.asanyarray(x)
M,N = self.shape
if x.shape != (N,) and x.shape != (N,1):
raise ValueError('dimension mismatch')
y = self._matvec(x)
if isinstance(x, np.matrix):
y = np.asmatrix(y)
else:
y = np.asarray(y)
if x.ndim == 1:
y = y.reshape(M)
elif x.ndim == 2:
y = y.reshape(M,1)
else:
raise ValueError('invalid shape returned by user-defined matvec()')
return y
def rmatvec(self, x):
"""Adjoint matrix-vector multiplication.
Performs the operation y = A^H * x where A is an MxN linear
operator and x is a column vector or 1-d array.
Parameters
----------
x : {matrix, ndarray}
An array with shape (M,) or (M,1).
Returns
-------
y : {matrix, ndarray}
A matrix or ndarray with shape (N,) or (N,1) depending
on the type and shape of the x argument.
Notes
-----
This rmatvec wraps the user-specified rmatvec routine or overridden
_rmatvec method to ensure that y has the correct shape and type.
"""
x = np.asanyarray(x)
M,N = self.shape
if x.shape != (M,) and x.shape != (M,1):
raise ValueError('dimension mismatch')
y = self._rmatvec(x)
if isinstance(x, np.matrix):
y = np.asmatrix(y)
else:
y = np.asarray(y)
if x.ndim == 1:
y = y.reshape(N)
elif x.ndim == 2:
y = y.reshape(N,1)
else:
raise ValueError('invalid shape returned by user-defined rmatvec()')
return y
def _rmatvec(self, x):
"""Default implementation of _rmatvec; defers to adjoint."""
if type(self)._adjoint == LinearOperator._adjoint:
# _adjoint not overridden, prevent infinite recursion
raise NotImplementedError
else:
return self.H.matvec(x)
def matmat(self, X):
"""Matrix-matrix multiplication.
Performs the operation y=A*X where A is an MxN linear
operator and X dense N*K matrix or ndarray.
Parameters
----------
X : {matrix, ndarray}
An array with shape (N,K).
Returns
-------
Y : {matrix, ndarray}
A matrix or ndarray with shape (M,K) depending on
the type of the X argument.
Notes
-----
This matmat wraps any user-specified matmat routine or overridden
_matmat method to ensure that y has the correct type.
"""
X = np.asanyarray(X)
if X.ndim != 2:
raise ValueError('expected 2-d ndarray or matrix, not %d-d'
% X.ndim)
M,N = self.shape
if X.shape[0] != N:
raise ValueError('dimension mismatch: %r, %r'
% (self.shape, X.shape))
Y = self._matmat(X)
if isinstance(Y, np.matrix):
Y = np.asmatrix(Y)
return Y
def __call__(self, x):
return self*x
def __mul__(self, x):
return self.dot(x)
def dot(self, x):
"""Matrix-matrix or matrix-vector multiplication.
Parameters
----------
x : array_like
1-d or 2-d array, representing a vector or matrix.
Returns
-------
Ax : array
1-d or 2-d array (depending on the shape of x) that represents
the result of applying this linear operator on x.
"""
if isinstance(x, LinearOperator):
return _ProductLinearOperator(self, x)
elif np.isscalar(x):
return _ScaledLinearOperator(self, x)
else:
x = np.asarray(x)
if x.ndim == 1 or x.ndim == 2 and x.shape[1] == 1:
return self.matvec(x)
elif x.ndim == 2:
return self.matmat(x)
else:
raise ValueError('expected 1-d or 2-d array or matrix, got %r'
% x)
def __rmul__(self, x):
if np.isscalar(x):
return _ScaledLinearOperator(self, x)
else:
return NotImplemented
def __pow__(self, p):
if np.isscalar(p):
return _PowerLinearOperator(self, p)
else:
return NotImplemented
def __add__(self, x):
if isinstance(x, LinearOperator):
return _SumLinearOperator(self, x)
else:
return NotImplemented
def __neg__(self):
return _ScaledLinearOperator(self, -1)
def __sub__(self, x):
return self.__add__(-x)
def __repr__(self):
M,N = self.shape
if self.dtype is None:
dt = 'unspecified dtype'
else:
dt = 'dtype=' + str(self.dtype)
return '<%dx%d %s with %s>' % (M, N, self.__class__.__name__, dt)
def adjoint(self):
"""Hermitian adjoint.
Returns the Hermitian adjoint of self, aka the Hermitian
conjugate or Hermitian transpose. For a complex matrix, the
Hermitian adjoint is equal to the conjugate transpose.
Can be abbreviated self.H instead of self.adjoint().
Returns
-------
A_H : LinearOperator
Hermitian adjoint of self.
"""
return self._adjoint()
H = property(adjoint)
def transpose(self):
"""Transpose this linear operator.
Returns a LinearOperator that represents the transpose of this one.
Can be abbreviated self.T instead of self.transpose().
"""
return self._transpose()
T = property(transpose)
def _adjoint(self):
"""Default implementation of _adjoint; defers to rmatvec."""
shape = (self.shape[1], self.shape[0])
return _CustomLinearOperator(shape, matvec=self.rmatvec,
rmatvec=self.matvec,
dtype=self.dtype)
class _CustomLinearOperator(LinearOperator):
"""Linear operator defined in terms of user-specified operations."""
def __init__(self, shape, matvec, rmatvec=None, matmat=None, dtype=None):
super(_CustomLinearOperator, self).__init__(dtype, shape)
self.args = ()
self.__matvec_impl = matvec
self.__rmatvec_impl = rmatvec
self.__matmat_impl = matmat
self._init_dtype()
def _matmat(self, X):
if self.__matmat_impl is not None:
return self.__matmat_impl(X)
else:
return super(_CustomLinearOperator, self)._matmat(X)
def _matvec(self, x):
return self.__matvec_impl(x)
def _rmatvec(self, x):
func = self.__rmatvec_impl
if func is None:
raise NotImplemented("rmatvec is not defined")
return self.__rmatvec_impl(x)
def _adjoint(self):
return _CustomLinearOperator(shape=(self.shape[1], self.shape[0]),
matvec=self.__rmatvec_impl,
rmatvec=self.__matvec_impl,
dtype=self.dtype)
def _get_dtype(operators, dtypes=[]):
for obj in operators:
if obj is not None and hasattr(obj, 'dtype'):
dtypes.append(obj.dtype)
return np.find_common_type(dtypes, [])
class _SumLinearOperator(LinearOperator):
def __init__(self, A, B):
if not isinstance(A, LinearOperator) or \
not isinstance(B, LinearOperator):
raise ValueError('both operands have to be a LinearOperator')
if A.shape != B.shape:
raise ValueError('cannot add %r and %r: shape mismatch'
% (A, B))
self.args = (A, B)
super(_SumLinearOperator, self).__init__(_get_dtype([A, B]), A.shape)
def _matvec(self, x):
return self.args[0].matvec(x) + self.args[1].matvec(x)
def _rmatvec(self, x):
return self.args[0].rmatvec(x) + self.args[1].rmatvec(x)
def _matmat(self, x):
return self.args[0].matmat(x) + self.args[1].matmat(x)
def _adjoint(self):
A, B = self.args
return A.H + B.H
class _ProductLinearOperator(LinearOperator):
def __init__(self, A, B):
if not isinstance(A, LinearOperator) or \
not isinstance(B, LinearOperator):
raise ValueError('both operands have to be a LinearOperator')
if A.shape[1] != B.shape[0]:
raise ValueError('cannot multiply %r and %r: shape mismatch'
% (A, B))
super(_ProductLinearOperator, self).__init__(_get_dtype([A, B]),
(A.shape[0], B.shape[1]))
self.args = (A, B)
def _matvec(self, x):
return self.args[0].matvec(self.args[1].matvec(x))
def _rmatvec(self, x):
return self.args[1].rmatvec(self.args[0].rmatvec(x))
def _matmat(self, x):
return self.args[0].matmat(self.args[1].matmat(x))
def _adjoint(self):
A, B = self.args
return B.H * A.H
class _ScaledLinearOperator(LinearOperator):
def __init__(self, A, alpha):
if not isinstance(A, LinearOperator):
raise ValueError('LinearOperator expected as A')
if not np.isscalar(alpha):
raise ValueError('scalar expected as alpha')
dtype = _get_dtype([A], [type(alpha)])
super(_ScaledLinearOperator, self).__init__(dtype, A.shape)
self.args = (A, alpha)
def _matvec(self, x):
return self.args[1] * self.args[0].matvec(x)
def _rmatvec(self, x):
return np.conj(self.args[1]) * self.args[0].rmatvec(x)
def _matmat(self, x):
return self.args[1] * self.args[0].matmat(x)
def _adjoint(self):
A, alpha = self.args
return A.H * alpha
class _PowerLinearOperator(LinearOperator):
def __init__(self, A, p):
if not isinstance(A, LinearOperator):
raise ValueError('LinearOperator expected as A')
if A.shape[0] != A.shape[1]:
raise ValueError('square LinearOperator expected, got %r' % A)
if not isintlike(p):
raise ValueError('integer expected as p')
super(_PowerLinearOperator, self).__init__(_get_dtype([A]), A.shape)
self.args = (A, p)
def _power(self, fun, x):
res = np.array(x, copy=True)
for i in range(self.args[1]):
res = fun(res)
return res
def _matvec(self, x):
return self._power(self.args[0].matvec, x)
def _rmatvec(self, x):
return self._power(self.args[0].rmatvec, x)
def _matmat(self, x):
return self._power(self.args[0].matmat, x)
def _adjoint(self):
A, p = self.args
return A.H ** p
class MatrixLinearOperator(LinearOperator):
def __init__(self, A):
super(MatrixLinearOperator, self).__init__(A.dtype, A.shape)
self.A = A
self.__adj = None
self.args = (A,)
def _matmat(self, X):
return self.A.dot(X)
def _adjoint(self):
if self.__adj is None:
self.__adj = _AdjointMatrixOperator(self)
return self.__adj
class _AdjointMatrixOperator(MatrixLinearOperator):
def __init__(self, adjoint):
self.A = adjoint.A.T.conj()
self.__adjoint = adjoint
self.args = (adjoint,)
self.shape = adjoint.shape[1], adjoint.shape[0]
@property
def dtype(self):
return self.__adjoint.dtype
def _adjoint(self):
return self.__adjoint
class IdentityOperator(LinearOperator):
def __init__(self, shape, dtype=None):
super(IdentityOperator, self).__init__(dtype, shape)
def _matvec(self, x):
return x
def _rmatvec(self, x):
return x
def _matmat(self, x):
return x
def _adjoint(self):
return self
def aslinearoperator(A):
"""Return A as a LinearOperator.
'A' may be any of the following types:
- ndarray
- matrix
- sparse matrix (e.g. csr_matrix, lil_matrix, etc.)
- LinearOperator
- An object with .shape and .matvec attributes
See the LinearOperator documentation for additional information.
Examples
--------
>>> from scipy import matrix
>>> M = matrix( [[1,2,3],[4,5,6]], dtype='int32' )
>>> aslinearoperator( M )
<2x3 LinearOperator with dtype=int32>
"""
if isinstance(A, LinearOperator):
return A
elif isinstance(A, np.ndarray) or isinstance(A, np.matrix):
if A.ndim > 2:
raise ValueError('array must have ndim <= 2')
A = np.atleast_2d(np.asarray(A))
return MatrixLinearOperator(A)
elif isspmatrix(A):
return MatrixLinearOperator(A)
else:
if hasattr(A, 'shape') and hasattr(A, 'matvec'):
rmatvec = None
dtype = None
if hasattr(A, 'rmatvec'):
rmatvec = A.rmatvec
if hasattr(A, 'dtype'):
dtype = A.dtype
return LinearOperator(A.shape, A.matvec,
rmatvec=rmatvec, dtype=dtype)
else:
raise TypeError('type not understood')
| bsd-3-clause | -4,016,377,749,391,690,000 | 29.690616 | 80 | 0.576083 | false |
chirilo/kuma | vendor/packages/translate/tools/test_pretranslate.py | 25 | 14223 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import warnings
from pytest import mark
from translate.convert import test_convert
from translate.misc import wStringIO
from translate.storage import po, xliff
from translate.tools import pretranslate
class TestPretranslate:
xliff_skeleton = '''<?xml version="1.0" encoding="utf-8"?>
<xliff version="1.1" xmlns="urn:oasis:names:tc:xliff:document:1.1">
<file original="doc.txt" source-language="en-US">
<body>
%s
</body>
</file>
</xliff>'''
def setup_method(self, method):
warnings.resetwarnings()
def teardown_method(self, method):
warnings.resetwarnings()
def pretranslatepo(self, input_source, template_source=None):
"""helper that converts strings to po source without requiring files"""
input_file = wStringIO.StringIO(input_source)
if template_source:
template_file = wStringIO.StringIO(template_source)
else:
template_file = None
output_file = wStringIO.StringIO()
pretranslate.pretranslate_file(input_file, output_file, template_file)
output_file.seek(0)
return po.pofile(output_file.read())
def pretranslatexliff(self, input_source, template_source=None):
"""helper that converts strings to po source without requiring files"""
input_file = wStringIO.StringIO(input_source)
if template_source:
template_file = wStringIO.StringIO(template_source)
else:
template_file = None
output_file = wStringIO.StringIO()
pretranslate.pretranslate_file(input_file, output_file, template_file)
output_file.seek(0)
return xliff.xlifffile(output_file.read())
def singleunit(self, pofile):
"""checks that the pofile contains a single non-header unit, and
returns it"""
if len(pofile.units) == 2 and pofile.units[0].isheader():
print(pofile.units[1])
return pofile.units[1]
else:
print(pofile.units[0])
return pofile.units[0]
def test_pretranslatepo_blank(self):
"""checks that the pretranslatepo function is working for a simple file
initialisation"""
input_source = '''#: simple.label%ssimple.accesskey\nmsgid "A &hard coded newline.\\n"\nmsgstr ""\n''' % po.lsep
newpo = self.pretranslatepo(input_source)
assert str(self.singleunit(newpo)) == input_source
def test_merging_simple(self):
"""checks that the pretranslatepo function is working for a simple
merge"""
input_source = '''#: simple.label%ssimple.accesskey\nmsgid "A &hard coded newline.\\n"\nmsgstr ""\n''' % po.lsep
template_source = '''#: simple.label%ssimple.accesskey\nmsgid "A &hard coded newline.\\n"\nmsgstr "&Hart gekoeerde nuwe lyne\\n"\n''' % po.lsep
newpo = self.pretranslatepo(input_source, template_source)
assert str(self.singleunit(newpo)) == template_source
def test_merging_messages_marked_fuzzy(self):
"""test that when we merge PO files with a fuzzy message that it
remains fuzzy"""
input_source = '''#: simple.label%ssimple.accesskey\nmsgid "A &hard coded newline.\\n"\nmsgstr ""\n''' % po.lsep
template_source = '''#: simple.label%ssimple.accesskey\n#, fuzzy\nmsgid "A &hard coded newline.\\n"\nmsgstr "&Hart gekoeerde nuwe lyne\\n"\n''' % po.lsep
newpo = self.pretranslatepo(input_source, template_source)
assert str(self.singleunit(newpo)) == template_source
def test_merging_plurals_with_fuzzy_matching(self):
"""test that when we merge PO files with a fuzzy message that it
remains fuzzy"""
input_source = r'''#: file.cpp:2
msgid "%d manual"
msgid_plural "%d manuals"
msgstr[0] ""
msgstr[1] ""
'''
template_source = r'''#: file.cpp:3
#, fuzzy
msgid "%d manual"
msgid_plural "%d manuals"
msgstr[0] "%d handleiding."
msgstr[1] "%d handleidings."
'''
# The #: comment and msgid's are different between the pot and the po
poexpected = r'''#: file.cpp:2
#, fuzzy
msgid "%d manual"
msgid_plural "%d manuals"
msgstr[0] "%d handleiding."
msgstr[1] "%d handleidings."
'''
newpo = self.pretranslatepo(input_source, template_source)
assert str(self.singleunit(newpo)) == poexpected
@mark.xfail(reason="Not Implemented")
def test_merging_msgid_change(self):
"""tests that if the msgid changes but the location stays the same that
we merge"""
input_source = '''#: simple.label\n#: simple.accesskey\nmsgid "Its &hard coding a newline.\\n"\nmsgstr ""\n'''
template_source = '''#: simple.label\n#: simple.accesskey\nmsgid "A &hard coded newline.\\n"\nmsgstr "&Hart gekoeerde nuwe lyne\\n"\n'''
poexpected = '''#: simple.label\n#: simple.accesskey\n#, fuzzy\nmsgid "Its &hard coding a newline.\\n"\nmsgstr "&Hart gekoeerde nuwe lyne\\n"\n'''
newpo = self.pretranslatepo(input_source, template_source)
print(newpo)
assert str(newpo) == poexpected
def test_merging_location_change(self):
"""tests that if the location changes but the msgid stays the same that
we merge"""
input_source = '''#: new_simple.label%snew_simple.accesskey\nmsgid "A &hard coded newline.\\n"\nmsgstr ""\n''' % po.lsep
template_source = '''#: simple.label%ssimple.accesskey\nmsgid "A &hard coded newline.\\n"\nmsgstr "&Hart gekoeerde nuwe lyne\\n"\n''' % po.lsep
poexpected = '''#: new_simple.label%snew_simple.accesskey\nmsgid "A &hard coded newline.\\n"\nmsgstr "&Hart gekoeerde nuwe lyne\\n"\n''' % po.lsep
newpo = self.pretranslatepo(input_source, template_source)
print(newpo)
assert str(newpo) == poexpected
def test_merging_location_and_whitespace_change(self):
"""test that even if the location changes that if the msgid only has
whitespace changes we can still merge"""
input_source = '''#: singlespace.label%ssinglespace.accesskey\nmsgid "&We have spaces"\nmsgstr ""\n''' % po.lsep
template_source = '''#: doublespace.label%sdoublespace.accesskey\nmsgid "&We have spaces"\nmsgstr "&One het spasies"\n''' % po.lsep
poexpected = '''#: singlespace.label%ssinglespace.accesskey\n#, fuzzy\nmsgid "&We have spaces"\nmsgstr "&One het spasies"\n''' % po.lsep
newpo = self.pretranslatepo(input_source, template_source)
print(newpo)
assert str(newpo) == poexpected
@mark.xfail(reason="Not Implemented")
def test_merging_accelerator_changes(self):
"""test that a change in the accelerator localtion still allows
merging"""
input_source = '''#: someline.c\nmsgid "A&bout"\nmsgstr ""\n'''
template_source = '''#: someline.c\nmsgid "&About"\nmsgstr "&Info"\n'''
poexpected = '''#: someline.c\nmsgid "A&bout"\nmsgstr "&Info"\n'''
newpo = self.pretranslatepo(input_source, template_source)
print(newpo)
assert str(newpo) == poexpected
@mark.xfail(reason="Not Implemented")
def test_lines_cut_differently(self):
"""Checks that the correct formatting is preserved when pot an po lines
differ."""
input_source = '''#: simple.label\nmsgid "Line split "\n"differently"\nmsgstr ""\n'''
template_source = '''#: simple.label\nmsgid "Line"\n" split differently"\nmsgstr "Lyne verskillend gesny"\n'''
newpo = self.pretranslatepo(input_source, template_source)
newpounit = self.singleunit(newpo)
assert str(newpounit) == template_source
def test_merging_automatic_comments_dont_duplicate(self):
"""ensure that we can merge #. comments correctly"""
input_source = '''#. Row 35\nmsgid "&About"\nmsgstr ""\n'''
template_source = '''#. Row 35\nmsgid "&About"\nmsgstr "&Info"\n'''
newpo = self.pretranslatepo(input_source, template_source)
newpounit = self.singleunit(newpo)
assert str(newpounit) == template_source
def test_merging_automatic_comments_new_overides_old(self):
"""ensure that new #. comments override the old comments"""
input_source = '''#. new comment\n#: someline.c\nmsgid "&About"\nmsgstr ""\n'''
template_source = '''#. old comment\n#: someline.c\nmsgid "&About"\nmsgstr "&Info"\n'''
poexpected = '''#. new comment\n#: someline.c\nmsgid "&About"\nmsgstr "&Info"\n'''
newpo = self.pretranslatepo(input_source, template_source)
newpounit = self.singleunit(newpo)
assert str(newpounit) == poexpected
def test_merging_comments_with_blank_comment_lines(self):
"""test that when we merge a comment that has a blank line we keep the
blank line"""
input_source = '''#: someline.c\nmsgid "About"\nmsgstr ""\n'''
template_source = '''# comment1\n#\n# comment2\n#: someline.c\nmsgid "About"\nmsgstr "Omtrent"\n'''
poexpected = template_source
newpo = self.pretranslatepo(input_source, template_source)
newpounit = self.singleunit(newpo)
assert str(newpounit) == poexpected
def test_empty_commentlines(self):
input_source = '''#: paneSecurity.title
msgid "Security"
msgstr ""
'''
template_source = '''# - Contributor(s):
# -
# - Alternatively, the
# -
#: paneSecurity.title
msgid "Security"
msgstr "Sekuriteit"
'''
poexpected = template_source
newpo = self.pretranslatepo(input_source, template_source)
newpounit = self.singleunit(newpo)
print("expected")
print(poexpected)
print("got:")
print(str(newpounit))
assert str(newpounit) == poexpected
def test_merging_msgidcomments(self):
"""ensure that we can merge msgidcomments messages"""
input_source = r'''#: window.width
msgid ""
"_: Do not translate this.\n"
"36em"
msgstr ""
'''
template_source = r'''#: window.width
msgid ""
"_: Do not translate this.\n"
"36em"
msgstr "36em"
'''
newpo = self.pretranslatepo(input_source, template_source)
newpounit = self.singleunit(newpo)
assert str(newpounit) == template_source
def test_merging_plurals(self):
"""ensure that we can merge plural messages"""
input_source = '''msgid "One"\nmsgid_plural "Two"\nmsgstr[0] ""\nmsgstr[1] ""\n'''
template_source = '''msgid "One"\nmsgid_plural "Two"\nmsgstr[0] "Een"\nmsgstr[1] "Twee"\nmsgstr[2] "Drie"\n'''
newpo = self.pretranslatepo(input_source, template_source)
print(newpo)
newpounit = self.singleunit(newpo)
assert str(newpounit) == template_source
def test_merging_resurect_obsolete_messages(self):
"""check that we can reuse old obsolete messages if the message comes
back"""
input_source = '''#: resurect.c\nmsgid "&About"\nmsgstr ""\n'''
template_source = '''#~ msgid "&About"\n#~ msgstr "&Omtrent"\n'''
expected = '''#: resurect.c\nmsgid "&About"\nmsgstr "&Omtrent"\n'''
newpo = self.pretranslatepo(input_source, template_source)
print(newpo)
assert str(newpo) == expected
def test_merging_comments(self):
"""Test that we can merge comments correctly"""
input_source = '''#. Don't do it!\n#: file.py:1\nmsgid "One"\nmsgstr ""\n'''
template_source = '''#. Don't do it!\n#: file.py:2\nmsgid "One"\nmsgstr "Een"\n'''
poexpected = '''#. Don't do it!\n#: file.py:1\nmsgid "One"\nmsgstr "Een"\n'''
newpo = self.pretranslatepo(input_source, template_source)
print(newpo)
newpounit = self.singleunit(newpo)
assert str(newpounit) == poexpected
def test_merging_typecomments(self):
"""Test that we can merge with typecomments"""
input_source = '''#: file.c:1\n#, c-format\nmsgid "%d pipes"\nmsgstr ""\n'''
template_source = '''#: file.c:2\nmsgid "%d pipes"\nmsgstr "%d pype"\n'''
poexpected = '''#: file.c:1\n#, c-format\nmsgid "%d pipes"\nmsgstr "%d pype"\n'''
newpo = self.pretranslatepo(input_source, template_source)
newpounit = self.singleunit(newpo)
print(newpounit)
assert str(newpounit) == poexpected
input_source = '''#: file.c:1\n#, c-format\nmsgid "%d computers"\nmsgstr ""\n'''
template_source = '''#: file.c:2\n#, c-format\nmsgid "%s computers "\nmsgstr "%s-rekenaars"\n'''
poexpected = '''#: file.c:1\n#, fuzzy, c-format\nmsgid "%d computers"\nmsgstr "%s-rekenaars"\n'''
newpo = self.pretranslatepo(input_source, template_source)
newpounit = self.singleunit(newpo)
assert newpounit.isfuzzy()
assert newpounit.hastypecomment("c-format")
def test_xliff_states(self):
"""Test correct maintenance of XLIFF states."""
xlf_template = self.xliff_skeleton \
% '''<trans-unit id="1" xml:space="preserve">
<source> File 1 </source>
</trans-unit>'''
xlf_old = self.xliff_skeleton \
% '''<trans-unit id="1" xml:space="preserve" approved="yes">
<source> File 1 </source>
<target> Lêer 1 </target>
</trans-unit>'''
template = xliff.xlifffile.parsestring(xlf_template)
old = xliff.xlifffile.parsestring(xlf_old)
new = self.pretranslatexliff(template, old)
print(str(old))
print('---')
print(str(new))
assert new.units[0].isapproved()
# Layout might have changed, so we won't compare the serialised
# versions
class TestPretranslateCommand(test_convert.TestConvertCommand, TestPretranslate):
"""Tests running actual pretranslate commands on files"""
convertmodule = pretranslate
def test_help(self):
"""tests getting help"""
options = test_convert.TestConvertCommand.test_help(self)
options = self.help_check(options, "-t TEMPLATE, --template=TEMPLATE")
options = self.help_check(options, "--tm")
options = self.help_check(options, "-s MIN_SIMILARITY, --similarity=MIN_SIMILARITY")
options = self.help_check(options, "--nofuzzymatching", last=True)
| mpl-2.0 | 6,862,671,191,136,994,000 | 44.149206 | 161 | 0.632471 | false |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_04_01/operations/_network_profiles_operations.py | 1 | 24143 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class NetworkProfilesOperations(object):
"""NetworkProfilesOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2020_04_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def _delete_initial(
self,
resource_group_name, # type: str
network_profile_name, # type: str
**kwargs # type: Any
):
# type: (...) -> None
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
accept = "application/json"
# Construct URL
url = self._delete_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkProfileName': self._serialize.url("network_profile_name", network_profile_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}'} # type: ignore
def begin_delete(
self,
resource_group_name, # type: str
network_profile_name, # type: str
**kwargs # type: Any
):
# type: (...) -> LROPoller[None]
"""Deletes the specified network profile.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param network_profile_name: The name of the NetworkProfile.
:type network_profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: Pass in True if you'd like the ARMPolling polling method,
False for no polling, or your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial(
resource_group_name=resource_group_name,
network_profile_name=network_profile_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkProfileName': self._serialize.url("network_profile_name", network_profile_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}'} # type: ignore
def get(
self,
resource_group_name, # type: str
network_profile_name, # type: str
expand=None, # type: Optional[str]
**kwargs # type: Any
):
# type: (...) -> "_models.NetworkProfile"
"""Gets the specified network profile in a specified resource group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param network_profile_name: The name of the public IP prefix.
:type network_profile_name: str
:param expand: Expands referenced resources.
:type expand: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: NetworkProfile, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2020_04_01.models.NetworkProfile
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.NetworkProfile"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkProfileName': self._serialize.url("network_profile_name", network_profile_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
if expand is not None:
query_parameters['$expand'] = self._serialize.query("expand", expand, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('NetworkProfile', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}'} # type: ignore
def create_or_update(
self,
resource_group_name, # type: str
network_profile_name, # type: str
parameters, # type: "_models.NetworkProfile"
**kwargs # type: Any
):
# type: (...) -> "_models.NetworkProfile"
"""Creates or updates a network profile.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param network_profile_name: The name of the network profile.
:type network_profile_name: str
:param parameters: Parameters supplied to the create or update network profile operation.
:type parameters: ~azure.mgmt.network.v2020_04_01.models.NetworkProfile
:keyword callable cls: A custom type or function that will be passed the direct response
:return: NetworkProfile, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2020_04_01.models.NetworkProfile
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.NetworkProfile"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.create_or_update.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkProfileName': self._serialize.url("network_profile_name", network_profile_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(parameters, 'NetworkProfile')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('NetworkProfile', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('NetworkProfile', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}'} # type: ignore
def update_tags(
self,
resource_group_name, # type: str
network_profile_name, # type: str
parameters, # type: "_models.TagsObject"
**kwargs # type: Any
):
# type: (...) -> "_models.NetworkProfile"
"""Updates network profile tags.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param network_profile_name: The name of the network profile.
:type network_profile_name: str
:param parameters: Parameters supplied to update network profile tags.
:type parameters: ~azure.mgmt.network.v2020_04_01.models.TagsObject
:keyword callable cls: A custom type or function that will be passed the direct response
:return: NetworkProfile, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2020_04_01.models.NetworkProfile
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.NetworkProfile"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.update_tags.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkProfileName': self._serialize.url("network_profile_name", network_profile_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(parameters, 'TagsObject')
body_content_kwargs['content'] = body_content
request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('NetworkProfile', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}'} # type: ignore
def list_all(
self,
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.NetworkProfileListResult"]
"""Gets all the network profiles in a subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either NetworkProfileListResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2020_04_01.models.NetworkProfileListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.NetworkProfileListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_all.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('NetworkProfileListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_all.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkProfiles'} # type: ignore
def list(
self,
resource_group_name, # type: str
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.NetworkProfileListResult"]
"""Gets all network profiles in a resource group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either NetworkProfileListResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2020_04_01.models.NetworkProfileListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.NetworkProfileListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('NetworkProfileListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles'} # type: ignore
| mit | 6,266,978,053,235,399,000 | 47.47992 | 190 | 0.638446 | false |
Moguri/bgui | bgui/label.py | 6 | 3457 | from .gl_utils import *
from .widget import Widget, BGUI_DEFAULT, BGUI_NO_NORMALIZE
class Label(Widget):
"""Widget for displaying text"""
theme_section = 'Label'
theme_options = {
'Font': '',
'Color': (1, 1, 1, 1),
'OutlineColor': (0, 0, 0, 1),
'OutlineSize': 0,
'OutlineSmoothing': False,
'Size': 30,
}
def __init__(self, parent, name=None, text="", font=None, pt_size=None, color=None,
outline_color=None, outline_size=None, outline_smoothing=None, pos=[0, 0], sub_theme='', options=BGUI_DEFAULT):
"""
:param parent: the widget's parent
:param name: the name of the widget
:param text: the text to display (this can be changed later via the text property)
:param font: the font to use
:param pt_size: the point size of the text to draw (defaults to 30 if None)
:param color: the color to use when rendering the font
:param pos: a tuple containing the x and y position
:param sub_theme: name of a sub_theme defined in the theme file (similar to CSS classes)
:param options: various other options
"""
Widget.__init__(self, parent, name, None, [0, 0], pos, sub_theme, options)
if font:
self.fontid = self.system.textlib.load(font)
else:
font = self.theme['Font']
self.fontid = self.system.textlib.load(font) if font else 0
if pt_size:
self.pt_size = pt_size
else:
self.pt_size = self.theme['Size']
if color:
self.color = color
else:
self.color = self.theme['Color']
if outline_color:
self.outline_color = outline_color
else:
self.outline_color = self.theme['OutlineColor']
if outline_size is not None:
self.outline_size = outline_size
else:
self.outline_size = self.theme['OutlineSize']
self.outline_size = int(self.outline_size)
if outline_smoothing is not None:
self.outline_smoothing = outline_smoothing
else:
self.outline_smoothing = self.theme['OutlineSmoothing']
self.text = text
@property
def text(self):
"""The text to display"""
return self._text
@text.setter
def text(self, value):
self.system.textlib.size(self.fontid, self.pt_size, 72)
size = [self.system.textlib.dimensions(self.fontid, value)[0], self.system.textlib.dimensions(self.fontid, 'Mj')[0]]
if not (self.options & BGUI_NO_NORMALIZE):
size[0] /= self.parent.size[0]
size[1] /= self.parent.size[1]
self._update_position(size, self._base_pos)
self._text = value
@property
def pt_size(self):
"""The point size of the label's font"""
return self._pt_size
@pt_size.setter
def pt_size(self, value):
# Normalize the pt size (1000px height = 1)
if self.system.normalize_text:
self._pt_size = int(value * (self.system.size[1] / 1000))
else:
self._pt_size = value
def _draw_text(self, x, y):
for i, txt in enumerate([i for i in self._text.split('\n')]):
self.system.textlib.position(self.fontid, x, y - (self.size[1] * i), 0)
self.system.textlib.draw(self.fontid, txt.replace('\t', ' '))
def _draw(self):
"""Display the text"""
self.system.textlib.size(self.fontid, self.pt_size, 72)
if self.outline_size:
glColor4f(*self.outline_color)
if self.outline_smoothing:
steps = range(-self.outline_size, self.outline_size + 1)
else:
steps = (-self.outline_size, 0, self.outline_size)
for x in steps:
for y in steps:
self._draw_text(self.position[0] + x, self.position[1] + y)
glColor4f(*self.color)
self._draw_text(*self.position)
Widget._draw(self)
| mit | -1,271,201,399,395,384,000 | 27.105691 | 118 | 0.666185 | false |
tensorflow/tensorflow | tensorflow/compiler/tests/conv2d_test.py | 9 | 31148 | # 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 Conv2D via the XLA JIT.
The canned results in these tests are created by running each test using the
Tensorflow CPU device and saving the output.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
from tensorflow.compiler.tests import test_utils
from tensorflow.compiler.tests import xla_test
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_nn_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.platform import googletest
DATA_FORMATS = (
("_data_format_NHWC", "NHWC"),
("_data_format_NCHW", "NCHW"),
)
class Conv2DTest(xla_test.XLATestCase, parameterized.TestCase):
def _VerifyValues(self,
input_sizes=None,
filter_sizes=None,
strides=None,
dilations=None,
padding=None,
data_format_src="NHWC",
data_format_dst="NHWC",
expected=None):
"""Tests that tf.nn.conv2d produces the expected value.
Args:
input_sizes: Input tensor dimensions in
[batch, input_rows, input_cols, input_depth].
filter_sizes: Filter tensor dimensions in
[kernel_rows, kernel_cols, input_depth, output_depth].
strides: Strides.
dilations: RHS dilations.
padding: Padding type.
data_format_src: Data format input is in.
data_format_dst: Data format verification will run and input is converted
to.
expected: Expected output.
"""
total_size_1 = np.prod(input_sizes)
total_size_2 = np.prod(filter_sizes)
x1 = np.arange(1, total_size_1 + 1, dtype=np.float32).reshape(input_sizes)
x2 = np.arange(1, total_size_2 + 1, dtype=np.float32).reshape(filter_sizes)
strides = [1] + strides + [1]
if dilations is None:
dilations = [1, 1]
dilations = [1] + dilations + [1]
# Convert between data formats.
expected = test_utils.ConvertBetweenDataFormats(expected, data_format_src,
data_format_dst)
x1 = test_utils.ConvertBetweenDataFormats(x1, data_format_src,
data_format_dst)
input_sizes = test_utils.PermuteDimsBetweenDataFormats(
input_sizes, data_format_src, data_format_dst)
strides = test_utils.PermuteDimsBetweenDataFormats(strides, data_format_src,
data_format_dst)
dilations = test_utils.PermuteDimsBetweenDataFormats(
dilations, data_format_src, data_format_dst)
with self.session() as sess:
t1 = array_ops.placeholder(dtypes.float32, shape=input_sizes)
t2 = array_ops.placeholder(dtypes.float32, shape=filter_sizes)
with self.test_scope():
out = nn_ops.conv2d(
t1,
t2,
strides=strides,
padding=padding,
data_format=data_format_dst,
dilations=dilations)
value = sess.run(out, {t1: x1, t2: x2})
self.assertAllClose(expected, value, 1e-3)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D1x1Filter(self, data_format):
expected_output = np.reshape([
30.0, 36.0, 42.0, 66.0, 81.0, 96.0, 102.0, 126.0, 150.0, 138.0, 171.0,
204.0, 174.0, 216.0, 258.0, 210.0, 261.0, 312.0
], [1, 2, 3, 3])
self._VerifyValues(
input_sizes=[1, 2, 3, 3],
filter_sizes=[1, 1, 3, 3],
strides=[1, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2Filter(self, data_format):
expected_output = np.reshape(
[2271.0, 2367.0, 2463.0, 2901.0, 3033.0, 3165.0], [1, 1, 2, 3])
self._VerifyValues(
input_sizes=[1, 2, 3, 3],
filter_sizes=[2, 2, 3, 3],
strides=[1, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2Filter2x1Dilation(self, data_format):
expected_output = np.array([[[[72], [82], [92]], [[112], [122], [132]]]])
self._VerifyValues(
input_sizes=[1, 4, 4, 1],
filter_sizes=[2, 2, 1, 1],
strides=[1, 1],
dilations=[2, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D1x2Filter(self, data_format):
expected_output = np.reshape([
231.0, 252.0, 273.0, 384.0, 423.0, 462.0, 690.0, 765.0, 840.0, 843.0,
936.0, 1029.0
], [1, 2, 2, 3])
self._VerifyValues(
input_sizes=[1, 2, 3, 3],
filter_sizes=[1, 2, 3, 3],
strides=[1, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2FilterStride2(self, data_format):
expected_output = np.reshape([2271.0, 2367.0, 2463.0], [1, 1, 1, 3])
self._VerifyValues(
input_sizes=[1, 2, 3, 3],
filter_sizes=[2, 2, 3, 3],
strides=[2, 2],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2FilterStride2Same(self, data_format):
expected_output = np.reshape(
[2271.0, 2367.0, 2463.0, 1230.0, 1305.0, 1380.0], [1, 1, 2, 3])
self._VerifyValues(
input_sizes=[1, 2, 3, 3],
filter_sizes=[2, 2, 3, 3],
strides=[2, 2],
padding="SAME",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2DEmptyDilation(self, data_format):
self._VerifyValues(
input_sizes=[0, 2, 3, 3],
filter_sizes=[1, 1, 3, 3],
strides=[1, 1],
dilations=[2, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=np.zeros([0, 2, 3, 3]))
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2FilterDilation(self, data_format):
self._VerifyValues(
input_sizes=[1, 2, 3, 3],
filter_sizes=[2, 2, 3, 3],
strides=[1, 1],
dilations=[1, 2],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=np.reshape([2667, 2781, 2895], [1, 1, 1, 3]))
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D1x2FilterDilation(self, data_format):
self._VerifyValues(
input_sizes=[1, 2, 3, 3],
filter_sizes=[1, 2, 3, 3],
strides=[1, 1],
dilations=[2, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=np.array([[[[231, 252, 273], [384, 423, 462]],
[[690, 765, 840], [843, 936, 1029]]]]))
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2DKernelSizeMatchesInputSizeDilation(self, data_format):
self._VerifyValues(
input_sizes=[1, 3, 3, 1],
filter_sizes=[2, 2, 1, 2],
strides=[1, 1],
dilations=[2, 2],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=np.reshape([108, 128], [1, 1, 1, 2]))
class Conv2DBackpropInputTest(xla_test.XLATestCase, parameterized.TestCase):
def _VerifyValues(self,
input_sizes=None,
filter_sizes=None,
out_backprop_sizes=None,
strides=None,
dilations=None,
padding=None,
data_format_src="NHWC",
data_format_dst="NHWC",
expected=None):
"""Tests that gen_nn_ops.conv2d_backprop_input produces the expected output.
Args:
input_sizes: Input tensor dimensions in
[batch, input_rows, input_cols, input_depth].
filter_sizes: Filter tensor dimensions in
[kernel_rows, kernel_cols, input_depth, output_depth].
out_backprop_sizes: Output gradients tensor dimensions.
strides: Strides.
dilations: Dilations.
padding: Padding type.
data_format_src: Data format input is in.
data_format_dst: Data format verification will run and input is converted
to.
expected: Expected output.
"""
total_size_1 = np.prod(filter_sizes)
total_size_2 = np.prod(out_backprop_sizes)
x1 = np.arange(1, total_size_1 + 1, dtype=np.float32).reshape(filter_sizes)
x2 = np.arange(
1, total_size_2 + 1, dtype=np.float32).reshape(out_backprop_sizes)
strides = [1] + strides + [1]
if dilations is not None:
dilations = [1] + dilations + [1]
expected = np.reshape(expected, input_sizes)
# Convert between data formats.
expected = test_utils.ConvertBetweenDataFormats(expected, data_format_src,
data_format_dst)
x2 = test_utils.ConvertBetweenDataFormats(x2, data_format_src,
data_format_dst)
input_sizes = test_utils.PermuteDimsBetweenDataFormats(
input_sizes, data_format_src, data_format_dst)
out_backprop_sizes = test_utils.PermuteDimsBetweenDataFormats(
out_backprop_sizes, data_format_src, data_format_dst)
strides = test_utils.PermuteDimsBetweenDataFormats(strides, data_format_src,
data_format_dst)
if dilations is not None:
dilations = test_utils.PermuteDimsBetweenDataFormats(
dilations, data_format_src, data_format_dst)
with self.session() as sess:
t1 = array_ops.placeholder(dtypes.float32, shape=filter_sizes)
t2 = array_ops.placeholder(dtypes.float32, shape=out_backprop_sizes)
with self.test_scope():
out = gen_nn_ops.conv2d_backprop_input(
input_sizes=input_sizes,
filter=t1,
out_backprop=t2,
strides=strides,
dilations=dilations,
padding=padding,
data_format=data_format_dst)
value = sess.run(out, {t1: x1, t2: x2})
self.assertAllEqual(input_sizes, value.shape)
self.assertAllClose(expected, value, 1e-3)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D1x1Filter(self, data_format):
expected_output = [
5, 11, 17, 11, 25, 39, 17, 39, 61, 23, 53, 83, 29, 67, 105, 35, 81, 127,
41, 95, 149, 47, 109, 171, 53, 123, 193, 59, 137, 215, 65, 151, 237, 71,
165, 259, 77, 179, 281, 83, 193, 303, 89, 207, 325, 95, 221, 347.
]
self._VerifyValues(
input_sizes=[1, 4, 4, 3],
filter_sizes=[1, 1, 3, 2],
out_backprop_sizes=[1, 4, 4, 2],
strides=[1, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D1x2FilterStride3Width5(self, data_format):
expected_output = [1, 2, 0, 2, 4]
self._VerifyValues(
input_sizes=[1, 1, 5, 1],
filter_sizes=[1, 2, 1, 1],
out_backprop_sizes=[1, 1, 2, 1],
strides=[3, 3],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D1x2FilterStride3Width6(self, data_format):
expected_output = [1, 2, 0, 2, 4, 0]
self._VerifyValues(
input_sizes=[1, 1, 6, 1],
filter_sizes=[1, 2, 1, 1],
out_backprop_sizes=[1, 1, 2, 1],
strides=[3, 3],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D1x2FilterStride3Width7(self, data_format):
expected_output = [1, 2, 0, 2, 4, 0, 0]
self._VerifyValues(
input_sizes=[1, 1, 7, 1],
filter_sizes=[1, 2, 1, 1],
out_backprop_sizes=[1, 1, 2, 1],
strides=[3, 3],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2FilterC1Same(self, data_format):
expected_output = [1, 4, 7, 7, 23, 33]
self._VerifyValues(
input_sizes=[1, 2, 3, 1],
filter_sizes=[2, 2, 1, 1],
out_backprop_sizes=[1, 2, 3, 1],
strides=[1, 1],
padding="SAME",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2Filter(self, data_format):
expected_output = [
14, 32, 50, 100, 163, 226, 167, 212, 257, 122, 140, 158, 478, 541, 604,
437, 482, 527
]
self._VerifyValues(
input_sizes=[1, 2, 3, 3],
filter_sizes=[2, 2, 3, 3],
out_backprop_sizes=[1, 1, 2, 3],
strides=[1, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2FilterSame(self, data_format):
expected_output = [
14, 32, 50, 100, 163, 226, 217, 334, 451, 190, 307, 424, 929, 1217,
1505, 1487, 1883, 2279
]
self._VerifyValues(
input_sizes=[1, 2, 3, 3],
filter_sizes=[2, 2, 3, 3],
out_backprop_sizes=[1, 2, 3, 3],
strides=[1, 1],
padding="SAME",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D1x2Filter(self, data_format):
expected_output = [1, 4, 4, 3, 10, 8, 5, 16, 12]
self._VerifyValues(
input_sizes=[1, 3, 3, 1],
filter_sizes=[1, 2, 1, 1],
out_backprop_sizes=[1, 3, 2, 1],
strides=[1, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D1x2FilterSame(self, data_format):
expected_output = [1, 4, 7, 4, 13, 16, 7, 22, 25]
self._VerifyValues(
input_sizes=[1, 3, 3, 1],
filter_sizes=[1, 2, 1, 1],
out_backprop_sizes=[1, 3, 3, 1],
strides=[1, 1],
padding="SAME",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2FilterStride2(self, data_format):
expected_output = [1, 2, 5, 4, 6, 0, 0, 0, 0, 0, 3, 6, 13, 8, 12]
self._VerifyValues(
input_sizes=[1, 3, 5, 1],
filter_sizes=[1, 3, 1, 1],
out_backprop_sizes=[1, 2, 2, 1],
strides=[2, 2],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2FilterStride2Same(self, data_format):
expected_output = [1, 2, 2, 3, 4, 6]
self._VerifyValues(
input_sizes=[1, 2, 3, 1],
filter_sizes=[2, 2, 1, 1],
out_backprop_sizes=[1, 1, 2, 1],
strides=[2, 2],
padding="SAME",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2Depth3ValidBackpropInputStride1x1Dilation2x1(
self, data_format):
self._VerifyValues(
input_sizes=[1, 3, 6, 1],
filter_sizes=[2, 2, 1, 1],
out_backprop_sizes=[1, 1, 5, 1],
strides=[1, 1],
dilations=[2, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=[1, 4, 7, 10, 13, 10, 0, 0, 0, 0, 0, 0, 3, 10, 17, 24, 31, 20])
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2Depth1ValidBackpropInputDilation1x2(self, data_format):
self._VerifyValues(
input_sizes=[1, 2, 3, 1],
filter_sizes=[2, 2, 1, 1],
out_backprop_sizes=[1, 1, 1, 1],
strides=[1, 1],
dilations=[1, 2],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=[1, 0, 2, 3, 0, 4])
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2DEmptyBackpropInputDilation1x2(self, data_format):
self._VerifyValues(
input_sizes=[0, 2, 3, 1],
filter_sizes=[2, 2, 1, 1],
out_backprop_sizes=[0, 1, 1, 1],
strides=[1, 1],
dilations=[1, 2],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=np.zeros([0]))
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2Depth3ValidBackpropInputDilation2x1(self, data_format):
# The GPU version of this test is not very stable. So adjusting the
# error threshold to 1e-4.
self._VerifyValues(
input_sizes=[1, 3, 2, 3],
filter_sizes=[2, 2, 3, 3],
out_backprop_sizes=[1, 1, 1, 3],
strides=[1, 1],
dilations=[2, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=[
14, 32, 50, 68, 86, 104, 0, 0, 0, 0, 0, 0, 122, 140, 158, 176, 194,
212
])
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2DKernelSizeMatchesInputSizeBackpropInputDilation2x2(
self, data_format):
self._VerifyValues(
input_sizes=[1, 3, 3, 1],
filter_sizes=[2, 2, 1, 2],
out_backprop_sizes=[1, 1, 1, 2],
strides=[1, 1],
dilations=[2, 2],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=[5, 0, 11, 0, 0, 0, 17, 0, 23])
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2DGroupedFilter(self, data_format):
expected_output = [
5, 17, 29, 25, 53, 81, 41, 53, 65, 109, 137, 165, 77, 89, 101, 193, 221,
249, 113, 125, 137, 277, 305, 333
]
self._VerifyValues(
input_sizes=[1, 2, 2, 6],
filter_sizes=[2, 2, 3, 4],
out_backprop_sizes=[1, 1, 1, 4],
strides=[1, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
class Conv2DBackpropFilterTest(xla_test.XLATestCase, parameterized.TestCase):
def _VerifyValues(self,
input_sizes=None,
filter_sizes=None,
out_backprop_sizes=None,
strides=None,
dilations=None,
padding=None,
data_format_src="NHWC",
data_format_dst="NHWC",
expected=None):
"""Tests that gen_nn_ops.conv2d_backprop_filter produces the right output.
Args:
input_sizes: Input tensor dimensions in
[batch, input_rows, input_cols, input_depth].
filter_sizes: Filter tensor dimensions in
[kernel_rows, kernel_cols, input_depth, output_depth].
out_backprop_sizes: Output gradients tensor dimensions.
strides: Stride.
dilations: Dilations.
padding: Padding type.
data_format_src: Data format input is in.
data_format_dst: Data format verification will run and input is converted
to.
expected: Expected output.
"""
total_size_1 = np.prod(input_sizes)
total_size_2 = np.prod(out_backprop_sizes)
x1 = np.arange(1, total_size_1 + 1, dtype=np.float32).reshape(input_sizes)
x2 = np.arange(
1, total_size_2 + 1, dtype=np.float32).reshape(out_backprop_sizes)
strides = [1] + strides + [1]
if dilations is not None:
dilations = [1] + dilations + [1]
expected = np.reshape(expected, filter_sizes)
# Convert between data formats.
x1 = test_utils.ConvertBetweenDataFormats(x1, data_format_src,
data_format_dst)
x2 = test_utils.ConvertBetweenDataFormats(x2, data_format_src,
data_format_dst)
input_sizes = test_utils.PermuteDimsBetweenDataFormats(
input_sizes, data_format_src, data_format_dst)
out_backprop_sizes = test_utils.PermuteDimsBetweenDataFormats(
out_backprop_sizes, data_format_src, data_format_dst)
strides = test_utils.PermuteDimsBetweenDataFormats(strides, data_format_src,
data_format_dst)
if dilations is not None:
dilations = test_utils.PermuteDimsBetweenDataFormats(
dilations, data_format_src, data_format_dst)
with self.session() as sess:
t1 = array_ops.placeholder(dtypes.float32, shape=input_sizes)
t2 = array_ops.placeholder(dtypes.float32, shape=out_backprop_sizes)
with self.test_scope():
tensor = gen_nn_ops.conv2d_backprop_filter(
input=t1,
filter_sizes=filter_sizes,
out_backprop=t2,
strides=strides,
dilations=dilations,
padding=padding,
data_format=data_format_dst)
value = sess.run(tensor, {t1: x1, t2: x2})
self.assertAllEqual(filter_sizes, value.shape)
self.assertAllClose(expected, value, 1e-3)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D1x1Filter(self, data_format):
expected_output = [8056, 8432, 8312, 8704, 8568, 8976]
self._VerifyValues(
input_sizes=[1, 4, 4, 3],
filter_sizes=[1, 1, 3, 2],
out_backprop_sizes=[1, 4, 4, 2],
strides=[1, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D1x2Filter(self, data_format):
expected_output = [120, 141]
self._VerifyValues(
input_sizes=[1, 3, 3, 1],
filter_sizes=[1, 2, 1, 1],
out_backprop_sizes=[1, 3, 2, 1],
strides=[1, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2FilterDepth1(self, data_format):
expected_output = [5, 8, 14, 17]
self._VerifyValues(
input_sizes=[1, 2, 3, 1],
filter_sizes=[2, 2, 1, 1],
out_backprop_sizes=[1, 1, 2, 1],
strides=[1, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2Filter(self, data_format):
expected_output = [
17, 22, 27, 22, 29, 36, 27, 36, 45, 32, 43, 54, 37, 50, 63, 42, 57, 72,
62, 85, 108, 67, 92, 117, 72, 99, 126, 77, 106, 135, 82, 113, 144, 87,
120, 153
]
self._VerifyValues(
input_sizes=[1, 2, 3, 3],
filter_sizes=[2, 2, 3, 3],
out_backprop_sizes=[1, 1, 2, 3],
strides=[1, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D1x2FilterStride3Width5(self, data_format):
expected_output = [9, 12]
self._VerifyValues(
input_sizes=[1, 1, 5, 1],
filter_sizes=[1, 2, 1, 1],
out_backprop_sizes=[1, 1, 2, 1],
strides=[3, 3],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D1x2FilterStride3Width6(self, data_format):
expected_output = [9, 12]
self._VerifyValues(
input_sizes=[1, 1, 6, 1],
filter_sizes=[1, 2, 1, 1],
out_backprop_sizes=[1, 1, 2, 1],
strides=[3, 3],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D1x2FilterStride3Width7(self, data_format):
expected_output = [9, 12]
self._VerifyValues(
input_sizes=[1, 1, 7, 1],
filter_sizes=[1, 2, 1, 1],
out_backprop_sizes=[1, 1, 2, 1],
strides=[3, 3],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D1x3Filter(self, data_format):
expected_output = [5, 8, 11]
self._VerifyValues(
input_sizes=[1, 1, 4, 1],
filter_sizes=[1, 3, 1, 1],
out_backprop_sizes=[1, 1, 2, 1],
strides=[1, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D1x3FilterSame(self, data_format):
expected_output = [20, 30, 20]
self._VerifyValues(
input_sizes=[1, 1, 4, 1],
filter_sizes=[1, 3, 1, 1],
out_backprop_sizes=[1, 1, 4, 1],
strides=[1, 1],
padding="SAME",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D1x3FilterSameOutbackprop2(self, data_format):
expected_output = [7, 10, 3]
self._VerifyValues(
input_sizes=[1, 1, 4, 1],
filter_sizes=[1, 3, 1, 1],
out_backprop_sizes=[1, 1, 2, 1],
strides=[2, 2],
padding="SAME",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2FilterC1Same(self, data_format):
expected_output = [91, 58, 32, 17]
self._VerifyValues(
input_sizes=[1, 2, 3, 1],
filter_sizes=[2, 2, 1, 1],
out_backprop_sizes=[1, 2, 3, 1],
strides=[1, 1],
padding="SAME",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2FilterStride2(self, data_format):
expected_output = [92, 102, 112]
self._VerifyValues(
input_sizes=[1, 3, 5, 1],
filter_sizes=[1, 3, 1, 1],
out_backprop_sizes=[1, 2, 2, 1],
strides=[2, 2],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2FilterStride2Same(self, data_format):
expected_output = [7, 2, 16, 5]
self._VerifyValues(
input_sizes=[1, 2, 3, 1],
filter_sizes=[2, 2, 1, 1],
out_backprop_sizes=[1, 1, 2, 1],
strides=[2, 2],
padding="SAME",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2Depth3ValidBackpropFilterStride1x1Dilation2x1(
self, data_format):
self._VerifyValues(
input_sizes=[1, 3, 6, 1],
filter_sizes=[2, 2, 1, 1],
out_backprop_sizes=[1, 1, 5, 1],
strides=[1, 1],
dilations=[2, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=[55, 70, 235, 250])
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2Depth1ValidBackpropFilterDilation1x2(self, data_format):
self._VerifyValues(
input_sizes=[1, 2, 3, 1],
filter_sizes=[2, 2, 1, 1],
out_backprop_sizes=[1, 1, 1, 1],
strides=[1, 1],
dilations=[1, 2],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=[1, 3, 4, 6])
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2DEmptyBackpropFilterDilation1x2(self, data_format):
self._VerifyValues(
input_sizes=[1, 2, 3, 1],
filter_sizes=[2, 2, 1, 0],
out_backprop_sizes=[1, 1, 1, 0],
strides=[1, 1],
dilations=[1, 2],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=np.zeros([0]))
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2D2x2Depth3ValidBackpropFilterDilation2x2(self, data_format):
self._VerifyValues(
input_sizes=[1, 3, 4, 3],
filter_sizes=[2, 2, 3, 3],
out_backprop_sizes=[1, 1, 2, 3],
strides=[1, 1],
dilations=[2, 2],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=[
17, 22, 27, 22, 29, 36, 27, 36, 45, 47, 64, 81, 52, 71, 90, 57, 78,
99, 137, 190, 243, 142, 197, 252, 147, 204, 261, 167, 232, 297, 172,
239, 306, 177, 246, 315
])
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2DKernelSizeMatchesInputSizeBackpropFilterDilation2x2(
self, data_format):
self._VerifyValues(
input_sizes=[1, 3, 3, 1],
filter_sizes=[2, 2, 1, 2],
out_backprop_sizes=[1, 1, 1, 2],
strides=[1, 1],
dilations=[2, 2],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=[1, 2, 3, 6, 7, 14, 9, 18])
@parameterized.named_parameters(*DATA_FORMATS)
def testConv2DGroupedFilter(self, data_format):
expected_output = [1, 4, 3, 8, 5, 12, 7, 16]
self._VerifyValues(
input_sizes=[1, 2, 2, 2],
filter_sizes=[2, 2, 1, 2],
out_backprop_sizes=[1, 1, 1, 2],
strides=[1, 1],
padding="VALID",
data_format_src="NHWC",
data_format_dst=data_format,
expected=expected_output)
if __name__ == "__main__":
googletest.main()
| apache-2.0 | -2,187,161,919,965,512,700 | 34.355278 | 80 | 0.588738 | false |
Fat-Zer/FreeCAD_sf_master | src/Mod/Draft/draftfunctions/upgrade.py | 12 | 22633 | # ***************************************************************************
# * Copyright (c) 2009, 2010 Yorik van Havre <[email protected]> *
# * Copyright (c) 2009, 2010 Ken Cline <[email protected]> *
# * Copyright (c) 2020 Eliud Cabrera Castillo <[email protected]> *
# * *
# * 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 upgrade objects by different methods.
See also the `downgrade` function.
"""
## @package downgrade
# \ingroup draftfuctions
# \brief Provides functions to upgrade objects by different methods.
import re
import lazy_loader.lazy_loader as lz
import FreeCAD as App
import draftutils.utils as utils
import draftutils.gui_utils as gui_utils
import draftfunctions.draftify as ext_draftify
import draftfunctions.fuse as fuse
import draftmake.make_line as make_line
import draftmake.make_wire as make_wire
import draftmake.make_block as make_block
from draftutils.messages import _msg, _err
from draftutils.translate import translate
from draftgeoutils.geometry import is_straight_line
# Delay import of module until first use because it is heavy
Part = lz.LazyLoader("Part", globals(), "Part")
DraftGeomUtils = lz.LazyLoader("DraftGeomUtils", globals(), "DraftGeomUtils")
Arch = lz.LazyLoader("Arch", globals(), "Arch")
_DEBUG = False
## \addtogroup draftfuctions
# @{
def upgrade(objects, delete=False, force=None):
"""Upgrade the given objects.
This is a counterpart to `downgrade`.
Parameters
----------
objects: Part::Feature or list
A single object to upgrade or a list
containing various such objects.
delete: bool, optional
It defaults to `False`.
If it is `True`, the old objects are deleted, and only the resulting
object is kept.
force: str, optional
It defaults to `None`.
Its value can be used to force a certain method of upgrading.
It can be any of: `'makeCompound'`, `'closeGroupWires'`,
`'makeSolid'`, `'closeWire'`, `'turnToParts'`, `'makeFusion'`,
`'makeShell'`, `'makeFaces'`, `'draftify'`, `'joinFaces'`,
`'makeSketchFace'`, `'makeWires'`.
Returns
-------
tuple
A tuple containing two lists, a list of new objects
and a list of objects to be deleted.
None
If there is a problem it will return `None`.
See Also
--------
downgrade
"""
_name = "upgrade"
utils.print_header(_name, "Upgrade objects")
if not isinstance(objects, list):
objects = [objects]
delete_list = []
add_list = []
doc = App.ActiveDocument
# definitions of actions to perform
def turnToLine(obj):
"""Turn an edge into a Draft Line."""
p1 = obj.Shape.Vertexes[0].Point
p2 = obj.Shape.Vertexes[-1].Point
newobj = make_line.make_line(p1, p2)
add_list.append(newobj)
delete_list.append(obj)
return newobj
def makeCompound(objectslist):
"""Return a compound object made from the given objects."""
newobj = make_block.make_block(objectslist)
add_list.append(newobj)
return newobj
def closeGroupWires(groupslist):
"""Close every open wire in the given groups."""
result = False
for grp in groupslist:
for obj in grp.Group:
newobj = closeWire(obj)
# add new objects to their respective groups
if newobj:
result = True
grp.addObject(newobj)
return result
def makeSolid(obj):
"""Turn an object into a solid, if possible."""
if obj.Shape.Solids:
return None
sol = None
try:
sol = Part.makeSolid(obj.Shape)
except Part.OCCError:
return None
else:
if sol:
if sol.isClosed():
newobj = doc.addObject("Part::Feature", "Solid")
newobj.Shape = sol
add_list.append(newobj)
delete_list.append(obj)
return newobj
else:
_err(translate("draft","Object must be a closed shape"))
else:
_err(translate("draft","No solid object created"))
return None
def closeWire(obj):
"""Close a wire object, if possible."""
if obj.Shape.Faces:
return None
if len(obj.Shape.Wires) != 1:
return None
if len(obj.Shape.Edges) == 1:
return None
if is_straight_line(obj.Shape) == True:
return None
if utils.get_type(obj) == "Wire":
obj.Closed = True
return True
else:
w = obj.Shape.Wires[0]
if not w.isClosed():
edges = w.Edges
p0 = w.Vertexes[0].Point
p1 = w.Vertexes[-1].Point
if p0 == p1:
# sometimes an open wire can have the same start
# and end points (OCCT bug); in this case,
# although it is not closed, the face works.
f = Part.Face(w)
newobj = doc.addObject("Part::Feature", "Face")
newobj.Shape = f
else:
edges.append(Part.LineSegment(p1, p0).toShape())
w = Part.Wire(Part.__sortEdges__(edges))
newobj = doc.addObject("Part::Feature", "Wire")
newobj.Shape = w
add_list.append(newobj)
delete_list.append(obj)
return newobj
else:
return None
def turnToParts(meshes):
"""Turn given meshes to parts."""
result = False
for mesh in meshes:
sh = Arch.getShapeFromMesh(mesh.Mesh)
if sh:
newobj = doc.addObject("Part::Feature", "Shell")
newobj.Shape = sh
add_list.append(newobj)
delete_list.append(mesh)
result = True
return result
def makeFusion(obj1, obj2=None):
"""Make a Draft or Part fusion between 2 given objects."""
if not obj2 and isinstance(obj1, (list, tuple)):
obj1, obj2 = obj1[0], obj1[1]
newobj = fuse.fuse(obj1, obj2)
if newobj:
add_list.append(newobj)
return newobj
return None
def makeShell(objectslist):
"""Make a shell or compound with the given objects."""
params = App.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft")
preserveFaceColor = params.GetBool("preserveFaceColor") # True
preserveFaceNames = params.GetBool("preserveFaceNames") # True
faces = []
facecolors = [[], []] if preserveFaceColor else None
for obj in objectslist:
faces.extend(obj.Shape.Faces)
if App.GuiUp and preserveFaceColor:
# at this point, obj.Shape.Faces are not in same order as the
# original faces we might have gotten as a result
# of downgrade, nor do they have the same hashCode().
# Nevertheless, they still keep reference to their original
# colors, capture that in facecolors.
# Also, cannot use ShapeColor here, we need a whole array
# matching the colors of the array of faces per object,
# only DiffuseColor has that
facecolors[0].extend(obj.ViewObject.DiffuseColor)
facecolors[1] = faces
sh = Part.makeShell(faces)
if sh:
if sh.Faces:
newobj = doc.addObject("Part::Feature", str(sh.ShapeType))
newobj.Shape = sh
if preserveFaceNames:
firstName = objectslist[0].Label
nameNoTrailNumbers = re.sub(r"\d+$", "", firstName)
newobj.Label = "{} {}".format(newobj.Label,
nameNoTrailNumbers)
if App.GuiUp and preserveFaceColor:
# At this point, sh.Faces are completely new,
# with different hashCodes and different ordering
# from obj.Shape.Faces. Since we cannot compare
# via hashCode(), we have to iterate and use a different
# criteria to find the original matching color
colarray = []
for ind, face in enumerate(newobj.Shape.Faces):
for fcind, fcface in enumerate(facecolors[1]):
if (face.Area == fcface.Area
and face.CenterOfMass == fcface.CenterOfMass):
colarray.append(facecolors[0][fcind])
break
newobj.ViewObject.DiffuseColor = colarray
add_list.append(newobj)
delete_list.extend(objectslist)
return newobj
return None
def joinFaces(objectslist, coplanarity=False, checked=False):
"""Make one big face from selected objects, if possible."""
faces = []
for obj in objectslist:
faces.extend(obj.Shape.Faces)
# check coplanarity if needed
if not checked:
coplanarity = DraftGeomUtils.is_coplanar(faces, 1e-3)
if not coplanarity:
_err(translate("draft","Faces must be coplanar to be refined"))
return None
# fuse faces
fuse_face = faces.pop(0)
for face in faces:
fuse_face = fuse_face.fuse(face)
face = DraftGeomUtils.concatenate(fuse_face)
# to prevent create new object if concatenate fails
if face.isEqual(fuse_face):
face = None
if face:
# several coplanar and non-curved faces,
# they can become a Draft Wire
if (not DraftGeomUtils.hasCurves(face)
and len(face.Wires) == 1):
newobj = make_wire.make_wire(face.Wires[0],
closed=True, face=True)
# if not possible, we do a non-parametric union
else:
newobj = doc.addObject("Part::Feature", "Union")
newobj.Shape = face
add_list.append(newobj)
delete_list.extend(objectslist)
return newobj
return None
def makeSketchFace(obj):
"""Make a face from a sketch."""
face = Part.makeFace(obj.Shape.Wires, "Part::FaceMakerBullseye")
if face:
newobj = doc.addObject("Part::Feature", "Face")
newobj.Shape = face
add_list.append(newobj)
if App.GuiUp:
obj.ViewObject.Visibility = False
return newobj
return None
def makeFaces(objectslist):
"""Make a face from every closed wire in the list."""
result = False
for o in objectslist:
for w in o.Shape.Wires:
try:
f = Part.Face(w)
except Part.OCCError:
pass
else:
newobj = doc.addObject("Part::Feature", "Face")
newobj.Shape = f
add_list.append(newobj)
result = True
if o not in delete_list:
delete_list.append(o)
return result
def makeWires(objectslist):
"""Join edges in the given objects list into wires."""
edges = []
for object in objectslist:
for edge in object.Shape.Edges:
edges.append(edge)
try:
sorted_edges = Part.sortEdges(edges)
if _DEBUG:
for item_sorted_edges in sorted_edges:
for e in item_sorted_edges:
print("Curve: {}".format(e.Curve))
print("first: {}, last: {}".format(e.Vertexes[0].Point,
e.Vertexes[-1].Point))
wires = [Part.Wire(e) for e in sorted_edges]
except Part.OCCError:
return None
else:
for wire in wires:
newobj = doc.addObject("Part::Feature", "Wire")
newobj.Shape = wire
add_list.append(newobj)
# delete object only if there are no links to it
# TODO: A more refined criteria to delete object
for object in objectslist:
if object.InList:
if App.GuiUp:
object.ViewObject.Visibility = False
else:
delete_list.append(object)
return True
return None
# analyzing what we have in our selection
edges = []
wires = []
openwires = []
faces = []
groups = []
parts = []
curves = []
facewires = []
loneedges = []
meshes = []
for ob in objects:
if ob.TypeId == "App::DocumentObjectGroup":
groups.append(ob)
elif hasattr(ob, 'Shape'):
parts.append(ob)
faces.extend(ob.Shape.Faces)
wires.extend(ob.Shape.Wires)
edges.extend(ob.Shape.Edges)
for f in ob.Shape.Faces:
facewires.extend(f.Wires)
wirededges = []
for w in ob.Shape.Wires:
if len(w.Edges) > 1:
for e in w.Edges:
wirededges.append(e.hashCode())
if not w.isClosed():
openwires.append(w)
for e in ob.Shape.Edges:
if DraftGeomUtils.geomType(e) != "Line":
curves.append(e)
if not e.hashCode() in wirededges and not e.isClosed():
loneedges.append(e)
elif ob.isDerivedFrom("Mesh::Feature"):
meshes.append(ob)
objects = parts
if _DEBUG:
print("objects: {}, edges: {}".format(objects, edges))
print("wires: {}, openwires: {}".format(wires, openwires))
print("faces: {}".format(faces))
print("groups: {}, curves: {}".format(groups, curves))
print("facewires: {}, loneedges: {}".format(facewires, loneedges))
if force:
all_func = {"makeCompound" : makeCompound,
"closeGroupWires" : closeGroupWires,
"makeSolid" : makeSolid,
"closeWire" : closeWire,
"turnToParts" : turnToParts,
"makeFusion" : makeFusion,
"makeShell" : makeShell,
"makeFaces" : makeFaces,
"draftify" : ext_draftify.draftify,
"joinFaces" : joinFaces,
"makeSketchFace" : makeSketchFace,
"makeWires" : makeWires,
"turnToLine" : turnToLine}
if force in all_func:
result = all_func[force](objects)
else:
_msg(translate("draft","Upgrade: Unknown force method:") + " " + force)
result = None
else:
# checking faces coplanarity
# The precision needed in Part.makeFace is 1e-7. Here we use a
# higher value to let that function throw the exception when
# joinFaces is called if the precision is insufficient
if faces:
faces_coplanarity = DraftGeomUtils.is_coplanar(faces, 1e-3)
# applying transformations automatically
result = None
# if we have a group: turn each closed wire inside into a face
if groups:
result = closeGroupWires(groups)
if result:
_msg(translate("draft","Found groups: closing each open object inside"))
# if we have meshes, we try to turn them into shapes
elif meshes:
result = turnToParts(meshes)
if result:
_msg(translate("draft","Found meshes: turning into Part shapes"))
# we have only faces here, no lone edges
elif faces and (len(wires) + len(openwires) == len(facewires)):
# we have one shell: we try to make a solid
if len(objects) == 1 and len(faces) > 3 and not faces_coplanarity:
result = makeSolid(objects[0])
if result:
_msg(translate("draft","Found 1 solidifiable object: solidifying it"))
# we have exactly 2 objects: we fuse them
elif len(objects) == 2 and not curves and not faces_coplanarity:
result = makeFusion(objects[0], objects[1])
if result:
_msg(translate("draft","Found 2 objects: fusing them"))
# we have many separate faces: we try to make a shell or compound
elif len(objects) >= 2 and len(faces) > 1 and not loneedges:
result = makeShell(objects)
if result:
_msg(translate("draft","Found several objects: creating a "
+ str(result.Shape.ShapeType)))
# we have faces: we try to join them if they are coplanar
elif len(objects) == 1 and len(faces) > 1:
result = joinFaces(objects, faces_coplanarity, True)
if result:
_msg(translate("draft","Found object with several coplanar faces: refine them"))
# only one object: if not parametric, we "draftify" it
elif (len(objects) == 1
and not objects[0].isDerivedFrom("Part::Part2DObjectPython")):
result = ext_draftify.draftify(objects[0])
if result:
_msg(translate("draft","Found 1 non-parametric objects: draftifying it"))
# in the following cases there are no faces
elif not faces:
# we have only closed wires
if wires and not openwires and not loneedges:
# we have a sketch: extract a face
if (len(objects) == 1
and objects[0].isDerivedFrom("Sketcher::SketchObject")):
result = makeSketchFace(objects[0])
if result:
_msg(translate("draft","Found 1 closed sketch object: creating a face from it"))
# only closed wires
else:
result = makeFaces(objects)
if result:
_msg(translate("draft","Found closed wires: creating faces"))
# wires or edges: we try to join them
elif len(objects) > 1 and len(edges) > 1:
result = makeWires(objects)
if result:
_msg(translate("draft","Found several wires or edges: wiring them"))
# special case, we have only one open wire. We close it,
# unless it has only 1 edge!
elif len(objects) == 1 and len(openwires) == 1:
result = closeWire(objects[0])
_msg(translate("draft","trying: closing it"))
if result:
_msg(translate("draft","Found 1 open wire: closing it"))
# we have only one object that contains one edge
# TODO: improve draftify function
# only one object: if not parametric, we "draftify" it
# elif (len(objects) == 1
# and not objects[0].isDerivedFrom("Part::Part2DObjectPython")):
# result = ext_draftify.draftify(objects[0])
# if result:
# _msg(translate("draft","Found 1 non-parametric objects: draftifying it"))
elif (len(objects) == 1 and len(edges) == 1
and not objects[0].isDerivedFrom("Part::Part2DObjectPython")):
e = objects[0].Shape.Edges[0]
edge_type = DraftGeomUtils.geomType(e)
# currently only support Line and Circle
if edge_type in ("Line", "Circle"):
result = ext_draftify.draftify(objects[0])
if result:
_msg(translate("draft","Found 1 object: draftifying it"))
# only points, no edges
elif not edges and len(objects) > 1:
result = makeCompound(objects)
if result:
_msg(translate("draft","Found points: creating compound"))
# all other cases, if more than 1 object, make a compound
elif len(objects) > 1:
result = makeCompound(objects)
if result:
_msg(translate("draft","Found several non-treatable objects: creating compound"))
# no result has been obtained
if not result:
_msg(translate("draft","Unable to upgrade these objects."))
if delete:
names = []
for o in delete_list:
names.append(o.Name)
delete_list = []
for n in names:
doc.removeObject(n)
gui_utils.select(add_list)
return add_list, delete_list
## @}
| lgpl-2.1 | -5,231,678,830,968,058,000 | 39.633752 | 104 | 0.525207 | false |
h3biomed/ansible | lib/ansible/playbook/role/metadata.py | 18 | 4366 | # (c) 2014 Michael DeHaan, <[email protected]>
#
# 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/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible.errors import AnsibleParserError, AnsibleError
from ansible.module_utils._text import to_native
from ansible.module_utils.six import string_types
from ansible.playbook.attribute import FieldAttribute
from ansible.playbook.base import Base
from ansible.playbook.collectionsearch import CollectionSearch
from ansible.playbook.helpers import load_list_of_roles
from ansible.playbook.role.requirement import RoleRequirement
__all__ = ['RoleMetadata']
class RoleMetadata(Base, CollectionSearch):
'''
This class wraps the parsing and validation of the optional metadata
within each Role (meta/main.yml).
'''
_allow_duplicates = FieldAttribute(isa='bool', default=False)
_dependencies = FieldAttribute(isa='list', default=list)
_galaxy_info = FieldAttribute(isa='GalaxyInfo')
def __init__(self, owner=None):
self._owner = owner
super(RoleMetadata, self).__init__()
@staticmethod
def load(data, owner, variable_manager=None, loader=None):
'''
Returns a new RoleMetadata object based on the datastructure passed in.
'''
if not isinstance(data, dict):
raise AnsibleParserError("the 'meta/main.yml' for role %s is not a dictionary" % owner.get_name())
m = RoleMetadata(owner=owner).load_data(data, variable_manager=variable_manager, loader=loader)
return m
def _load_dependencies(self, attr, ds):
'''
This is a helper loading function for the dependencies list,
which returns a list of RoleInclude objects
'''
roles = []
if ds:
if not isinstance(ds, list):
raise AnsibleParserError("Expected role dependencies to be a list.", obj=self._ds)
for role_def in ds:
if isinstance(role_def, string_types) or 'role' in role_def or 'name' in role_def:
roles.append(role_def)
continue
try:
# role_def is new style: { src: 'galaxy.role,version,name', other_vars: "here" }
def_parsed = RoleRequirement.role_yaml_parse(role_def)
if def_parsed.get('name'):
role_def['name'] = def_parsed['name']
roles.append(role_def)
except AnsibleError as exc:
raise AnsibleParserError(to_native(exc), obj=role_def, orig_exc=exc)
current_role_path = None
if self._owner:
current_role_path = os.path.dirname(self._owner._role_path)
try:
return load_list_of_roles(roles, play=self._owner._play, current_role_path=current_role_path, variable_manager=self._variable_manager,
loader=self._loader)
except AssertionError as e:
raise AnsibleParserError("A malformed list of role dependencies was encountered.", obj=self._ds, orig_exc=e)
def _load_galaxy_info(self, attr, ds):
'''
This is a helper loading function for the galaxy info entry
in the metadata, which returns a GalaxyInfo object rather than
a simple dictionary.
'''
return ds
def serialize(self):
return dict(
allow_duplicates=self._allow_duplicates,
dependencies=self._dependencies
)
def deserialize(self, data):
setattr(self, 'allow_duplicates', data.get('allow_duplicates', False))
setattr(self, 'dependencies', data.get('dependencies', []))
| gpl-3.0 | -6,526,209,749,022,717,000 | 37.637168 | 146 | 0.650481 | false |
angryrancor/kivy | kivy/core/text/__init__.py | 6 | 27224 | '''
Text
====
An abstraction of text creation. Depending of the selected backend, the
accuracy of text rendering may vary.
.. versionchanged:: 1.5.0
:attr:`LabelBase.line_height` added.
.. versionchanged:: 1.0.7
The :class:`LabelBase` does not generate any texture if the text has a
width <= 1.
This is the backend layer for getting text out of different text providers,
you should only be using this directly if your needs aren't fulfilled by the
:class:`~kivy.uix.label.Label`.
Usage example::
from kivy.core.text import Label as CoreLabel
...
...
my_label = CoreLabel()
my_label.text = 'hello'
# the label is usually not drawn until needed, so force it to draw.
my_label.refresh()
# Now access the texture of the label and use it wherever and
# however you may please.
hello_texture = my_label.texture
'''
__all__ = ('LabelBase', 'Label')
import re
import os
from functools import partial
from copy import copy
from kivy import kivy_data_dir
from kivy.utils import platform
from kivy.graphics.texture import Texture
from kivy.core import core_select_lib
from kivy.core.text.text_layout import layout_text, LayoutWord
from kivy.resources import resource_find, resource_add_path
from kivy.compat import PY2
from kivy.setupconfig import USE_SDL2
DEFAULT_FONT = 'DroidSans'
FONT_REGULAR = 0
FONT_ITALIC = 1
FONT_BOLD = 2
FONT_BOLDITALIC = 3
class LabelBase(object):
'''Core text label.
This is the abstract class used by different backends to render text.
.. warning::
The core text label can't be changed at runtime. You must recreate one.
:Parameters:
`font_size`: int, defaults to 12
Font size of the text
`font_name`: str, defaults to DEFAULT_FONT
Font name of the text
`bold`: bool, defaults to False
Activate "bold" text style
`italic`: bool, defaults to False
Activate "italic" text style
`text_size`: tuple, defaults to (None, None)
Add constraint to render the text (inside a bounding box).
If no size is given, the label size will be set to the text size.
`padding`: float, defaults to None
If it's a float, it will set padding_x and padding_y
`padding_x`: float, defaults to 0.0
Left/right padding
`padding_y`: float, defaults to 0.0
Top/bottom padding
`halign`: str, defaults to "left"
Horizontal text alignment inside the bounding box
`valign`: str, defaults to "bottom"
Vertical text alignment inside the bounding box
`shorten`: bool, defaults to False
Indicate whether the label should attempt to shorten its textual
contents as much as possible if a `size` is given.
Setting this to True without an appropriately set size will lead to
unexpected results.
`shorten_from`: str, defaults to `center`
The side from which we should shorten the text from, can be left,
right, or center. E.g. if left, the ellipsis will appear towards
the left side and it will display as much text starting from the
right as possible.
`split_str`: string, defaults to `' '` (space)
The string to use to split the words by when shortening. If empty,
we can split after every character filling up the line as much as
possible.
`max_lines`: int, defaults to 0 (unlimited)
If set, this indicate how maximum line are allowed to render the
text. Works only if a limitation on text_size is set.
`mipmap` : bool, defaults to False
Create a mipmap for the texture
`strip` : bool, defaults to False
Whether each row of text has its leading and trailing spaces
stripped. If `halign` is `justify` it is implicitly True.
`strip_reflow` : bool, defaults to True
Whether text that has been reflowed into a second line should
be striped, even if `strip` is False. This is only in effect when
`size_hint_x` is not None, because otherwise lines are never
split.
`unicode_errors` : str, defaults to `'replace'`
How to handle unicode decode errors. Can be `'strict'`, `'replace'`
or `'ignore'`.
.. versionchanged:: 1.9.0
`strip`, `strip_reflow`, `shorten_from`, `split_str`, and
`unicode_errors` were added.
.. versionchanged:: 1.9.0
`padding_x` and `padding_y` has been fixed to work as expected.
In the past, the text was padded by the negative of their values.
.. versionchanged:: 1.8.0
`max_lines` parameters has been added.
.. versionchanged:: 1.0.8
`size` have been deprecated and replaced with `text_size`.
.. versionchanged:: 1.0.7
The `valign` is now respected. This wasn't the case previously
so you might have an issue in your application if you have not
considered this.
'''
__slots__ = ('options', 'texture', '_label', '_text_size')
_cached_lines = []
_fonts = {}
_fonts_cache = {}
_fonts_dirs = []
_texture_1px = None
def __init__(
self, text='', font_size=12, font_name=DEFAULT_FONT, bold=False,
italic=False, halign='left', valign='bottom', shorten=False,
text_size=None, mipmap=False, color=None, line_height=1.0, strip=False,
strip_reflow=True, shorten_from='center', split_str=' ',
unicode_errors='replace', **kwargs):
# Include system fonts_dir in resource paths.
# This allows us to specify a font from those dirs.
LabelBase.get_system_fonts_dir()
options = {'text': text, 'font_size': font_size,
'font_name': font_name, 'bold': bold, 'italic': italic,
'halign': halign, 'valign': valign, 'shorten': shorten,
'mipmap': mipmap, 'line_height': line_height,
'strip': strip, 'strip_reflow': strip_reflow,
'shorten_from': shorten_from, 'split_str': split_str,
'unicode_errors': unicode_errors}
options['color'] = color or (1, 1, 1, 1)
options['padding'] = kwargs.get('padding', (0, 0))
if not isinstance(options['padding'], (list, tuple)):
options['padding'] = (options['padding'], options['padding'])
options['padding_x'] = kwargs.get('padding_x', options['padding'][0])
options['padding_y'] = kwargs.get('padding_y', options['padding'][1])
if 'size' in kwargs:
options['text_size'] = kwargs['size']
else:
if text_size is None:
options['text_size'] = (None, None)
else:
options['text_size'] = text_size
self._text_size = options['text_size']
self._text = options['text']
self._internal_size = 0, 0 # the real computed text size (inclds pad)
self._cached_lines = []
self.options = options
self.texture = None
self.resolve_font_name()
@staticmethod
def register(name, fn_regular, fn_italic=None, fn_bold=None,
fn_bolditalic=None):
'''Register an alias for a Font.
.. versionadded:: 1.1.0
If you're using a ttf directly, you might not be able to use the
bold/italic properties of
the ttf version. If the font is delivered in multiple files
(one regular, one italic and one bold), then you need to register these
files and use the alias instead.
All the fn_regular/fn_italic/fn_bold parameters are resolved with
:func:`kivy.resources.resource_find`. If fn_italic/fn_bold are None,
fn_regular will be used instead.
'''
fonts = []
for font_type in fn_regular, fn_italic, fn_bold, fn_bolditalic:
if font_type is not None:
font = resource_find(font_type)
if font is None:
raise IOError('File {0}s not found'.format(font_type))
else:
fonts.append(font)
else:
fonts.append(fonts[-1]) # add regular font to list again
LabelBase._fonts[name] = tuple(fonts)
def resolve_font_name(self):
options = self.options
fontname = options['font_name']
fonts = self._fonts
fontscache = self._fonts_cache
# is the font is registered ?
if fontname in fonts:
# return the prefered font for the current bold/italic combinaison
italic = int(options['italic'])
if options['bold']:
bold = FONT_BOLD
else:
bold = FONT_REGULAR
options['font_name_r'] = fonts[fontname][italic | bold]
elif fontname in fontscache:
options['font_name_r'] = fontscache[fontname]
else:
filename = resource_find(fontname)
if not filename:
fontname = fontname + \
('' if fontname.endswith('.ttf') else '.ttf')
filename = resource_find(fontname)
if filename is None:
# XXX for compatibility, check directly in the data dir
filename = os.path.join(kivy_data_dir, fontname)
if not os.path.exists(filename):
raise IOError('Label: File %r not found' % fontname)
fontscache[fontname] = filename
options['font_name_r'] = filename
@staticmethod
def get_system_fonts_dir():
'''Return the Directory used by the system for fonts.
'''
if LabelBase._fonts_dirs:
return LabelBase._fonts_dirs
fdirs = []
if platform == 'linux':
fdirs = [
'/usr/share/fonts/truetype', '/usr/local/share/fonts',
os.path.expanduser('~/.fonts'),
os.path.expanduser('~/.local/share/fonts')]
elif platform == 'macosx':
fdirs = ['/Library/Fonts', '/System/Library/Fonts',
os.path.expanduser('~/Library/Fonts')]
elif platform == 'win':
fdirs = [os.environ['SYSTEMROOT'] + os.sep + 'Fonts']
elif platform == 'ios':
fdirs = ['/System/Library/Fonts']
elif platform == 'android':
fdirs = ['/system/fonts']
if fdirs:
fdirs.append(kivy_data_dir + os.sep + 'fonts')
# let's register the font dirs
rdirs = []
for _dir in fdirs:
if os.path.exists(_dir):
resource_add_path(_dir)
rdirs.append(_dir)
LabelBase._fonts_dirs = rdirs
return rdirs
raise Exception("Unknown Platform {}".format(platform))
def get_extents(self, text):
'''Return a tuple (width, height) indicating the size of the specified
text'''
return (0, 0)
def get_cached_extents(self):
'''Returns a cached version of the :meth:`get_extents` function.
::
>>> func = self._get_cached_extents()
>>> func
<built-in method size of pygame.font.Font object at 0x01E45650>
>>> func('a line')
(36, 18)
.. warning::
This method returns a size measuring function that is valid
for the font settings used at the time :meth:`get_cached_extents`
was called. Any change in the font settings will render the
returned function incorrect. You should only use this if you know
what you're doing.
.. versionadded:: 1.9.0
'''
return self.get_extents
def _render_begin(self):
pass
def _render_text(self, text, x, y):
pass
def _render_end(self):
pass
def shorten(self, text, margin=2):
''' Shortens the text to fit into a single line by the width specified
by :attr:`text_size` [0]. If :attr:`text_size` [0] is None, it returns
text text unchanged.
:attr:`split_str` and :attr:`shorten_from` determines how the text is
shortened.
:params:
`text` str, the text to be shortened.
`margin` int, the amount of space to leave between the margins
and the text. This is in addition to :attr:`padding_x`.
:retruns:
the text shortened to fit into a single line.
'''
textwidth = self.get_cached_extents()
uw = self.text_size[0]
if uw is None or not text:
return text
opts = self.options
uw = max(0, int(uw - opts['padding_x'] * 2 - margin))
# if larger, it won't fit so don't even try extents
chr = type(text)
text = text.replace(chr('\n'), chr(' '))
if len(text) <= uw and textwidth(text)[0] <= uw:
return text
c = opts['split_str']
offset = 0 if len(c) else 1
dir = opts['shorten_from'][0]
elps = textwidth('...')[0]
if elps > uw:
if textwidth('..')[0] <= uw:
return '..'
else:
return '.'
uw -= elps
f = partial(text.find, c)
f_rev = partial(text.rfind, c)
# now find the first and last word
e1, s2 = f(), f_rev()
if dir != 'l': # center or right
# no split, or the first word doesn't even fit
if e1 != -1:
l1 = textwidth(text[:e1])[0]
l2 = textwidth(text[s2 + 1:])[0]
if e1 == -1 or l1 + l2 > uw:
if len(c):
opts['split_str'] = ''
res = self.shorten(text, margin)
opts['split_str'] = c
return res
# at this point we do char by char so e1 must be zero
if l1 <= uw:
return chr('{0}...').format(text[:e1])
return chr('...')
# both word fits, and there's at least on split_str
if s2 == e1: # there's only on split_str
return chr('{0}...{1}').format(text[:e1], text[s2 + 1:])
# both the first and last word fits, and they start/end at diff pos
if dir == 'r':
ee1 = f(e1 + 1)
while l2 + textwidth(text[:ee1])[0] <= uw:
e1 = ee1
if e1 == s2:
break
ee1 = f(e1 + 1)
else:
while True:
if l1 <= l2:
ee1 = f(e1 + 1)
l1 = textwidth(text[:ee1])[0]
if l2 + l1 > uw:
break
e1 = ee1
if e1 == s2:
break
else:
ss2 = f_rev(0, s2 - offset)
l2 = textwidth(text[ss2 + 1:])[0]
if l2 + l1 > uw:
break
s2 = ss2
if e1 == s2:
break
else: # left
# no split, or the last word doesn't even fit
if s2 != -1:
l2 = textwidth(text[s2 + (1 if len(c) else -1):])[0]
l1 = textwidth(text[:max(0, e1)])[0]
# if split_str
if s2 == -1 or l2 + l1 > uw:
if len(c):
opts['split_str'] = ''
res = self.shorten(text, margin)
opts['split_str'] = c
return res
return chr('...')
# both word fits, and there's at least on split_str
if s2 == e1: # there's only on split_str
return chr('{0}...{1}').format(text[:e1], text[s2 + 1:])
# both the first and last word fits, and they start/end at diff pos
ss2 = f_rev(0, s2 - offset)
while l1 + textwidth(text[ss2 + 1:])[0] <= uw:
s2 = ss2
if s2 == e1:
break
ss2 = f_rev(0, s2 - offset)
return chr('{0}...{1}').format(text[:e1], text[s2 + 1:])
def _render_real(self):
lines = self._cached_lines
options = None
for line in lines:
if len(line.words): # get opts from first line, first word
options = line.words[0].options
break
if not options: # there was no text to render
self._render_begin()
data = self._render_end()
assert(data)
if data is not None and data.width > 1:
self.texture.blit_data(data)
return
render_text = self._render_text
get_extents = self.get_cached_extents()
uw, uh = options['text_size']
xpad, ypad = options['padding_x'], options['padding_y']
x, y = xpad, ypad # pos in the texture
iw, ih = self._internal_size # the real size of text, not texture
if uw is not None:
uww = uw - 2 * xpad # real width of just text
w, h = self.size
sw = options['space_width']
halign = options['halign']
valign = options['valign']
split = re.split
pat = re.compile('( +)')
self._render_begin()
if valign == 'bottom':
y = h - ih + ypad
elif valign == 'middle':
y = int((h - ih) / 2 + ypad)
for layout_line in lines: # for plain label each line has only one str
lw, lh = layout_line.w, layout_line.h
line = ''
assert len(layout_line.words) < 2
if len(layout_line.words):
last_word = layout_line.words[0]
line = last_word.text
x = xpad
if halign[0] == 'c': # center
x = int((w - lw) / 2.)
elif halign[0] == 'r': # right
x = max(0, int(w - lw - xpad))
# right left justify
# divide left over space between `spaces`
# TODO implement a better method of stretching glyphs?
if (uw is not None and halign[-1] == 'y' and line and not
layout_line.is_last_line):
# number spaces needed to fill, and remainder
n, rem = divmod(max(uww - lw, 0), sw)
n = int(n)
words = None
if n or rem:
# there's no trailing space when justify is selected
words = split(pat, line)
if words is not None and len(words) > 1:
space = type(line)(' ')
# words: every even index is spaces, just add ltr n spaces
for i in range(n):
idx = (2 * i + 1) % (len(words) - 1)
words[idx] = words[idx] + space
if rem:
# render the last word at the edge, also add it to line
ext = get_extents(words[-1])
word = LayoutWord(last_word.options, ext[0], ext[1],
words[-1])
layout_line.words.append(word)
last_word.lw = uww - ext[0] # word was stretched
render_text(words[-1], x + last_word.lw, y)
last_word.text = line = ''.join(words[:-2])
else:
last_word.lw = uww # word was stretched
last_word.text = line = ''.join(words)
layout_line.w = uww # the line occupies full width
if len(line):
layout_line.x = x
layout_line.y = y
render_text(line, x, y)
y += lh
# get data from provider
data = self._render_end()
assert(data)
# If the text is 1px width, usually, the data is black.
# Don't blit that kind of data, otherwise, you have a little black bar.
if data is not None and data.width > 1:
self.texture.blit_data(data)
def render(self, real=False):
'''Return a tuple (width, height) to create the image
with the user constraints. (width, height) includes the padding.
'''
if real:
return self._render_real()
options = copy(self.options)
options['space_width'] = self.get_extents(' ')[0]
options['strip'] = strip = (options['strip'] or
options['halign'][-1] == 'y')
uw, uh = options['text_size'] = self._text_size
text = self.text
if strip:
text = text.strip()
if uw is not None and options['shorten']:
text = self.shorten(text)
self._cached_lines = lines = []
if not text:
return 0, 0
if uh is not None and options['valign'][-1] == 'e': # middle
center = -1 # pos of newline
if len(text) > 1:
middle = int(len(text) // 2)
l, r = text.rfind('\n', 0, middle), text.find('\n', middle)
if l != -1 and r != -1:
center = l if center - l <= r - center else r
elif l != -1:
center = l
elif r != -1:
center = r
# if a newline split text, render from center down and up til uh
if center != -1:
# layout from center down until half uh
w, h, clipped = layout_text(text[center + 1:], lines, (0, 0),
(uw, uh / 2), options, self.get_cached_extents(), True, True)
# now layout from center upwards until uh is reached
w, h, clipped = layout_text(text[:center + 1], lines, (w, h),
(uw, uh), options, self.get_cached_extents(), False, True)
else: # if there's no new line, layout everything
w, h, clipped = layout_text(text, lines, (0, 0), (uw, None),
options, self.get_cached_extents(), True, True)
else: # top or bottom
w, h, clipped = layout_text(text, lines, (0, 0), (uw, uh), options,
self.get_cached_extents(), options['valign'][-1] == 'p', True)
self._internal_size = w, h
if uw:
w = uw
if uh:
h = uh
if h > 1 and w < 2:
w = 2
return int(w), int(h)
def _texture_refresh(self, *l):
self.refresh()
def _texture_fill(self, texture):
# second pass, render for real
self.render(real=True)
def refresh(self):
'''Force re-rendering of the text
'''
self.resolve_font_name()
# first pass, calculating width/height
sz = self.render()
self._size_texture = sz
self._size = (sz[0], sz[1])
# if no text are rendered, return nothing.
width, height = self._size
if width <= 1 or height <= 1:
self.texture = self.texture_1px
return
# create a delayed texture
texture = self.texture
if texture is None or \
width != texture.width or \
height != texture.height:
texture = Texture.create(size=(width, height),
mipmap=self.options['mipmap'],
callback=self._texture_fill)
texture.flip_vertical()
texture.add_reload_observer(self._texture_refresh)
self.texture = texture
else:
texture.ask_update(self._texture_fill)
def _get_text(self):
if PY2:
try:
if isinstance(self._text, unicode):
return self._text
return self._text.decode('utf8')
except AttributeError:
# python 3 support
return str(self._text)
except UnicodeDecodeError:
return self._text
else:
return self._text
def _set_text(self, text):
if text != self._text:
self._text = text
text = property(_get_text, _set_text, doc='Get/Set the text')
label = property(_get_text, _set_text, doc='Get/Set the text')
@property
def texture_1px(self):
if LabelBase._texture_1px is None:
tex = Texture.create(size=(1, 1), colorfmt='rgba')
tex.blit_buffer(b'\x00\x00\x00\x00', colorfmt='rgba')
LabelBase._texture_1px = tex
return LabelBase._texture_1px
@property
def size(self):
return self._size
@property
def width(self):
return self._size[0]
@property
def height(self):
return self._size[1]
@property
def content_width(self):
'''Return the content width; i.e. the width of the text without
any padding.'''
if self.texture is None:
return 0
return self.texture.width - 2 * self.options['padding_x']
@property
def content_height(self):
'''Return the content height; i.e. the height of the text without
any padding.'''
if self.texture is None:
return 0
return self.texture.height - 2 * self.options['padding_y']
@property
def content_size(self):
'''Return the content size (width, height)'''
if self.texture is None:
return (0, 0)
return (self.content_width, self.content_height)
@property
def fontid(self):
'''Return a unique id for all font parameters'''
return str([self.options[x] for x in (
'font_size', 'font_name_r', 'bold', 'italic')])
def _get_text_size(self):
return self._text_size
def _set_text_size(self, x):
self._text_size = x
text_size = property(_get_text_size, _set_text_size,
doc='''Get/set the (width, height) of the '
'contrained rendering box''')
usersize = property(_get_text_size, _set_text_size,
doc='''(deprecated) Use text_size instead.''')
# Load the appropriate provider
label_libs = []
if USE_SDL2:
label_libs += [('sdl2', 'text_sdl2', 'LabelSDL2')]
else:
label_libs += [('pygame', 'text_pygame', 'LabelPygame')]
label_libs += [
('pil', 'text_pil', 'LabelPIL')]
Label = core_select_lib('text', label_libs)
if 'KIVY_DOC' not in os.environ:
if not Label:
from kivy.logger import Logger
import sys
Logger.critical('App: Unable to get a Text provider, abort.')
sys.exit(1)
# For the first initalization, register the default font
Label.register('DroidSans',
'data/fonts/DroidSans.ttf',
'data/fonts/DroidSans-Italic.ttf',
'data/fonts/DroidSans-Bold.ttf',
'data/fonts/DroidSans-BoldItalic.ttf')
| mit | 6,648,953,332,499,671,000 | 35.444444 | 79 | 0.523545 | false |
SmileyChris/easy-thumbnails | setup.py | 1 | 2432 | #!/usr/bin/env python
import codecs
import os
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import easy_thumbnails
class DjangoTests(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
from django.core import management
DSM = 'DJANGO_SETTINGS_MODULE'
if DSM not in os.environ:
os.environ[DSM] = 'easy_thumbnails.tests.settings'
management.execute_from_command_line()
def read_files(*filenames):
"""
Output the contents of one or more files to a single concatenated string.
"""
output = []
for filename in filenames:
f = codecs.open(filename, encoding='utf-8')
try:
output.append(f.read())
finally:
f.close()
return '\n\n'.join(output)
setup(
name='easy-thumbnails',
version=easy_thumbnails.get_version(),
url='http://github.com/SmileyChris/easy-thumbnails',
description='Easy thumbnails for Django',
long_description=read_files('README.rst', 'CHANGES.rst'),
author='Chris Beaven',
author_email='[email protected]',
platforms=['any'],
packages=find_packages(),
include_package_data=True,
install_requires=[
'django>=1.11,<4.0',
'pillow',
],
python_requires='>=3.5',
cmdclass={'test': DjangoTests},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.11',
'Framework :: Django :: 2.2',
'Framework :: Django :: 3.0',
'Framework :: Django :: 3.1',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: Software Development :: Libraries :: Python Modules',
],
zip_safe=False,
)
| bsd-3-clause | -3,170,840,693,045,934,000 | 30.179487 | 79 | 0.60773 | false |
HuimingCheng/AutoGrading | learning/web_Haotian/venv/Lib/site-packages/jinja2/nodes.py | 89 | 30853 | # -*- coding: utf-8 -*-
"""
jinja2.nodes
~~~~~~~~~~~~
This module implements additional nodes derived from the ast base node.
It also provides some node tree helper functions like `in_lineno` and
`get_nodes` used by the parser and translator in order to normalize
python and jinja nodes.
:copyright: (c) 2017 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import types
import operator
from collections import deque
from jinja2.utils import Markup
from jinja2._compat import izip, with_metaclass, text_type, PY2
#: the types we support for context functions
_context_function_types = (types.FunctionType, types.MethodType)
_binop_to_func = {
'*': operator.mul,
'/': operator.truediv,
'//': operator.floordiv,
'**': operator.pow,
'%': operator.mod,
'+': operator.add,
'-': operator.sub
}
_uaop_to_func = {
'not': operator.not_,
'+': operator.pos,
'-': operator.neg
}
_cmpop_to_func = {
'eq': operator.eq,
'ne': operator.ne,
'gt': operator.gt,
'gteq': operator.ge,
'lt': operator.lt,
'lteq': operator.le,
'in': lambda a, b: a in b,
'notin': lambda a, b: a not in b
}
class Impossible(Exception):
"""Raised if the node could not perform a requested action."""
class NodeType(type):
"""A metaclass for nodes that handles the field and attribute
inheritance. fields and attributes from the parent class are
automatically forwarded to the child."""
def __new__(cls, name, bases, d):
for attr in 'fields', 'attributes':
storage = []
storage.extend(getattr(bases[0], attr, ()))
storage.extend(d.get(attr, ()))
assert len(bases) == 1, 'multiple inheritance not allowed'
assert len(storage) == len(set(storage)), 'layout conflict'
d[attr] = tuple(storage)
d.setdefault('abstract', False)
return type.__new__(cls, name, bases, d)
class EvalContext(object):
"""Holds evaluation time information. Custom attributes can be attached
to it in extensions.
"""
def __init__(self, environment, template_name=None):
self.environment = environment
if callable(environment.autoescape):
self.autoescape = environment.autoescape(template_name)
else:
self.autoescape = environment.autoescape
self.volatile = False
def save(self):
return self.__dict__.copy()
def revert(self, old):
self.__dict__.clear()
self.__dict__.update(old)
def get_eval_context(node, ctx):
if ctx is None:
if node.environment is None:
raise RuntimeError('if no eval context is passed, the '
'node must have an attached '
'environment.')
return EvalContext(node.environment)
return ctx
class Node(with_metaclass(NodeType, object)):
"""Baseclass for all Jinja2 nodes. There are a number of nodes available
of different types. There are four major types:
- :class:`Stmt`: statements
- :class:`Expr`: expressions
- :class:`Helper`: helper nodes
- :class:`Template`: the outermost wrapper node
All nodes have fields and attributes. Fields may be other nodes, lists,
or arbitrary values. Fields are passed to the constructor as regular
positional arguments, attributes as keyword arguments. Each node has
two attributes: `lineno` (the line number of the node) and `environment`.
The `environment` attribute is set at the end of the parsing process for
all nodes automatically.
"""
fields = ()
attributes = ('lineno', 'environment')
abstract = True
def __init__(self, *fields, **attributes):
if self.abstract:
raise TypeError('abstract nodes are not instanciable')
if fields:
if len(fields) != len(self.fields):
if not self.fields:
raise TypeError('%r takes 0 arguments' %
self.__class__.__name__)
raise TypeError('%r takes 0 or %d argument%s' % (
self.__class__.__name__,
len(self.fields),
len(self.fields) != 1 and 's' or ''
))
for name, arg in izip(self.fields, fields):
setattr(self, name, arg)
for attr in self.attributes:
setattr(self, attr, attributes.pop(attr, None))
if attributes:
raise TypeError('unknown attribute %r' %
next(iter(attributes)))
def iter_fields(self, exclude=None, only=None):
"""This method iterates over all fields that are defined and yields
``(key, value)`` tuples. Per default all fields are returned, but
it's possible to limit that to some fields by providing the `only`
parameter or to exclude some using the `exclude` parameter. Both
should be sets or tuples of field names.
"""
for name in self.fields:
if (exclude is only is None) or \
(exclude is not None and name not in exclude) or \
(only is not None and name in only):
try:
yield name, getattr(self, name)
except AttributeError:
pass
def iter_child_nodes(self, exclude=None, only=None):
"""Iterates over all direct child nodes of the node. This iterates
over all fields and yields the values of they are nodes. If the value
of a field is a list all the nodes in that list are returned.
"""
for field, item in self.iter_fields(exclude, only):
if isinstance(item, list):
for n in item:
if isinstance(n, Node):
yield n
elif isinstance(item, Node):
yield item
def find(self, node_type):
"""Find the first node of a given type. If no such node exists the
return value is `None`.
"""
for result in self.find_all(node_type):
return result
def find_all(self, node_type):
"""Find all the nodes of a given type. If the type is a tuple,
the check is performed for any of the tuple items.
"""
for child in self.iter_child_nodes():
if isinstance(child, node_type):
yield child
for result in child.find_all(node_type):
yield result
def set_ctx(self, ctx):
"""Reset the context of a node and all child nodes. Per default the
parser will all generate nodes that have a 'load' context as it's the
most common one. This method is used in the parser to set assignment
targets and other nodes to a store context.
"""
todo = deque([self])
while todo:
node = todo.popleft()
if 'ctx' in node.fields:
node.ctx = ctx
todo.extend(node.iter_child_nodes())
return self
def set_lineno(self, lineno, override=False):
"""Set the line numbers of the node and children."""
todo = deque([self])
while todo:
node = todo.popleft()
if 'lineno' in node.attributes:
if node.lineno is None or override:
node.lineno = lineno
todo.extend(node.iter_child_nodes())
return self
def set_environment(self, environment):
"""Set the environment for all nodes."""
todo = deque([self])
while todo:
node = todo.popleft()
node.environment = environment
todo.extend(node.iter_child_nodes())
return self
def __eq__(self, other):
return type(self) is type(other) and \
tuple(self.iter_fields()) == tuple(other.iter_fields())
def __ne__(self, other):
return not self.__eq__(other)
# Restore Python 2 hashing behavior on Python 3
__hash__ = object.__hash__
def __repr__(self):
return '%s(%s)' % (
self.__class__.__name__,
', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
arg in self.fields)
)
def dump(self):
def _dump(node):
if not isinstance(node, Node):
buf.append(repr(node))
return
buf.append('nodes.%s(' % node.__class__.__name__)
if not node.fields:
buf.append(')')
return
for idx, field in enumerate(node.fields):
if idx:
buf.append(', ')
value = getattr(node, field)
if isinstance(value, list):
buf.append('[')
for idx, item in enumerate(value):
if idx:
buf.append(', ')
_dump(item)
buf.append(']')
else:
_dump(value)
buf.append(')')
buf = []
_dump(self)
return ''.join(buf)
class Stmt(Node):
"""Base node for all statements."""
abstract = True
class Helper(Node):
"""Nodes that exist in a specific context only."""
abstract = True
class Template(Node):
"""Node that represents a template. This must be the outermost node that
is passed to the compiler.
"""
fields = ('body',)
class Output(Stmt):
"""A node that holds multiple expressions which are then printed out.
This is used both for the `print` statement and the regular template data.
"""
fields = ('nodes',)
class Extends(Stmt):
"""Represents an extends statement."""
fields = ('template',)
class For(Stmt):
"""The for loop. `target` is the target for the iteration (usually a
:class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
of nodes that are used as loop-body, and `else_` a list of nodes for the
`else` block. If no else node exists it has to be an empty list.
For filtered nodes an expression can be stored as `test`, otherwise `None`.
"""
fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
class If(Stmt):
"""If `test` is true, `body` is rendered, else `else_`."""
fields = ('test', 'body', 'elif_', 'else_')
class Macro(Stmt):
"""A macro definition. `name` is the name of the macro, `args` a list of
arguments and `defaults` a list of defaults if there are any. `body` is
a list of nodes for the macro body.
"""
fields = ('name', 'args', 'defaults', 'body')
class CallBlock(Stmt):
"""Like a macro without a name but a call instead. `call` is called with
the unnamed macro as `caller` argument this node holds.
"""
fields = ('call', 'args', 'defaults', 'body')
class FilterBlock(Stmt):
"""Node for filter sections."""
fields = ('body', 'filter')
class With(Stmt):
"""Specific node for with statements. In older versions of Jinja the
with statement was implemented on the base of the `Scope` node instead.
.. versionadded:: 2.9.3
"""
fields = ('targets', 'values', 'body')
class Block(Stmt):
"""A node that represents a block."""
fields = ('name', 'body', 'scoped')
class Include(Stmt):
"""A node that represents the include tag."""
fields = ('template', 'with_context', 'ignore_missing')
class Import(Stmt):
"""A node that represents the import tag."""
fields = ('template', 'target', 'with_context')
class FromImport(Stmt):
"""A node that represents the from import tag. It's important to not
pass unsafe names to the name attribute. The compiler translates the
attribute lookups directly into getattr calls and does *not* use the
subscript callback of the interface. As exported variables may not
start with double underscores (which the parser asserts) this is not a
problem for regular Jinja code, but if this node is used in an extension
extra care must be taken.
The list of names may contain tuples if aliases are wanted.
"""
fields = ('template', 'names', 'with_context')
class ExprStmt(Stmt):
"""A statement that evaluates an expression and discards the result."""
fields = ('node',)
class Assign(Stmt):
"""Assigns an expression to a target."""
fields = ('target', 'node')
class AssignBlock(Stmt):
"""Assigns a block to a target."""
fields = ('target', 'filter', 'body')
class Expr(Node):
"""Baseclass for all expressions."""
abstract = True
def as_const(self, eval_ctx=None):
"""Return the value of the expression as constant or raise
:exc:`Impossible` if this was not possible.
An :class:`EvalContext` can be provided, if none is given
a default context is created which requires the nodes to have
an attached environment.
.. versionchanged:: 2.4
the `eval_ctx` parameter was added.
"""
raise Impossible()
def can_assign(self):
"""Check if it's possible to assign something to this node."""
return False
class BinExpr(Expr):
"""Baseclass for all binary expressions."""
fields = ('left', 'right')
operator = None
abstract = True
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
# intercepted operators cannot be folded at compile time
if self.environment.sandboxed and \
self.operator in self.environment.intercepted_binops:
raise Impossible()
f = _binop_to_func[self.operator]
try:
return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
except Exception:
raise Impossible()
class UnaryExpr(Expr):
"""Baseclass for all unary expressions."""
fields = ('node',)
operator = None
abstract = True
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
# intercepted operators cannot be folded at compile time
if self.environment.sandboxed and \
self.operator in self.environment.intercepted_unops:
raise Impossible()
f = _uaop_to_func[self.operator]
try:
return f(self.node.as_const(eval_ctx))
except Exception:
raise Impossible()
class Name(Expr):
"""Looks up a name or stores a value in a name.
The `ctx` of the node can be one of the following values:
- `store`: store a value in the name
- `load`: load that name
- `param`: like `store` but if the name was defined as function parameter.
"""
fields = ('name', 'ctx')
def can_assign(self):
return self.name not in ('true', 'false', 'none',
'True', 'False', 'None')
class NSRef(Expr):
"""Reference to a namespace value assignment"""
fields = ('name', 'attr')
def can_assign(self):
# We don't need any special checks here; NSRef assignments have a
# runtime check to ensure the target is a namespace object which will
# have been checked already as it is created using a normal assignment
# which goes through a `Name` node.
return True
class Literal(Expr):
"""Baseclass for literals."""
abstract = True
class Const(Literal):
"""All constant values. The parser will return this node for simple
constants such as ``42`` or ``"foo"`` but it can be used to store more
complex values such as lists too. Only constants with a safe
representation (objects where ``eval(repr(x)) == x`` is true).
"""
fields = ('value',)
def as_const(self, eval_ctx=None):
rv = self.value
if PY2 and type(rv) is text_type and \
self.environment.policies['compiler.ascii_str']:
try:
rv = rv.encode('ascii')
except UnicodeError:
pass
return rv
@classmethod
def from_untrusted(cls, value, lineno=None, environment=None):
"""Return a const object if the value is representable as
constant value in the generated code, otherwise it will raise
an `Impossible` exception.
"""
from .compiler import has_safe_repr
if not has_safe_repr(value):
raise Impossible()
return cls(value, lineno=lineno, environment=environment)
class TemplateData(Literal):
"""A constant template string."""
fields = ('data',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
if eval_ctx.autoescape:
return Markup(self.data)
return self.data
class Tuple(Literal):
"""For loop unpacking and some other things like multiple arguments
for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
is used for loading the names or storing.
"""
fields = ('items', 'ctx')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return tuple(x.as_const(eval_ctx) for x in self.items)
def can_assign(self):
for item in self.items:
if not item.can_assign():
return False
return True
class List(Literal):
"""Any list literal such as ``[1, 2, 3]``"""
fields = ('items',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return [x.as_const(eval_ctx) for x in self.items]
class Dict(Literal):
"""Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
:class:`Pair` nodes.
"""
fields = ('items',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return dict(x.as_const(eval_ctx) for x in self.items)
class Pair(Helper):
"""A key, value pair for dicts."""
fields = ('key', 'value')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
class Keyword(Helper):
"""A key, value pair for keyword arguments where key is a string."""
fields = ('key', 'value')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return self.key, self.value.as_const(eval_ctx)
class CondExpr(Expr):
"""A conditional expression (inline if expression). (``{{
foo if bar else baz }}``)
"""
fields = ('test', 'expr1', 'expr2')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if self.test.as_const(eval_ctx):
return self.expr1.as_const(eval_ctx)
# if we evaluate to an undefined object, we better do that at runtime
if self.expr2 is None:
raise Impossible()
return self.expr2.as_const(eval_ctx)
def args_as_const(node, eval_ctx):
args = [x.as_const(eval_ctx) for x in node.args]
kwargs = dict(x.as_const(eval_ctx) for x in node.kwargs)
if node.dyn_args is not None:
try:
args.extend(node.dyn_args.as_const(eval_ctx))
except Exception:
raise Impossible()
if node.dyn_kwargs is not None:
try:
kwargs.update(node.dyn_kwargs.as_const(eval_ctx))
except Exception:
raise Impossible()
return args, kwargs
class Filter(Expr):
"""This node applies a filter on an expression. `name` is the name of
the filter, the rest of the fields are the same as for :class:`Call`.
If the `node` of a filter is `None` the contents of the last buffer are
filtered. Buffers are created by macros and filter blocks.
"""
fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile or self.node is None:
raise Impossible()
# we have to be careful here because we call filter_ below.
# if this variable would be called filter, 2to3 would wrap the
# call in a list beause it is assuming we are talking about the
# builtin filter function here which no longer returns a list in
# python 3. because of that, do not rename filter_ to filter!
filter_ = self.environment.filters.get(self.name)
if filter_ is None or getattr(filter_, 'contextfilter', False):
raise Impossible()
# We cannot constant handle async filters, so we need to make sure
# to not go down this path.
if (
eval_ctx.environment.is_async
and getattr(filter_, 'asyncfiltervariant', False)
):
raise Impossible()
args, kwargs = args_as_const(self, eval_ctx)
args.insert(0, self.node.as_const(eval_ctx))
if getattr(filter_, 'evalcontextfilter', False):
args.insert(0, eval_ctx)
elif getattr(filter_, 'environmentfilter', False):
args.insert(0, self.environment)
try:
return filter_(*args, **kwargs)
except Exception:
raise Impossible()
class Test(Expr):
"""Applies a test on an expression. `name` is the name of the test, the
rest of the fields are the same as for :class:`Call`.
"""
fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
def as_const(self, eval_ctx=None):
test = self.environment.tests.get(self.name)
if test is None:
raise Impossible()
eval_ctx = get_eval_context(self, eval_ctx)
args, kwargs = args_as_const(self, eval_ctx)
args.insert(0, self.node.as_const(eval_ctx))
try:
return test(*args, **kwargs)
except Exception:
raise Impossible()
class Call(Expr):
"""Calls an expression. `args` is a list of arguments, `kwargs` a list
of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
and `dyn_kwargs` has to be either `None` or a node that is used as
node for dynamic positional (``*args``) or keyword (``**kwargs``)
arguments.
"""
fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
class Getitem(Expr):
"""Get an attribute or item from an expression and prefer the item."""
fields = ('node', 'arg', 'ctx')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if self.ctx != 'load':
raise Impossible()
try:
return self.environment.getitem(self.node.as_const(eval_ctx),
self.arg.as_const(eval_ctx))
except Exception:
raise Impossible()
def can_assign(self):
return False
class Getattr(Expr):
"""Get an attribute or item from an expression that is a ascii-only
bytestring and prefer the attribute.
"""
fields = ('node', 'attr', 'ctx')
def as_const(self, eval_ctx=None):
if self.ctx != 'load':
raise Impossible()
try:
eval_ctx = get_eval_context(self, eval_ctx)
return self.environment.getattr(self.node.as_const(eval_ctx),
self.attr)
except Exception:
raise Impossible()
def can_assign(self):
return False
class Slice(Expr):
"""Represents a slice object. This must only be used as argument for
:class:`Subscript`.
"""
fields = ('start', 'stop', 'step')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
def const(obj):
if obj is None:
return None
return obj.as_const(eval_ctx)
return slice(const(self.start), const(self.stop), const(self.step))
class Concat(Expr):
"""Concatenates the list of expressions provided after converting them to
unicode.
"""
fields = ('nodes',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return ''.join(text_type(x.as_const(eval_ctx)) for x in self.nodes)
class Compare(Expr):
"""Compares an expression with some other expressions. `ops` must be a
list of :class:`Operand`\\s.
"""
fields = ('expr', 'ops')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
result = value = self.expr.as_const(eval_ctx)
try:
for op in self.ops:
new_value = op.expr.as_const(eval_ctx)
result = _cmpop_to_func[op.op](value, new_value)
value = new_value
except Exception:
raise Impossible()
return result
class Operand(Helper):
"""Holds an operator and an expression."""
fields = ('op', 'expr')
if __debug__:
Operand.__doc__ += '\nThe following operators are available: ' + \
', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
set(_uaop_to_func) | set(_cmpop_to_func)))
class Mul(BinExpr):
"""Multiplies the left with the right node."""
operator = '*'
class Div(BinExpr):
"""Divides the left by the right node."""
operator = '/'
class FloorDiv(BinExpr):
"""Divides the left by the right node and truncates conver the
result into an integer by truncating.
"""
operator = '//'
class Add(BinExpr):
"""Add the left to the right node."""
operator = '+'
class Sub(BinExpr):
"""Subtract the right from the left node."""
operator = '-'
class Mod(BinExpr):
"""Left modulo right."""
operator = '%'
class Pow(BinExpr):
"""Left to the power of right."""
operator = '**'
class And(BinExpr):
"""Short circuited AND."""
operator = 'and'
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
class Or(BinExpr):
"""Short circuited OR."""
operator = 'or'
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
class Not(UnaryExpr):
"""Negate the expression."""
operator = 'not'
class Neg(UnaryExpr):
"""Make the expression negative."""
operator = '-'
class Pos(UnaryExpr):
"""Make the expression positive (noop for most expressions)"""
operator = '+'
# Helpers for extensions
class EnvironmentAttribute(Expr):
"""Loads an attribute from the environment object. This is useful for
extensions that want to call a callback stored on the environment.
"""
fields = ('name',)
class ExtensionAttribute(Expr):
"""Returns the attribute of an extension bound to the environment.
The identifier is the identifier of the :class:`Extension`.
This node is usually constructed by calling the
:meth:`~jinja2.ext.Extension.attr` method on an extension.
"""
fields = ('identifier', 'name')
class ImportedName(Expr):
"""If created with an import name the import name is returned on node
access. For example ``ImportedName('cgi.escape')`` returns the `escape`
function from the cgi module on evaluation. Imports are optimized by the
compiler so there is no need to assign them to local variables.
"""
fields = ('importname',)
class InternalName(Expr):
"""An internal name in the compiler. You cannot create these nodes
yourself but the parser provides a
:meth:`~jinja2.parser.Parser.free_identifier` method that creates
a new identifier for you. This identifier is not available from the
template and is not threated specially by the compiler.
"""
fields = ('name',)
def __init__(self):
raise TypeError('Can\'t create internal names. Use the '
'`free_identifier` method on a parser.')
class MarkSafe(Expr):
"""Mark the wrapped expression as safe (wrap it as `Markup`)."""
fields = ('expr',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return Markup(self.expr.as_const(eval_ctx))
class MarkSafeIfAutoescape(Expr):
"""Mark the wrapped expression as safe (wrap it as `Markup`) but
only if autoescaping is active.
.. versionadded:: 2.5
"""
fields = ('expr',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
expr = self.expr.as_const(eval_ctx)
if eval_ctx.autoescape:
return Markup(expr)
return expr
class ContextReference(Expr):
"""Returns the current template context. It can be used like a
:class:`Name` node, with a ``'load'`` ctx and will return the
current :class:`~jinja2.runtime.Context` object.
Here an example that assigns the current template name to a
variable named `foo`::
Assign(Name('foo', ctx='store'),
Getattr(ContextReference(), 'name'))
"""
class Continue(Stmt):
"""Continue a loop."""
class Break(Stmt):
"""Break a loop."""
class Scope(Stmt):
"""An artificial scope."""
fields = ('body',)
class OverlayScope(Stmt):
"""An overlay scope for extensions. This is a largely unoptimized scope
that however can be used to introduce completely arbitrary variables into
a sub scope from a dictionary or dictionary like object. The `context`
field has to evaluate to a dictionary object.
Example usage::
OverlayScope(context=self.call_method('get_context'),
body=[...])
.. versionadded:: 2.10
"""
fields = ('context', 'body')
class EvalContextModifier(Stmt):
"""Modifies the eval context. For each option that should be modified,
a :class:`Keyword` has to be added to the :attr:`options` list.
Example to change the `autoescape` setting::
EvalContextModifier(options=[Keyword('autoescape', Const(True))])
"""
fields = ('options',)
class ScopedEvalContextModifier(EvalContextModifier):
"""Modifies the eval context and reverts it later. Works exactly like
:class:`EvalContextModifier` but will only modify the
:class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
"""
fields = ('body',)
# make sure nobody creates custom nodes
def _failing_new(*args, **kwargs):
raise TypeError('can\'t create custom node types')
NodeType.__new__ = staticmethod(_failing_new); del _failing_new
| mit | 2,318,251,839,521,424,000 | 29.883884 | 81 | 0.59683 | false |
sshnaidm/ru | plugin.video.turbofilm.tv/default.py | 2 | 19750 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# *
# *
# * This Program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License as published by
# * the Free Software Foundation; either version 2, 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; see the file COPYING. If not, write to
# * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
# * http://www.gnu.org/copyleft/gpl.html
import urllib, urllib2, cookielib, re, xbmcaddon, string, xbmc, xbmcgui, xbmcplugin, os, httplib, socket
import base64
import random
import sha
__settings__ = xbmcaddon.Addon(id='plugin.video.turbofilm.tv')
__language__ = __settings__.getLocalizedString
USERNAME = __settings__.getSetting('username')
USERPASS = __settings__.getSetting('password')
handle = int(sys.argv[1])
PLUGIN_NAME = 'Turbofilm.TV'
SITE_HOSTNAME = 'turbofilm.tv'
SITEPREF = 'http://%s' % SITE_HOSTNAME
SITE_URL = SITEPREF + '/'
phpsessid_file = os.path.join(xbmc.translatePath('special://temp/'), 'plugin_video_turbofilmtv.sess')
plotdescr_file = os.path.join(xbmc.translatePath('special://temp/'), 'plugin_video_turbofilmtv.plot')
thumb = os.path.join( os.getcwd(), "icon.png" )
def run_once():
global USERNAME, USERPASS
while (Get('/') == None):
user_keyboard = xbmc.Keyboard()
user_keyboard.setHeading(__language__(30001))
user_keyboard.doModal()
if (user_keyboard.isConfirmed()):
USERNAME = user_keyboard.getText()
pass_keyboard = xbmc.Keyboard()
pass_keyboard.setHeading(__language__(30002))
pass_keyboard.setHiddenInput(True)
pass_keyboard.doModal()
if (pass_keyboard.isConfirmed()):
USERPASS = pass_keyboard.getText()
__settings__.setSetting('username', USERNAME)
__settings__.setSetting('password', USERPASS)
else:
return False
else:
return False
return True
def Get(url, ref=None):
use_auth = False
inter = 2
while inter:
wurl = SITEPREF + url
cj = cookielib.CookieJar()
h = urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(h)
urllib2.install_opener(opener)
post = None
if use_auth:
post = urllib.urlencode({'login': USERNAME, 'passwd': USERPASS})
url = SITE_URL
request = urllib2.Request(wurl, post)
request.add_header('User-Agent', 'Opera/9.80 (X11; Linux i686; U; ru) Presto/2.6.30 Version/10.70')
request.add_header('Host', SITE_HOSTNAME)
request.add_header('Accept', 'text/html, application/xml, application/xhtml+xml, */*')
request.add_header('Accept-Language', 'ru,en;q=0.9')
if ref != None:
request.add_header('Referer', ref)
if (os.path.isfile(phpsessid_file) and (not use_auth)):
fh = open(phpsessid_file, 'r')
phpsessid = fh.read()
fh.close()
request.add_header('Cookie', 'IAS_ID=' + phpsessid)
o = urllib2.urlopen(request)
for index, cookie in enumerate(cj):
cookraw = re.compile('<Cookie IAS_ID=(.*?) for.*/>').findall(str(cookie))
if len(cookraw) > 0:
fh = open(phpsessid_file, 'w')
fh.write(cookraw[0])
fh.close()
http = o.read()
o.close()
if (http.find('<div class="loginblock" id="loginblock">') == -1):
return http
else:
use_auth = True
url = '/Signin/'
inter = inter - 1
return None
def get_params():
param=[]
paramstring=sys.argv[2]
if len(paramstring)>=2:
params=sys.argv[2]
cleanedparams=params.replace('?','')
if (params[len(params)-1]=='/'):
params=params[0:len(params)-2]
pairsofparams=cleanedparams.split('&')
param={}
for i in range(len(pairsofparams)):
splitparams={}
splitparams=pairsofparams[i].split('=')
if (len(splitparams))==2:
param[splitparams[0]]=splitparams[1]
return param
def ShowSeries(url):
http = Get(url)
if http == None:
xbmc.output('[%s] ShowSeries() Error 1: Not received data when opening URL=%s' % (PLUGIN_NAME, url))
return
#xbmc.output(http)
raw1 = re.compile('<div id="series">(.*?)<div id="footer">', re.DOTALL).findall(http)
if len(raw1) == 0:
xbmc.output('[%s] ShowSeries() Error 2: r.e. not found it necessary elements. URL=%s' % (PLUGIN_NAME, url))
xbmc.output(http)
return
#xbmc.output(raw1[0])
raw2 = re.compile('\s<a href="(.*?)">\s(.*?)</a>', re.DOTALL).findall(raw1[0])
if len(raw1) == 0:
xbmc.output('[%s] ShowSeries() Error 3: r.e. not found it necessary elements. URL=%s' % (PLUGIN_NAME, url))
xbmc.output(raw1[0])
return
x = 1;
for wurl, http2 in raw2:
raw_img = re.compile('<img src="(.*?)".*/>').findall(http2)
if len(raw_img) == 0:
Thumb = thumb
else:
Thumb = SITEPREF + raw_img[0]
raw_en = re.compile('<span class="serieslistboxen">(.*?)</span>').findall(http2)
if len(raw_en) == 0:
TitleEN = 'No title'
else:
TitleEN = raw_en[0]
raw_ru = re.compile('<span class="serieslistboxru">(.*?)</span>').findall(http2)
if len(raw_ru) == 0:
TitleRU = 'No title'
else:
TitleRU = raw_ru[0]
Descr = ''
raw_des = re.compile('<span class="serieslistboxperstext">(.*?)</span>').findall(http2)
if len(raw_des) != 0:
for cur_des in raw_des:
Descr = Descr + cur_des + '\n'
raw_des2 = re.compile('<span class="serieslistboxdesc">(.*?)</span>').findall(http2)
if len(raw_des2) > 0:
Descr = Descr + raw_des2[0]
sindex = str(x)
#xbmc.output('*** %s Thumb = %s' % (sindex, Thumb))
#xbmc.output('*** %s TitleEN = %s' % (sindex, TitleEN))
#xbmc.output('*** %s TitleRU = %s' % (sindex, TitleRU))
#xbmc.output('*** %s Descr = %s' % (sindex, Descr))
#xbmc.output('*** %s wurl = %s' % (sindex, wurl))
Title = '%s. %s (%s)' % (sindex, TitleRU, TitleEN)
listitem = xbmcgui.ListItem(Title, iconImage = Thumb, thumbnailImage = Thumb)
listitem.setInfo(type = "Video",
infoLabels = {
"Title": Title,
"Plot": Descr,
"FolderName": TitleRU
}
);
listitem.setProperty("Fanart_Image", Thumb);
url = sys.argv[0] + '?mode=OpenSeries&url=' + urllib.quote_plus(wurl) \
+ '&title=' + urllib.quote_plus(Title)
xbmcplugin.addDirectoryItem(handle, url, listitem, True)
x += 1
def OpenSeries(url, title):
http = Get(url, SITEPREF + '/Series/')
if http == None:
xbmc.output('[%s] OpenSeries() Error 1: Not received data when opening URL=%s' % (PLUGIN_NAME, url))
return
raw_topimg = re.compile('<div class="topimgseries">\s*<img src="(.*?)"').findall(http)
if len(raw_topimg) == 0:
TopIMG = thumb
else:
TopIMG = SITEPREF + raw_topimg[0]
raw1 = re.compile('<div class="sserieslistbox">(.*?)<div class="sseriesrightbox">', re.DOTALL).findall(http)
if len(raw1) == 0:
xbmc.output('[%s] OpenSeries() Error 2: r.e. not found it necessary elements. URL=%s' % (PLUGIN_NAME, url))
xbmc.output(http)
return
raw2 = re.compile('<a href="(.+?)">\s(.*?)</a>', re.DOTALL).findall(raw1[0])
if len(raw1) == 0:
xbmc.output('[%s] OpenSeries() Error 3: r.e. not found it necessary elements. URL=%s' % (PLUGIN_NAME, url))
xbmc.output(raw1[0])
return
x = 1
for wurl, http2 in raw2:
#xbmc.output('************** wurl = %s' % wurl)
#xbmc.output('http2 = %s' % http2)
raw_img = re.compile('<img src="(.*?)".*/>').findall(http2)
if len(raw_img) == 0:
Thumb = TopIMG
else:
Thumb = raw_img[0]
raw_en = re.compile('<span class="sserieslistonetxten">(.*?)</span>').findall(http2)
if len(raw_en) == 0:
TitleEN = 'No title'
else:
TitleEN = raw_en[0]
raw_ru = re.compile('<span class="sserieslistonetxtru">(.*?)</span>').findall(http2)
if len(raw_ru) == 0:
TitleRU = 'No title'
else:
TitleRU = raw_ru[0]
raw_se = re.compile(u'<span class="sserieslistonetxtse">Сезон: (.*?)</span>').findall(http2)
if len(raw_se) == 0:
SeaNUM = 'Season not specified'
else:
SeaNUM = raw_se[0]
raw_ep = re.compile('<span class="sserieslistonetxtep">Эпизод: (.*?)</span>').findall(http2)
if len(raw_ep) == 0:
EpiNUM = 'The episode is not specified'
else:
EpiNUM = raw_ep[0]
sindex = str(x)
xbmc.output('*** %s Thumb = %s' % (sindex, Thumb))
xbmc.output('*** %s TitleEN = %s' % (sindex, TitleEN))
xbmc.output('*** %s TitleRU = %s' % (sindex, TitleRU))
xbmc.output('*** %s SeaNUM = %s' % (sindex, SeaNUM))
xbmc.output('*** %s EpiNUM = %s' % (sindex, EpiNUM))
xbmc.output('*** %s wurl = %s' % (sindex, wurl))
Title = 'Episode %s: %s / %s' % (EpiNUM, TitleRU, TitleEN)
Descr = 'Season: %s\nEpisode: %s' % (SeaNUM, EpiNUM)
listitem = xbmcgui.ListItem(Title, iconImage = Thumb, thumbnailImage = Thumb)
listitem.setInfo(type = "Video",
infoLabels = {
"title": Title,
"tvshowtitle": title,
"plot": "",
"episode": EpiNUM,
"season": SeaNUM,
"VideoCodec": "h264"
}
)
listitem.setProperty("Fanart_Image", Thumb)
url = sys.argv[0] + '?mode=Watch&url=' + urllib.quote_plus(wurl) \
+ '&title=' + urllib.quote_plus(Title)
xbmcplugin.addDirectoryItem(handle, url, listitem, False)
x += 1
raw3 = re.compile('<div class="seasonnum">(.*?)</div>', re.DOTALL).findall(http)
if len(raw3) == 0:
xbmc.output('[%s] OpenSeries() Error 4: r.e. not found it necessary elements. URL=%s' % (PLUGIN_NAME, url))
xbmc.output(http)
return
raw4 = re.compile('<a href="(.*?)"><span class=".*">(.*?)</span></a>').findall(raw3[0])
if len(raw4) == 0:
xbmc.output('[%s] OpenSeries() Error 5: r.e. not found it necessary elements. URL=%s' % (PLUGIN_NAME, url))
xbmc.output(raw3[0])
return
for row_url, row_name in raw4:
xbmc.output('*** row_url = %s' % row_url)
xbmc.output('*** row_name = %s' % row_name)
listitem = xbmcgui.ListItem(row_name, iconImage = TopIMG, thumbnailImage = TopIMG)
listitem.setInfo(type = "Video", infoLabels = {
"Title": row_name
} )
url = sys.argv[0] + '?mode=OpenSeries&url=' + urllib.quote_plus(row_url) \
+ '&title=' + urllib.quote_plus(title + ' : ' + row_name)
xbmcplugin.addDirectoryItem(handle, url, listitem, True)
def Watch(url, title, img):
def meta_decoder(param1):
def enc_replace(param1, param2):
loc_4 = []
loc_5 = []
loc_6 = ['2','I','0','=','3','Q','8','V','7','X','G','M','R','U','H','4','1','Z','5','D','N','6','L','9','B','W'];
loc_7 = ['x','u','Y','o','k','n','g','r','m','T','w','f','d','c','e','s','i','l','y','t','p','b','z','a','J','v'];
if (param2 == 'e'):
loc_4 = loc_6
loc_5 = loc_7
if (param2 == 'd'):
loc_4 = loc_7
loc_5 = loc_6
loc_8 = 0
while (loc_8 < len(loc_4)):
param1 = param1.replace(loc_4[loc_8], '___')
param1 = param1.replace(loc_5[loc_8], loc_4[loc_8])
param1 = param1.replace('___', loc_5[loc_8])
loc_8 += 1
return param1
param1 = param1.replace('%2b', '+')
param1 = param1.replace('%3d', '=')
param1 = param1.replace('%2f', '/')
param1 = enc_replace(param1, 'd')
return base64.b64decode(param1)
http = Get(url)
if http == None:
xbmc.output('[%s] Watch() Error 1: Not received data when opening URL=%s' % (PLUGIN_NAME, url))
return
raw1 = re.compile('<input type="hidden" id="metadata" value="(.*)" />').findall(http)
if len(raw1) == 0:
xbmc.output('[%s] Watch() Error 2: r.e. not found it necessary elements. URL=%s' % (PLUGIN_NAME, url))
xbmc.output(http)
return
Metadata = raw1[0]
Plot = 'No plot'
raw2 = re.compile('<span class="textdesc">(.*?)</span>', re.DOTALL).findall(http)
if len(raw2)> 0:
Plot = raw2[0]
eid = '0'
raw3 = re.compile('<input type="hidden" id="eid" value="(.*?)" />').findall(http)
if len(raw3) > 0:
eid = raw3[0]
pid = '0'
raw4 = re.compile('<input type="hidden" id="pid" value="(.*?)" />').findall(http)
if len(raw4) > 0:
pid = raw4[0]
sid = '0'
raw5 = re.compile('<input type="hidden" id="sid" value="(.*?)" />').findall(http)
if len(raw5) > 0:
sid = raw5[0]
epwatch = '0'
raw6 = re.compile('<input type="hidden" id="epwatch" value="(.*?)" />').findall(http)
if len(raw6) > 0:
epwatch = raw6[0]
sewatch = '0'
raw7 = re.compile('<input type="hidden" id="sewatch" value="(.*?)" />').findall(http)
if len(raw7) > 0:
sewatch = raw7[0]
h1 = '0'
raw8 = re.compile('<input type="hidden" id="h1" value="(.*?)" />').findall(http)
if len(raw8) > 0:
h1 = raw8[0]
Hash = '0'
raw9 = re.compile('<input type="hidden" id="hash" value="(.*?)" />').findall(http)
if len(raw9) > 0:
Hash = raw9[0]
xbmc.output('*** eid = %s' % eid)
xbmc.output('*** pid = %s' % pid)
xbmc.output('*** sid = %s' % sid)
xbmc.output('*** epwatch = %s' % epwatch)
xbmc.output('*** sewatch = %s' % sewatch)
xbmc.output('*** h1 = %s' % h1)
xbmc.output('*** Hash = %s' % Hash)
xbmc.output('*** Metadata = %s' % Metadata)
xbmc.output('*** Plot = %s' % Plot)
Meta = meta_decoder(Metadata)
sources2_default = ''
sources2_hq = ''
aspect = '0'
duration = '0'
hq = '1'
Eid = '0'
screen = ''
sizes_default = '0'
sizes_hq = '0'
langs_en = '0'
langs_ru = '0'
subtitles_en = '0'
subtitles_ru = '0'
subtitles_en_sources = ''
subtitles_ru_sources = ''
r1 = re.compile('<movie>(.*?)</movie>', re.DOTALL).findall(Meta)
if len(r1) > 0:
r2 = re.compile('<sources2>(.*?)</sources2>', re.DOTALL).findall(r1[0])
if len(r2) > 0:
r3 = re.compile('<default>(.*?)</default>').findall(r2[0])
if len(r3) > 0:
sources2_default = r3[0]
r3 = re.compile('<hq>(.*?)</hq>').findall(r2[0])
if len(r3) > 0:
sources2_hq = r3[0]
r2 = re.compile('<aspect>(.*?)</aspect>').findall(r1[0])
if len(r2) > 0:
aspect = r2[0]
r2 = re.compile('<duration>(.*?)</duration>').findall(r1[0])
if len(r2) > 0:
duration = r2[0]
r2 = re.compile('<hq>(.*?)</hq>').findall(r1[0])
if len(r2) > 0:
hq = r2[0]
r2 = re.compile('<eid>(.*?)</eid>').findall(r1[0])
if len(r2) > 0:
Eid = r2[0]
r2 = re.compile('<screen>(.*?)</screen>').findall(r1[0])
if len(r2) > 0:
screen = r2[0]
r2 = re.compile('<sizes>(.*?)</sizes>', re.DOTALL).findall(r1[0])
if len(r2) > 0:
r3 = re.compile('<default>(.*?)</default>').findall(r2[0])
if len(r3) > 0:
sizes_default = r3[0]
r3 = re.compile('<hq>(.*?)</hq>').findall(r2[0])
if len(r3) > 0:
sizes_hq = r3[0]
r2 = re.compile('<langs>(.*?)</langs>', re.DOTALL).findall(r1[0])
if len(r2) > 0:
r3 = re.compile('<en>(.*?)</en>').findall(r2[0])
if len(r3) > 0:
langs_en = r3[0]
r3 = re.compile('<ru>(.*?)</ru>').findall(r2[0])
if len(r3) > 0:
langs_ru = r3[0]
r2 = re.compile('<subtitles>(.*?)</subtitles>', re.DOTALL).findall(r1[0])
if len(r2) > 0:
r3 = re.compile('<en>(.*?)</en>').findall(r2[0])
if len(r3) > 0:
subtitles_en = r3[0]
r3 = re.compile('<ru>(.*?)</ru>').findall(r2[0])
if len(r3) > 0:
subtitles_ru = r3[0]
r3 = re.compile('<sources>(.*?)</sources>', re.DOTALL).findall(r2[0])
if len(r3) > 0:
r4 = re.compile('<en>(.*?)</en>').findall(r3[0])
if len(r4) > 0:
subtitles_en_sources = r4[0]
r4 = re.compile('<ru>(.*?)</ru>').findall(r3[0])
if len(r4) > 0:
subtitles_ru = r4[0]
xbmc.output(' sources2_default = %s' % sources2_default)
xbmc.output(' sources2_hq = %s' % sources2_hq)
xbmc.output(' aspect = %s' % aspect)
xbmc.output(' duration = %s' % duration)
xbmc.output(' hq = %s' % hq)
xbmc.output(' Eid = %s' % Eid)
xbmc.output(' screen = %s' % screen)
xbmc.output(' sizes_default = %s' % sizes_default)
xbmc.output(' sizes_hq = %s' % sizes_hq)
xbmc.output(' langs_en = %s' % langs_en)
xbmc.output(' langs_ru = %s' % langs_ru)
xbmc.output(' subtitles_en = %s' % subtitles_en)
xbmc.output(' subtitles_ru = %s' % subtitles_ru)
xbmc.output('subtitles_en_sources = %s' % subtitles_en_sources)
xbmc.output('subtitles_ru_sources = %s' % subtitles_ru_sources)
Hash = Hash[::-1]
Lang = 'ru'
Time = '0'
#p0 = 'http://cdn.turbofilm.tv'
#p0 = 'http://217.199.218.60'
p1 = sha.new(Lang).hexdigest()
p2 = str(eid)
p3 = str(sources2_default)
p4 = str(Time)
p5 = Hash
p6 = sha.new(Hash + str(random.random())).hexdigest()
p7 = sha.new(p6 + eid + 'A2DC51DE0F8BC1E9').hexdigest()
retval = '/%s/%s/%s/%s/%s/%s/%s' % (p1,p2,p3,p4,p5,p6,p7)
xbmc.output ('SRC file retval = %s' % retval)
rurl = url.replace('/', '_')
#dest = os.path.join(xbmc.translatePath('special://temp/'), rurl)
#xbmc.output ('Dest file = %s' % dest)
phpsessid = ''
#req = urllib2.Request(durl)
if os.path.isfile(phpsessid_file):
fh = open(phpsessid_file, 'r')
phpsessid = fh.read()
fh.close()
def PlayURL(path):
conn = httplib.HTTPConnection('cdn.turbofilm.tv', 80, 10)
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.54 Safari/535.2',\
'Host': 'cdn.turbofilm.tv',\
'Accept': '*/*',\
'Accept-Language': 'ru,en;q=0.9',\
'Accept-Charset': 'iso-8859-1, utf-8, utf-16, *;q=0.1',\
'Accept-Encoding': 'deflate, gzip, x-gzip, identity, *;q=0',\
'Referer': 'http://turbofilm.tv/media/swf/Player20.swf',\
'Cookie': 'IAS_ID='+str(phpsessid)+'; _',\
'Cookie2': '$Version=1',\
'Connection': 'Keep-Alive' }
conn.request("GET", path, '', headers)
response = conn.getresponse()
conn.close()
if(response.status == 302):
xbmc.output('OK - response.status == 302')
Location = response.getheader('Location') # + '@'
xbmc.output('Location: %s' % Location)
#item = xbmcgui.ListItem(title, iconImage = thumb, thumbnailImage = thumb)
#item.setInfo(type="Video", infoLabels = {
# "Title": title,
# "Plot": Plot
# } )
h_1 = '|Referer=' + urllib.quote_plus('http://turbofilm.tv/media/swf/Player20.swf')
h_2 = '&User-Agent=' + urllib.quote_plus('Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.54 Safari/535.2')
h_3 = '&Accept=' + urllib.quote_plus('*/*')
h_4 = '&Accept-Language=' + urllib.quote_plus('ru,en;q=0.9')
h_5 = '&Accept-Charset=' + urllib.quote_plus('iso-8859-1, utf-8, utf-16, *;q=0.1')
h_6 = '&Accept-Encoding=' + urllib.quote_plus('deflate, gzip, x-gzip, identity, *;q=0')
h_7 = '&Connection=' + urllib.quote_plus('Keep-Alive')
#
finalUrl = Location + h_1 + h_2 + h_3 + h_4 + h_5 + h_6 + h_7
item = xbmcgui.ListItem(title, iconImage = thumb, thumbnailImage = thumb, path = finalUrl)
item.setInfo(type="Video", infoLabels = {
"Title": title,
"Plot": Plot
} )
item.setProperty("IsPlayable", "true")
item.setProperty('mimetype', 'video/mp4');
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)
xbmc.Player().play(finalUrl, item)
#xbmc.Player().play(finalItem)
return
return
PlayURL(retval)
if run_once():
params = get_params()
mode = None
url = ''
title = ''
ref = ''
img = ''
try:
mode = urllib.unquote_plus(params["mode"])
except:
pass
try:
url = urllib.unquote_plus(params["url"])
except:
pass
try:
title = urllib.unquote_plus(params["title"])
except:
pass
try:
img = urllib.unquote_plus(params["img"])
except:
pass
if mode == None:
ShowSeries('/Series/')
xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
xbmcplugin.endOfDirectory(handle)
elif mode == 'OpenSeries':
OpenSeries(url, title)
xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
xbmcplugin.endOfDirectory(handle)
elif mode == 'Watch':
Watch(url, title, img)
#xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
#xbmcplugin.endOfDirectory(handle) | gpl-2.0 | 7,923,008,056,527,638,000 | 31.097561 | 145 | 0.600284 | false |
open-synergy/opnsynid-hr | hr_employee_training_allowance_job_family_modelling/models/hr_job_grade.py | 1 | 1584 | # -*- coding: utf-8 -*-
# © 2016 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields, api
class HrJobGrade(models.Model):
_inherit = "hr.job_grade"
training_allowance_pricelist_ids = fields.One2many(
string="Training Allowance Pricelist",
comodel_name="hr.job_grade_training_allowance_pricelist",
inverse_name="job_grade_id",
)
@api.multi
def _get_training_allowance_pricelist(self, participant_type):
self.ensure_one()
obj_pricelist = self.env["hr.job_grade_training_allowance_pricelist"]
criteria = [
("job_grade_id", "=", self.id),
("participant_type_id", "=", participant_type.id),
]
pricelists = obj_pricelist.search(criteria)
return pricelists[0].pricelist_id if len(pricelists) > 0 else False
class HrJobGradeTrainingAllowancePricelist(models.Model):
_name = "hr.job_grade_training_allowance_pricelist"
_description = "Job Grade Training Allowance Pricelist"
job_grade_id = fields.Many2one(
string="Job Grade",
comodel_name="hr.job_grade",
required=True,
ondelete="cascade",
)
participant_type_id = fields.Many2one(
string="Participant Type",
comodel_name="hr.training_participant_type",
required=True,
ondelete="restrict",
)
pricelist_id = fields.Many2one(
string="Pricelist",
comodel_name="product.pricelist",
required=True,
ondelete="restrict",
)
| agpl-3.0 | 4,471,841,648,557,866,500 | 30.66 | 77 | 0.637397 | false |
Batterfii/zulip | zerver/test_hooks.py | 13 | 42649 | # -*- coding: utf-8 -*-
from zerver.lib.test_helpers import AuthedTestCase
from zerver.lib.test_runner import slow
from zerver.models import Message
import ujson
class JiraHookTests(AuthedTestCase):
def send_jira_message(self, action):
email = "[email protected]"
api_key = self.get_api_key(email)
url = "/api/v1/external/jira?api_key=%s" % (api_key,)
return self.send_json_payload(email,
url,
self.fixture_data('jira', action),
stream_name="jira",
content_type="application/json")
def test_unknown(self):
email = "[email protected]"
api_key = self.get_api_key(email)
url = "/api/v1/external/jira?api_key=%s" % (api_key,)
result = self.client.post(url, self.fixture_data('jira', 'unknown'),
stream_name="jira",
content_type="application/json")
self.assert_json_error(result, 'Unknown JIRA event type')
def test_custom_stream(self):
email = "[email protected]"
api_key = self.get_api_key(email)
action = 'created'
url = "/api/v1/external/jira?api_key=%s&stream=jira_custom" % (api_key,)
msg = self.send_json_payload(email, url,
self.fixture_data('jira', action),
stream_name="jira_custom",
content_type="application/json")
self.assertEqual(msg.subject, "BUG-15: New bug with hook")
self.assertEqual(msg.content, """Leo Franchi **created** [BUG-15](http://lfranchi.com:8080/browse/BUG-15) priority Major, assigned to **no one**:
> New bug with hook""")
def test_created(self):
msg = self.send_jira_message('created')
self.assertEqual(msg.subject, "BUG-15: New bug with hook")
self.assertEqual(msg.content, """Leo Franchi **created** [BUG-15](http://lfranchi.com:8080/browse/BUG-15) priority Major, assigned to **no one**:
> New bug with hook""")
def test_created_assignee(self):
msg = self.send_jira_message('created_assignee')
self.assertEqual(msg.subject, "TEST-4: Test Created Assignee")
self.assertEqual(msg.content, """Leonardo Franchi [Administrator] **created** [TEST-4](https://zulipp.atlassian.net/browse/TEST-4) priority Major, assigned to **Leonardo Franchi [Administrator]**:
> Test Created Assignee""")
def test_commented(self):
msg = self.send_jira_message('commented')
self.assertEqual(msg.subject, "BUG-15: New bug with hook")
self.assertEqual(msg.content, """Leo Franchi **updated** [BUG-15](http://lfranchi.com:8080/browse/BUG-15) (assigned to @**Othello, the Moor of Venice**):
Adding a comment. Oh, what a comment it is!
""")
def test_commented_markup(self):
msg = self.send_jira_message('commented_markup')
self.assertEqual(msg.subject, "TEST-7: Testing of rich text")
self.assertEqual(msg.content, """Leonardo Franchi [Administrator] **updated** [TEST-7](https://zulipp.atlassian.net/browse/TEST-7):\n\n\nThis is a comment that likes to **exercise** a lot of _different_ `conventions` that `jira uses`.\r\n\r\n~~~\n\r\nthis code is not highlighted, but monospaced\r\n\n~~~\r\n\r\n~~~\n\r\ndef python():\r\n print "likes to be formatted"\r\n\n~~~\r\n\r\n[http://www.google.com](http://www.google.com) is a bare link, and [Google](http://www.google.com) is given a title.\r\n\r\nThanks!\r\n\r\n~~~ quote\n\r\nSomeone said somewhere\r\n\n~~~\n""")
def test_deleted(self):
msg = self.send_jira_message('deleted')
self.assertEqual(msg.subject, "BUG-15: New bug with hook")
self.assertEqual(msg.content, "Leo Franchi **deleted** [BUG-15](http://lfranchi.com:8080/browse/BUG-15)!")
def test_reassigned(self):
msg = self.send_jira_message('reassigned')
self.assertEqual(msg.subject, "BUG-15: New bug with hook")
self.assertEqual(msg.content, """Leo Franchi **updated** [BUG-15](http://lfranchi.com:8080/browse/BUG-15) (assigned to @**Othello, the Moor of Venice**):
* Changed assignee from **None** to @**Othello, the Moor of Venice**
""")
def test_reopened(self):
msg = self.send_jira_message('reopened')
self.assertEqual(msg.subject, "BUG-7: More cowbell polease")
self.assertEqual(msg.content, """Leo Franchi **updated** [BUG-7](http://lfranchi.com:8080/browse/BUG-7) (assigned to @**Othello, the Moor of Venice**):
* Changed resolution from **Fixed** to **None**
* Changed status from **Resolved** to **Reopened**
Re-opened yeah!
""")
def test_resolved(self):
msg = self.send_jira_message('resolved')
self.assertEqual(msg.subject, "BUG-13: Refreshing the page loses the user's current posi...")
self.assertEqual(msg.content, """Leo Franchi **updated** [BUG-13](http://lfranchi.com:8080/browse/BUG-13) (assigned to @**Othello, the Moor of Venice**):
* Changed status from **Open** to **Resolved**
* Changed assignee from **None** to @**Othello, the Moor of Venice**
* Changed resolution from **None** to **Fixed**
Fixed it, finally!
""")
def test_workflow_postfuncion(self):
msg = self.send_jira_message('postfunction_hook')
self.assertEqual(msg.subject, "TEST-5: PostTest")
self.assertEqual(msg.content, """Leo Franchi [Administrator] **transitioned** [TEST-5](https://lfranchi-test.atlassian.net/browse/TEST-5) from Resolved to Reopened""")
def test_workflow_postfunction(self):
msg = self.send_jira_message('postfunction_hook')
self.assertEqual(msg.subject, "TEST-5: PostTest")
self.assertEqual(msg.content, """Leo Franchi [Administrator] **transitioned** [TEST-5](https://lfranchi-test.atlassian.net/browse/TEST-5) from Resolved to Reopened""")
def test_workflow_postfunction_started(self):
msg = self.send_jira_message('postfunction_started')
self.assertEqual(msg.subject, "TEST-7: Gluttony of Post Functions")
self.assertEqual(msg.content, """Leo Franchi [Administrator] **transitioned** [TEST-7](https://lfranchi-test.atlassian.net/browse/TEST-7) from Open to Underway""")
def test_workflow_postfunction_resolved(self):
msg = self.send_jira_message('postfunction_resolved')
self.assertEqual(msg.subject, "TEST-7: Gluttony of Post Functions")
self.assertEqual(msg.content, """Leo Franchi [Administrator] **transitioned** [TEST-7](https://lfranchi-test.atlassian.net/browse/TEST-7) from Open to Resolved""")
def test_mention(self):
msg = self.send_jira_message('watch_mention_updated')
self.assertEqual(msg.subject, "TEST-5: Lunch Decision Needed")
self.assertEqual(msg.content, """Leonardo Franchi [Administrator] **updated** [TEST-5](https://zulipp.atlassian.net/browse/TEST-5) (assigned to @**Othello, the Moor of Venice**):
Making a comment, @**Othello, the Moor of Venice** is watching this issue
""")
def test_priority_updated(self):
msg = self.send_jira_message('updated_priority')
self.assertEqual(msg.subject, "TEST-1: Fix That")
self.assertEqual(msg.content, """Leonardo Franchi [Administrator] **updated** [TEST-1](https://zulipp.atlassian.net/browse/TEST-1) (assigned to **[email protected]**):
* Changed priority from **Critical** to **Major**
""")
class BeanstalkHookTests(AuthedTestCase):
def send_beanstalk_message(self, action):
email = "[email protected]"
data = {'payload': self.fixture_data('beanstalk', action)}
return self.send_json_payload(email, "/api/v1/external/beanstalk",
data,
stream_name="commits",
**self.api_auth(email))
def test_git_single(self):
msg = self.send_beanstalk_message('git_singlecommit')
self.assertEqual(msg.subject, "work-test")
self.assertEqual(msg.content, """Leo Franchi [pushed](http://lfranchi-svn.beanstalkapp.com/work-test) to branch master
* [e50508d](http://lfranchi-svn.beanstalkapp.com/work-test/changesets/e50508df): add some stuff
""")
@slow(0.20, "lots of queries")
def test_git_multiple(self):
msg = self.send_beanstalk_message('git_multiple')
self.assertEqual(msg.subject, "work-test")
self.assertEqual(msg.content, """Leo Franchi [pushed](http://lfranchi-svn.beanstalkapp.com/work-test) to branch master
* [edf529c](http://lfranchi-svn.beanstalkapp.com/work-test/changesets/edf529c7): Added new file
* [c2a191b](http://lfranchi-svn.beanstalkapp.com/work-test/changesets/c2a191b9): Filled in new file with some stuff
* [2009815](http://lfranchi-svn.beanstalkapp.com/work-test/changesets/20098158): More work to fix some bugs
""")
def test_svn_addremove(self):
msg = self.send_beanstalk_message('svn_addremove')
self.assertEqual(msg.subject, "svn r3")
self.assertEqual(msg.content, """Leo Franchi pushed [revision 3](http://lfranchi-svn.beanstalkapp.com/work-test/changesets/3):
> Removed a file and added another one!""")
def test_svn_changefile(self):
msg = self.send_beanstalk_message('svn_changefile')
self.assertEqual(msg.subject, "svn r2")
self.assertEqual(msg.content, """Leo Franchi pushed [revision 2](http://lfranchi-svn.beanstalkapp.com/work-test/changesets/2):
> Added some code""")
class GithubV1HookTests(AuthedTestCase):
push_content = """zbenjamin [pushed](https://github.com/zbenjamin/zulip-test/compare/4f9adc4777d5...b95449196980) to branch master
* [48c329a](https://github.com/zbenjamin/zulip-test/commit/48c329a0b68a9a379ff195ee3f1c1f4ab0b2a89e): Add baz
* [06ebe5f](https://github.com/zbenjamin/zulip-test/commit/06ebe5f472a32f6f31fd2a665f0c7442b69cce72): Baz needs to be longer
* [b954491](https://github.com/zbenjamin/zulip-test/commit/b95449196980507f08209bdfdc4f1d611689b7a8): Final edit to baz, I swear
"""
def test_spam_branch_is_ignored(self):
email = "[email protected]"
api_key = self.get_api_key(email)
stream = 'commits'
data = ujson.loads(self.fixture_data('github', 'v1_push'))
data.update({'email': email,
'api-key': api_key,
'branches': 'dev,staging',
'stream': stream,
'payload': ujson.dumps(data['payload'])})
url = '/api/v1/external/github'
# We subscribe to the stream in this test, even though
# it won't get written, to avoid failing for the wrong
# reason.
self.subscribe_to_stream(email, stream)
prior_count = Message.objects.count()
result = self.client.post(url, data)
self.assert_json_success(result)
after_count = Message.objects.count()
self.assertEqual(prior_count, after_count)
def basic_test(self, fixture_name, stream_name, expected_subject, expected_content, send_stream=False, branches=None):
email = "[email protected]"
api_key = self.get_api_key(email)
data = ujson.loads(self.fixture_data('github', 'v1_' + fixture_name))
data.update({'email': email,
'api-key': api_key,
'payload': ujson.dumps(data['payload'])})
if send_stream:
data['stream'] = stream_name
if branches is not None:
data['branches'] = branches
msg = self.send_json_payload(email, "/api/v1/external/github",
data,
stream_name=stream_name)
self.assertEqual(msg.subject, expected_subject)
self.assertEqual(msg.content, expected_content)
def test_user_specified_branches(self):
self.basic_test('push', 'my_commits', 'zulip-test', self.push_content,
send_stream=True, branches="master,staging")
def test_user_specified_stream(self):
# Around May 2013 the github webhook started to specify the stream.
# Before then, the stream was hard coded to "commits".
self.basic_test('push', 'my_commits', 'zulip-test', self.push_content,
send_stream=True)
def test_legacy_hook(self):
self.basic_test('push', 'commits', 'zulip-test', self.push_content)
def test_issues_opened(self):
self.basic_test('issues_opened', 'issues',
"zulip-test: issue 5: The frobnicator doesn't work",
"zbenjamin opened [issue 5](https://github.com/zbenjamin/zulip-test/issues/5)\n\n~~~ quote\nI tried changing the widgets, but I got:\r\n\r\nPermission denied: widgets are immutable\n~~~")
def test_issue_comment(self):
self.basic_test('issue_comment', 'issues',
"zulip-test: issue 5: The frobnicator doesn't work",
"zbenjamin [commented](https://github.com/zbenjamin/zulip-test/issues/5#issuecomment-23374280) on [issue 5](https://github.com/zbenjamin/zulip-test/issues/5)\n\n~~~ quote\nWhoops, I did something wrong.\r\n\r\nI'm sorry.\n~~~")
def test_issues_closed(self):
self.basic_test('issues_closed', 'issues',
"zulip-test: issue 5: The frobnicator doesn't work",
"zbenjamin closed [issue 5](https://github.com/zbenjamin/zulip-test/issues/5)")
def test_pull_request_opened(self):
self.basic_test('pull_request_opened', 'commits',
"zulip-test: pull request 7: Counting is hard.",
"lfaraone opened [pull request 7](https://github.com/zbenjamin/zulip-test/pull/7)\n\n~~~ quote\nOmitted something I think?\n~~~")
def test_pull_request_closed(self):
self.basic_test('pull_request_closed', 'commits',
"zulip-test: pull request 7: Counting is hard.",
"zbenjamin closed [pull request 7](https://github.com/zbenjamin/zulip-test/pull/7)")
def test_pull_request_synchronize(self):
self.basic_test('pull_request_synchronize', 'commits',
"zulip-test: pull request 13: Even more cowbell.",
"zbenjamin synchronized [pull request 13](https://github.com/zbenjamin/zulip-test/pull/13)")
def test_pull_request_comment(self):
self.basic_test('pull_request_comment', 'commits',
"zulip-test: pull request 9: Less cowbell.",
"zbenjamin [commented](https://github.com/zbenjamin/zulip-test/pull/9#issuecomment-24771110) on [pull request 9](https://github.com/zbenjamin/zulip-test/pull/9)\n\n~~~ quote\nYeah, who really needs more cowbell than we already have?\n~~~")
def test_pull_request_comment_user_specified_stream(self):
self.basic_test('pull_request_comment', 'my_commits',
"zulip-test: pull request 9: Less cowbell.",
"zbenjamin [commented](https://github.com/zbenjamin/zulip-test/pull/9#issuecomment-24771110) on [pull request 9](https://github.com/zbenjamin/zulip-test/pull/9)\n\n~~~ quote\nYeah, who really needs more cowbell than we already have?\n~~~",
send_stream=True)
def test_commit_comment(self):
self.basic_test('commit_comment', 'commits',
"zulip-test: commit 7c994678d2f98797d299abed852d3ff9d0834533",
"zbenjamin [commented](https://github.com/zbenjamin/zulip-test/commit/7c994678d2f98797d299abed852d3ff9d0834533#commitcomment-4252302)\n\n~~~ quote\nAre we sure this is enough cowbell?\n~~~")
def test_commit_comment_line(self):
self.basic_test('commit_comment_line', 'commits',
"zulip-test: commit 7c994678d2f98797d299abed852d3ff9d0834533",
"zbenjamin [commented](https://github.com/zbenjamin/zulip-test/commit/7c994678d2f98797d299abed852d3ff9d0834533#commitcomment-4252307) on `cowbell`, line 13\n\n~~~ quote\nThis line adds /unlucky/ cowbell (because of its line number). We should remove it.\n~~~")
class GithubV2HookTests(AuthedTestCase):
push_content = """zbenjamin [pushed](https://github.com/zbenjamin/zulip-test/compare/4f9adc4777d5...b95449196980) to branch master
* [48c329a](https://github.com/zbenjamin/zulip-test/commit/48c329a0b68a9a379ff195ee3f1c1f4ab0b2a89e): Add baz
* [06ebe5f](https://github.com/zbenjamin/zulip-test/commit/06ebe5f472a32f6f31fd2a665f0c7442b69cce72): Baz needs to be longer
* [b954491](https://github.com/zbenjamin/zulip-test/commit/b95449196980507f08209bdfdc4f1d611689b7a8): Final edit to baz, I swear
"""
def test_spam_branch_is_ignored(self):
email = "[email protected]"
api_key = self.get_api_key(email)
stream = 'commits'
data = ujson.loads(self.fixture_data('github', 'v2_push'))
data.update({'email': email,
'api-key': api_key,
'branches': 'dev,staging',
'stream': stream,
'payload': ujson.dumps(data['payload'])})
url = '/api/v1/external/github'
# We subscribe to the stream in this test, even though
# it won't get written, to avoid failing for the wrong
# reason.
self.subscribe_to_stream(email, stream)
prior_count = Message.objects.count()
result = self.client.post(url, data)
self.assert_json_success(result)
after_count = Message.objects.count()
self.assertEqual(prior_count, after_count)
def basic_test(self, fixture_name, stream_name, expected_subject, expected_content, send_stream=False, branches=None):
email = "[email protected]"
api_key = self.get_api_key(email)
data = ujson.loads(self.fixture_data('github', 'v2_' + fixture_name))
data.update({'email': email,
'api-key': api_key,
'payload': ujson.dumps(data['payload'])})
if send_stream:
data['stream'] = stream_name
if branches is not None:
data['branches'] = branches
msg = self.send_json_payload(email, "/api/v1/external/github",
data,
stream_name=stream_name)
self.assertEqual(msg.subject, expected_subject)
self.assertEqual(msg.content, expected_content)
def test_user_specified_branches(self):
self.basic_test('push', 'my_commits', 'zulip-test', self.push_content,
send_stream=True, branches="master,staging")
def test_user_specified_stream(self):
# Around May 2013 the github webhook started to specify the stream.
# Before then, the stream was hard coded to "commits".
self.basic_test('push', 'my_commits', 'zulip-test', self.push_content,
send_stream=True)
def test_legacy_hook(self):
self.basic_test('push', 'commits', 'zulip-test', self.push_content)
def test_issues_opened(self):
self.basic_test('issues_opened', 'issues',
"zulip-test: issue 5: The frobnicator doesn't work",
"zbenjamin opened [issue 5](https://github.com/zbenjamin/zulip-test/issues/5)\n\n~~~ quote\nI tried changing the widgets, but I got:\r\n\r\nPermission denied: widgets are immutable\n~~~")
def test_issue_comment(self):
self.basic_test('issue_comment', 'issues',
"zulip-test: issue 5: The frobnicator doesn't work",
"zbenjamin [commented](https://github.com/zbenjamin/zulip-test/issues/5#issuecomment-23374280) on [issue 5](https://github.com/zbenjamin/zulip-test/issues/5)\n\n~~~ quote\nWhoops, I did something wrong.\r\n\r\nI'm sorry.\n~~~")
def test_issues_closed(self):
self.basic_test('issues_closed', 'issues',
"zulip-test: issue 5: The frobnicator doesn't work",
"zbenjamin closed [issue 5](https://github.com/zbenjamin/zulip-test/issues/5)")
def test_pull_request_opened(self):
self.basic_test('pull_request_opened', 'commits',
"zulip-test: pull request 7: Counting is hard.",
"lfaraone opened [pull request 7](https://github.com/zbenjamin/zulip-test/pull/7)\n\n~~~ quote\nOmitted something I think?\n~~~")
def test_pull_request_closed(self):
self.basic_test('pull_request_closed', 'commits',
"zulip-test: pull request 7: Counting is hard.",
"zbenjamin closed [pull request 7](https://github.com/zbenjamin/zulip-test/pull/7)")
def test_pull_request_synchronize(self):
self.basic_test('pull_request_synchronize', 'commits',
"zulip-test: pull request 13: Even more cowbell.",
"zbenjamin synchronized [pull request 13](https://github.com/zbenjamin/zulip-test/pull/13)")
def test_pull_request_comment(self):
self.basic_test('pull_request_comment', 'commits',
"zulip-test: pull request 9: Less cowbell.",
"zbenjamin [commented](https://github.com/zbenjamin/zulip-test/pull/9#issuecomment-24771110) on [pull request 9](https://github.com/zbenjamin/zulip-test/pull/9)\n\n~~~ quote\nYeah, who really needs more cowbell than we already have?\n~~~")
def test_pull_request_comment_user_specified_stream(self):
self.basic_test('pull_request_comment', 'my_commits',
"zulip-test: pull request 9: Less cowbell.",
"zbenjamin [commented](https://github.com/zbenjamin/zulip-test/pull/9#issuecomment-24771110) on [pull request 9](https://github.com/zbenjamin/zulip-test/pull/9)\n\n~~~ quote\nYeah, who really needs more cowbell than we already have?\n~~~",
send_stream=True)
def test_commit_comment(self):
self.basic_test('commit_comment', 'commits',
"zulip-test: commit 7c994678d2f98797d299abed852d3ff9d0834533",
"zbenjamin [commented](https://github.com/zbenjamin/zulip-test/commit/7c994678d2f98797d299abed852d3ff9d0834533#commitcomment-4252302)\n\n~~~ quote\nAre we sure this is enough cowbell?\n~~~")
def test_commit_comment_line(self):
self.basic_test('commit_comment_line', 'commits',
"zulip-test: commit 7c994678d2f98797d299abed852d3ff9d0834533",
"zbenjamin [commented](https://github.com/zbenjamin/zulip-test/commit/7c994678d2f98797d299abed852d3ff9d0834533#commitcomment-4252307) on `cowbell`, line 13\n\n~~~ quote\nThis line adds /unlucky/ cowbell (because of its line number). We should remove it.\n~~~")
class PivotalV3HookTests(AuthedTestCase):
def send_pivotal_message(self, name):
email = "[email protected]"
api_key = self.get_api_key(email)
return self.send_json_payload(email, "/api/v1/external/pivotal?api_key=%s&stream=%s" % (api_key,"pivotal"),
self.fixture_data('pivotal', name, file_type='xml'),
stream_name="pivotal",
content_type="application/xml")
def test_accepted(self):
msg = self.send_pivotal_message('accepted')
self.assertEqual(msg.subject, 'My new Feature story')
self.assertEqual(msg.content, 'Leo Franchi accepted "My new Feature story" \
[(view)](https://www.pivotaltracker.com/s/projects/807213/stories/48276573)')
def test_commented(self):
msg = self.send_pivotal_message('commented')
self.assertEqual(msg.subject, 'Comment added')
self.assertEqual(msg.content, 'Leo Franchi added comment: "FIX THIS NOW" \
[(view)](https://www.pivotaltracker.com/s/projects/807213/stories/48276573)')
def test_created(self):
msg = self.send_pivotal_message('created')
self.assertEqual(msg.subject, 'My new Feature story')
self.assertEqual(msg.content, 'Leo Franchi added "My new Feature story" \
(unscheduled feature):\n\n~~~ quote\nThis is my long description\n~~~\n\n \
[(view)](https://www.pivotaltracker.com/s/projects/807213/stories/48276573)')
def test_delivered(self):
msg = self.send_pivotal_message('delivered')
self.assertEqual(msg.subject, 'Another new story')
self.assertEqual(msg.content, 'Leo Franchi delivered "Another new story" \
[(view)](https://www.pivotaltracker.com/s/projects/807213/stories/48278289)')
def test_finished(self):
msg = self.send_pivotal_message('finished')
self.assertEqual(msg.subject, 'Another new story')
self.assertEqual(msg.content, 'Leo Franchi finished "Another new story" \
[(view)](https://www.pivotaltracker.com/s/projects/807213/stories/48278289)')
def test_moved(self):
msg = self.send_pivotal_message('moved')
self.assertEqual(msg.subject, 'My new Feature story')
self.assertEqual(msg.content, 'Leo Franchi edited "My new Feature story" \
[(view)](https://www.pivotaltracker.com/s/projects/807213/stories/48276573)')
def test_rejected(self):
msg = self.send_pivotal_message('rejected')
self.assertEqual(msg.subject, 'Another new story')
self.assertEqual(msg.content, 'Leo Franchi rejected "Another new story" with comments: \
"Not good enough, sorry" [(view)](https://www.pivotaltracker.com/s/projects/807213/stories/48278289)')
def test_started(self):
msg = self.send_pivotal_message('started')
self.assertEqual(msg.subject, 'Another new story')
self.assertEqual(msg.content, 'Leo Franchi started "Another new story" \
[(view)](https://www.pivotaltracker.com/s/projects/807213/stories/48278289)')
def test_created_estimate(self):
msg = self.send_pivotal_message('created_estimate')
self.assertEqual(msg.subject, 'Another new story')
self.assertEqual(msg.content, 'Leo Franchi added "Another new story" \
(unscheduled feature worth 2 story points):\n\n~~~ quote\nSome loong description\n~~~\n\n \
[(view)](https://www.pivotaltracker.com/s/projects/807213/stories/48278289)')
def test_type_changed(self):
msg = self.send_pivotal_message('type_changed')
self.assertEqual(msg.subject, 'My new Feature story')
self.assertEqual(msg.content, 'Leo Franchi edited "My new Feature story" \
[(view)](https://www.pivotaltracker.com/s/projects/807213/stories/48276573)')
class PivotalV5HookTests(AuthedTestCase):
def send_pivotal_message(self, name):
email = "[email protected]"
api_key = self.get_api_key(email)
return self.send_json_payload(email, "/api/v1/external/pivotal?api_key=%s&stream=%s" % (api_key,"pivotal"),
self.fixture_data('pivotal', "v5_" + name, file_type='json'),
stream_name="pivotal",
content_type="application/xml")
def test_accepted(self):
msg = self.send_pivotal_message('accepted')
self.assertEqual(msg.subject, '#63486316: Story of the Year')
self.assertEqual(msg.content, """Leo Franchi updated [Hard Code](https://www.pivotaltracker.com/s/projects/807213): [Story of the Year](http://www.pivotaltracker.com/story/show/63486316):
* state changed from **unstarted** to **accepted**
""")
def test_commented(self):
msg = self.send_pivotal_message('commented')
self.assertEqual(msg.subject, '#63486316: Story of the Year')
self.assertEqual(msg.content, """Leo Franchi added a comment to [Hard Code](https://www.pivotaltracker.com/s/projects/807213): [Story of the Year](http://www.pivotaltracker.com/story/show/63486316):
~~~quote
A comment on the story
~~~""")
def test_created(self):
msg = self.send_pivotal_message('created')
self.assertEqual(msg.subject, '#63495662: Story that I created')
self.assertEqual(msg.content, """Leo Franchi created bug: [Hard Code](https://www.pivotaltracker.com/s/projects/807213): [Story that I created](http://www.pivotaltracker.com/story/show/63495662)
* State is **unscheduled**
* Description is
> What a description""")
def test_delivered(self):
msg = self.send_pivotal_message('delivered')
self.assertEqual(msg.subject, '#63486316: Story of the Year')
self.assertEqual(msg.content, """Leo Franchi updated [Hard Code](https://www.pivotaltracker.com/s/projects/807213): [Story of the Year](http://www.pivotaltracker.com/story/show/63486316):
* state changed from **accepted** to **delivered**
""")
def test_finished(self):
msg = self.send_pivotal_message('finished')
self.assertEqual(msg.subject, '#63486316: Story of the Year')
self.assertEqual(msg.content, """Leo Franchi updated [Hard Code](https://www.pivotaltracker.com/s/projects/807213): [Story of the Year](http://www.pivotaltracker.com/story/show/63486316):
* state changed from **delivered** to **accepted**
""")
def test_moved(self):
msg = self.send_pivotal_message('moved')
self.assertEqual(msg.subject, '#63496066: Pivotal Test')
self.assertEqual(msg.content, """Leo Franchi moved [Hard Code](https://www.pivotaltracker.com/s/projects/807213): [Pivotal Test](http://www.pivotaltracker.com/story/show/63496066) from **unstarted** to **unscheduled**""")
def test_rejected(self):
msg = self.send_pivotal_message('rejected')
self.assertEqual(msg.subject, '#63486316: Story of the Year')
self.assertEqual(msg.content, """Leo Franchi updated [Hard Code](https://www.pivotaltracker.com/s/projects/807213): [Story of the Year](http://www.pivotaltracker.com/story/show/63486316):
* Comment added:
~~~quote
Try again next time
~~~
* state changed from **delivered** to **rejected**
""")
def test_started(self):
msg = self.send_pivotal_message('started')
self.assertEqual(msg.subject, '#63495972: Fresh Story')
self.assertEqual(msg.content, """Leo Franchi updated [Hard Code](https://www.pivotaltracker.com/s/projects/807213): [Fresh Story](http://www.pivotaltracker.com/story/show/63495972):
* state changed from **unstarted** to **started**
""")
def test_created_estimate(self):
msg = self.send_pivotal_message('created_estimate')
self.assertEqual(msg.subject, '#63496066: Pivotal Test')
self.assertEqual(msg.content, """Leo Franchi updated [Hard Code](https://www.pivotaltracker.com/s/projects/807213): [Pivotal Test](http://www.pivotaltracker.com/story/show/63496066):
* estimate is now **3 points**
""")
def test_type_changed(self):
msg = self.send_pivotal_message('type_changed')
self.assertEqual(msg.subject, '#63496066: Pivotal Test')
self.assertEqual(msg.content, """Leo Franchi updated [Hard Code](https://www.pivotaltracker.com/s/projects/807213): [Pivotal Test](http://www.pivotaltracker.com/story/show/63496066):
* estimate changed from 3 to **0 points**
* type changed from **feature** to **bug**
""")
class NewRelicHookTests(AuthedTestCase):
def send_new_relic_message(self, name):
email = "[email protected]"
api_key = self.get_api_key(email)
return self.send_json_payload(email, "/api/v1/external/newrelic?api_key=%s&stream=%s" % (api_key,"newrelic"),
self.fixture_data('newrelic', name, file_type='txt'),
stream_name="newrelic",
content_type="application/x-www-form-urlencoded")
def test_alert(self):
msg = self.send_new_relic_message('alert')
self.assertEqual(msg.subject, "Apdex score fell below critical level of 0.90")
self.assertEqual(msg.content, 'Alert opened on [application name]: \
Apdex score fell below critical level of 0.90\n\
[View alert](https://rpm.newrelc.com/accounts/[account_id]/applications/[application_id]/incidents/[incident_id])')
def test_deployment(self):
msg = self.send_new_relic_message('deployment')
self.assertEqual(msg.subject, 'Test App deploy')
self.assertEqual(msg.content, '`1242` deployed by **Zulip Test**\n\
Description sent via curl\n\nChangelog string')
class StashHookTests(AuthedTestCase):
def test_stash_message(self):
"""
Messages are generated by Stash on a `git push`.
The subject describes the repo and Stash "project". The
content describes the commits pushed.
"""
email = "[email protected]"
msg = self.send_json_payload(
email, "/api/v1/external/stash?stream=commits",
self.fixture_data("stash", "push", file_type="json"),
stream_name="commits",
content_type="application/x-www-form-urlencoded",
**self.api_auth(email))
self.assertEqual(msg.subject, u"Secret project/Operation unicorn: master")
self.assertEqual(msg.content, """`f259e90` was pushed to **master** in **Secret project/Operation unicorn** with:
* `f259e90`: Updating poms ...""")
class FreshdeskHookTests(AuthedTestCase):
def generate_webhook_response(self, fixture):
"""
Helper function to handle the webhook boilerplate.
"""
email = "[email protected]"
return self.send_json_payload(
email, "/api/v1/external/freshdesk?stream=freshdesk",
self.fixture_data("freshdesk", fixture, file_type="json"),
stream_name="freshdesk",
content_type="application/x-www-form-urlencoded",
**self.api_auth(email))
def test_ticket_creation(self):
"""
Messages are generated on ticket creation through Freshdesk's
"Dispatch'r" service.
"""
msg = self.generate_webhook_response("ticket_created")
self.assertEqual(msg.subject, u"#11: Test ticket subject ☃")
self.assertEqual(msg.content, u"""Requester ☃ Bob <[email protected]> created [ticket #11](http://test1234zzz.freshdesk.com/helpdesk/tickets/11):
~~~ quote
Test ticket description ☃.
~~~
Type: **Incident**
Priority: **High**
Status: **Pending**""")
def test_status_change(self):
"""
Messages are generated when a ticket's status changes through
Freshdesk's "Observer" service.
"""
msg = self.generate_webhook_response("status_changed")
self.assertEqual(msg.subject, u"#11: Test ticket subject ☃")
self.assertEqual(msg.content, """Requester Bob <[email protected]> updated [ticket #11](http://test1234zzz.freshdesk.com/helpdesk/tickets/11):
Status: **Resolved** => **Waiting on Customer**""")
def test_priority_change(self):
"""
Messages are generated when a ticket's priority changes through
Freshdesk's "Observer" service.
"""
msg = self.generate_webhook_response("priority_changed")
self.assertEqual(msg.subject, u"#11: Test ticket subject")
self.assertEqual(msg.content, """Requester Bob <[email protected]> updated [ticket #11](http://test1234zzz.freshdesk.com/helpdesk/tickets/11):
Priority: **High** => **Low**""")
def note_change(self, fixture, note_type):
"""
Messages are generated when a note gets added to a ticket through
Freshdesk's "Observer" service.
"""
msg = self.generate_webhook_response(fixture)
self.assertEqual(msg.subject, u"#11: Test ticket subject")
self.assertEqual(msg.content, """Requester Bob <[email protected]> added a %s note to [ticket #11](http://test1234zzz.freshdesk.com/helpdesk/tickets/11).""" % (note_type,))
def test_private_note_change(self):
self.note_change("private_note", "private")
def test_public_note_change(self):
self.note_change("public_note", "public")
def test_inline_image(self):
"""
Freshdesk sends us descriptions as HTML, so we have to make the
descriptions Zulip markdown-friendly while still doing our best to
preserve links and images.
"""
msg = self.generate_webhook_response("inline_images")
self.assertEqual(msg.subject, u"#12: Not enough ☃ guinea pigs")
self.assertIn("[guinea_pig.png](http://cdn.freshdesk.com/data/helpdesk/attachments/production/12744808/original/guinea_pig.png)", msg.content)
class ZenDeskHookTests(AuthedTestCase):
def generate_webhook_response(self, ticket_title='User can\'t login',
ticket_id=54, message='Message',
stream_name='zendesk'):
data = {
'ticket_title': ticket_title,
'ticket_id': ticket_id,
'message': message,
'stream': stream_name,
}
email = '[email protected]'
self.subscribe_to_stream(email, stream_name)
result = self.client.post('/api/v1/external/zendesk', data,
**self.api_auth(email))
self.assert_json_success(result)
# Check the correct message was sent
msg = Message.objects.filter().order_by('-id')[0]
self.assertEqual(msg.sender.email, email)
return msg
def test_subject(self):
msg = self.generate_webhook_response(ticket_id=4, ticket_title="Test ticket")
self.assertEqual(msg.subject, '#4: Test ticket')
def test_long_subject(self):
msg = self.generate_webhook_response(ticket_id=4, ticket_title="Test ticket" + '!' * 80)
self.assertEqual(msg.subject, '#4: Test ticket' + '!' * 42 + '...')
def test_content(self):
msg = self.generate_webhook_response(message='New comment:\n> It is better\n* here')
self.assertEqual(msg.content, 'New comment:\n> It is better\n* here')
class PagerDutyHookTests(AuthedTestCase):
def send_webhook(self, data, stream_name, topic=None):
email = '[email protected]'
self.subscribe_to_stream(email, stream_name)
api_key = self.get_api_key(email)
if topic:
url = '/api/v1/external/pagerduty?api_key=%s&stream=%s&topic=%s' % (api_key, stream_name, topic)
else:
url = '/api/v1/external/pagerduty?api_key=%s&stream=%s' % (api_key, stream_name)
result = self.client.post(url, ujson.dumps(data), content_type="application/json")
self.assert_json_success(result)
# Check the correct message was sent
msg = Message.objects.filter().order_by('-id')[0]
self.assertEqual(msg.sender.email, email)
return msg
def test_trigger(self):
data = ujson.loads(self.fixture_data('pagerduty', 'trigger'))
msg = self.send_webhook(data, 'pagerduty')
self.assertEqual(msg.subject, 'incident 3')
self.assertEqual(
msg.content,
':imp: Incident [3](https://zulip-test.pagerduty.com/incidents/P140S4Y) triggered by [Test service](https://zulip-test.pagerduty.com/services/PIL5CUQ) and assigned to [armooo@](https://zulip-test.pagerduty.com/users/POBCFRJ)\n\n>foo'
)
def test_unacknowledge(self):
data = ujson.loads(self.fixture_data('pagerduty', 'unacknowledge'))
msg = self.send_webhook(data, 'pagerduty')
self.assertEqual(msg.subject, 'incident 3')
self.assertEqual(
msg.content,
':imp: Incident [3](https://zulip-test.pagerduty.com/incidents/P140S4Y) unacknowledged by [Test service](https://zulip-test.pagerduty.com/services/PIL5CUQ) and assigned to [armooo@](https://zulip-test.pagerduty.com/users/POBCFRJ)\n\n>foo'
)
def test_resolved(self):
data = ujson.loads(self.fixture_data('pagerduty', 'resolved'))
msg = self.send_webhook(data, 'pagerduty')
self.assertEqual(msg.subject, 'incident 1')
self.assertEqual(
msg.content,
':grinning: Incident [1](https://zulip-test.pagerduty.com/incidents/PO1XIJ5) resolved by [armooo@](https://zulip-test.pagerduty.com/users/POBCFRJ)\n\n>It is on fire'
)
def test_auto_resolved(self):
data = ujson.loads(self.fixture_data('pagerduty', 'auto_resolved'))
msg = self.send_webhook(data, 'pagerduty')
self.assertEqual(msg.subject, 'incident 2')
self.assertEqual(
msg.content,
':grinning: Incident [2](https://zulip-test.pagerduty.com/incidents/PX7K9J2) resolved\n\n>new'
)
def test_acknowledge(self):
data = ujson.loads(self.fixture_data('pagerduty', 'acknowledge'))
msg = self.send_webhook(data, 'pagerduty')
self.assertEqual(msg.subject, 'incident 1')
self.assertEqual(
msg.content,
':no_good: Incident [1](https://zulip-test.pagerduty.com/incidents/PO1XIJ5) acknowledged by [armooo@](https://zulip-test.pagerduty.com/users/POBCFRJ)\n\n>It is on fire'
)
def test_no_subject(self):
data = ujson.loads(self.fixture_data('pagerduty', 'mp_fail'))
msg = self.send_webhook(data, 'pagerduty')
self.assertEqual(msg.subject, 'incident 48219')
self.assertEqual(
msg.content,
u':grinning: Incident [48219](https://dropbox.pagerduty.com/incidents/PJKGZF9) resolved\n\n>mp_error_block_down_critical\u2119\u01b4'
)
def test_explicit_subject(self):
data = ujson.loads(self.fixture_data('pagerduty', 'acknowledge'))
msg = self.send_webhook(data, 'pagerduty', topic="my+cool+topic")
self.assertEqual(msg.subject, 'my cool topic')
self.assertEqual(
msg.content,
':no_good: Incident [1](https://zulip-test.pagerduty.com/incidents/PO1XIJ5) acknowledged by [armooo@](https://zulip-test.pagerduty.com/users/POBCFRJ)\n\n>It is on fire'
)
def test_bad_message(self):
data = {'messages': [{'type': 'incident.triggered'}]}
msg = self.send_webhook(data, 'pagerduty')
self.assertEqual(msg.subject, 'pagerduty')
self.assertEqual(
msg.content,
'Unknown pagerduty message\n``` py\n{u\'type\': u\'incident.triggered\'}\n```'
)
def test_unknown_message_type(self):
data = {'messages': [{'type': 'foo'}]}
msg = self.send_webhook(data, 'pagerduty')
self.assertEqual(msg.subject, 'pagerduty')
self.assertEqual(
msg.content,
'Unknown pagerduty message\n``` py\n{u\'type\': u\'foo\'}\n```'
)
| apache-2.0 | -7,605,699,080,188,207,000 | 50.003589 | 587 | 0.638688 | false |
stepos01/ns3-lr-wpan-mlme | src/dsr/bindings/modulegen__gcc_ILP32.py | 2 | 752869 | 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.dsr', 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')
## wifi-preamble.h (module 'wifi'): ns3::WifiPreamble [enumeration]
module.add_enum('WifiPreamble', ['WIFI_PREAMBLE_LONG', 'WIFI_PREAMBLE_SHORT'], import_from_module='ns.wifi')
## wifi-mode.h (module 'wifi'): ns3::WifiModulationClass [enumeration]
module.add_enum('WifiModulationClass', ['WIFI_MOD_CLASS_UNKNOWN', 'WIFI_MOD_CLASS_IR', 'WIFI_MOD_CLASS_FHSS', 'WIFI_MOD_CLASS_DSSS', 'WIFI_MOD_CLASS_ERP_PBCC', 'WIFI_MOD_CLASS_DSSS_OFDM', 'WIFI_MOD_CLASS_ERP_OFDM', 'WIFI_MOD_CLASS_OFDM', 'WIFI_MOD_CLASS_HT'], import_from_module='ns.wifi')
## wifi-phy-standard.h (module 'wifi'): ns3::WifiPhyStandard [enumeration]
module.add_enum('WifiPhyStandard', ['WIFI_PHY_STANDARD_80211a', 'WIFI_PHY_STANDARD_80211b', 'WIFI_PHY_STANDARD_80211g', 'WIFI_PHY_STANDARD_80211_10MHZ', 'WIFI_PHY_STANDARD_80211_5MHZ', 'WIFI_PHY_STANDARD_holland', 'WIFI_PHY_STANDARD_80211p_CCH', 'WIFI_PHY_STANDARD_80211p_SCH'], import_from_module='ns.wifi')
## qos-utils.h (module 'wifi'): ns3::AcIndex [enumeration]
module.add_enum('AcIndex', ['AC_BE', 'AC_BK', 'AC_VI', 'AC_VO', 'AC_BE_NQOS', 'AC_UNDEF'], import_from_module='ns.wifi')
## wifi-mode.h (module 'wifi'): ns3::WifiCodeRate [enumeration]
module.add_enum('WifiCodeRate', ['WIFI_CODE_RATE_UNDEFINED', 'WIFI_CODE_RATE_3_4', 'WIFI_CODE_RATE_2_3', 'WIFI_CODE_RATE_1_2'], 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')
## dsr-helper.h (module 'dsr'): ns3::DsrHelper [class]
module.add_class('DsrHelper')
## dsr-main-helper.h (module 'dsr'): ns3::DsrMainHelper [class]
module.add_class('DsrMainHelper')
## event-garbage-collector.h (module 'tools'): ns3::EventGarbageCollector [class]
module.add_class('EventGarbageCollector', import_from_module='ns.tools')
## 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')
## 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')
## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs [class]
module.add_class('SystemWallClockMs', import_from_module='ns.core')
## tag.h (module 'network'): ns3::Tag [class]
module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase'])
## tag-buffer.h (module 'network'): ns3::TagBuffer [class]
module.add_class('TagBuffer', import_from_module='ns.network')
## timer.h (module 'core'): ns3::Timer [class]
module.add_class('Timer', import_from_module='ns.core')
## timer.h (module 'core'): ns3::Timer::DestroyPolicy [enumeration]
module.add_enum('DestroyPolicy', ['CANCEL_ON_DESTROY', 'REMOVE_ON_DESTROY', 'CHECK_ON_DESTROY'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core')
## timer.h (module 'core'): ns3::Timer::State [enumeration]
module.add_enum('State', ['RUNNING', 'EXPIRED', 'SUSPENDED'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core')
## timer-impl.h (module 'core'): ns3::TimerImpl [class]
module.add_class('TimerImpl', allow_subclassing=True, import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId [class]
module.add_class('TypeId', import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration]
module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct]
module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId'])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct]
module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId'])
## wifi-mode.h (module 'wifi'): ns3::WifiMode [class]
module.add_class('WifiMode', import_from_module='ns.wifi')
## wifi-mode.h (module 'wifi'): ns3::WifiModeFactory [class]
module.add_class('WifiModeFactory', import_from_module='ns.wifi')
## wifi-phy.h (module 'wifi'): ns3::WifiPhyListener [class]
module.add_class('WifiPhyListener', allow_subclassing=True, import_from_module='ns.wifi')
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation [struct]
module.add_class('WifiRemoteStation', import_from_module='ns.wifi')
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationInfo [class]
module.add_class('WifiRemoteStationInfo', import_from_module='ns.wifi')
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState [struct]
module.add_class('WifiRemoteStationState', import_from_module='ns.wifi')
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState [enumeration]
module.add_enum('', ['BRAND_NEW', 'DISASSOC', 'WAIT_ASSOC_TX_OK', 'GOT_ASSOC_TX_OK'], outer_class=root_module['ns3::WifiRemoteStationState'], import_from_module='ns.wifi')
## empty.h (module 'core'): ns3::empty [class]
module.add_class('empty', import_from_module='ns.core')
## int64x64-double.h (module 'core'): ns3::int64x64_t [class]
module.add_class('int64x64_t', import_from_module='ns.core')
## chunk.h (module 'network'): ns3::Chunk [class]
module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase'])
## header.h (module 'network'): ns3::Header [class]
module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk'])
## icmpv4.h (module 'internet'): ns3::Icmpv4DestinationUnreachable [class]
module.add_class('Icmpv4DestinationUnreachable', import_from_module='ns.internet', parent=root_module['ns3::Header'])
## icmpv4.h (module 'internet'): ns3::Icmpv4DestinationUnreachable [enumeration]
module.add_enum('', ['NET_UNREACHABLE', 'HOST_UNREACHABLE', 'PROTOCOL_UNREACHABLE', 'PORT_UNREACHABLE', 'FRAG_NEEDED', 'SOURCE_ROUTE_FAILED'], outer_class=root_module['ns3::Icmpv4DestinationUnreachable'], import_from_module='ns.internet')
## icmpv4.h (module 'internet'): ns3::Icmpv4Echo [class]
module.add_class('Icmpv4Echo', import_from_module='ns.internet', parent=root_module['ns3::Header'])
## icmpv4.h (module 'internet'): ns3::Icmpv4Header [class]
module.add_class('Icmpv4Header', import_from_module='ns.internet', parent=root_module['ns3::Header'])
## icmpv4.h (module 'internet'): ns3::Icmpv4Header [enumeration]
module.add_enum('', ['ECHO_REPLY', 'DEST_UNREACH', 'ECHO', 'TIME_EXCEEDED'], outer_class=root_module['ns3::Icmpv4Header'], import_from_module='ns.internet')
## icmpv4.h (module 'internet'): ns3::Icmpv4TimeExceeded [class]
module.add_class('Icmpv4TimeExceeded', import_from_module='ns.internet', parent=root_module['ns3::Header'])
## icmpv4.h (module 'internet'): ns3::Icmpv4TimeExceeded [enumeration]
module.add_enum('', ['TIME_TO_LIVE', 'FRAGMENT_REASSEMBLY'], outer_class=root_module['ns3::Icmpv4TimeExceeded'], import_from_module='ns.internet')
## 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'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::WifiInformationElement', 'ns3::empty', 'ns3::DefaultDeleter<ns3::WifiInformationElement>'], 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-information-element.h (module 'wifi'): ns3::WifiInformationElement [class]
module.add_class('WifiInformationElement', import_from_module='ns.wifi', parent=root_module['ns3::SimpleRefCount< ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> >'])
## wifi-mac.h (module 'wifi'): ns3::WifiMac [class]
module.add_class('WifiMac', import_from_module='ns.wifi', parent=root_module['ns3::Object'])
## 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')
## wifi-phy.h (module 'wifi'): ns3::WifiPhy [class]
module.add_class('WifiPhy', import_from_module='ns.wifi', parent=root_module['ns3::Object'])
## wifi-phy.h (module 'wifi'): ns3::WifiPhy::State [enumeration]
module.add_enum('State', ['IDLE', 'CCA_BUSY', 'TX', 'RX', 'SWITCHING'], outer_class=root_module['ns3::WifiPhy'], import_from_module='ns.wifi')
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationManager [class]
module.add_class('WifiRemoteStationManager', import_from_module='ns.wifi', parent=root_module['ns3::Object'])
## 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'])
## ssid.h (module 'wifi'): ns3::Ssid [class]
module.add_class('Ssid', import_from_module='ns.wifi', parent=root_module['ns3::WifiInformationElement'])
## ssid.h (module 'wifi'): ns3::SsidChecker [class]
module.add_class('SsidChecker', import_from_module='ns.wifi', parent=root_module['ns3::AttributeChecker'])
## ssid.h (module 'wifi'): ns3::SsidValue [class]
module.add_class('SsidValue', import_from_module='ns.wifi', parent=root_module['ns3::AttributeValue'])
## tcp-l4-protocol.h (module 'internet'): ns3::TcpL4Protocol [class]
module.add_class('TcpL4Protocol', import_from_module='ns.internet', parent=root_module['ns3::IpL4Protocol'])
## 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'])
## udp-l4-protocol.h (module 'internet'): ns3::UdpL4Protocol [class]
module.add_class('UdpL4Protocol', import_from_module='ns.internet', parent=root_module['ns3::IpL4Protocol'])
## uinteger.h (module 'core'): ns3::UintegerValue [class]
module.add_class('UintegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## wifi-mode.h (module 'wifi'): ns3::WifiModeChecker [class]
module.add_class('WifiModeChecker', import_from_module='ns.wifi', parent=root_module['ns3::AttributeChecker'])
## wifi-mode.h (module 'wifi'): ns3::WifiModeValue [class]
module.add_class('WifiModeValue', import_from_module='ns.wifi', 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'])
## icmpv4-l4-protocol.h (module 'internet'): ns3::Icmpv4L4Protocol [class]
module.add_class('Icmpv4L4Protocol', import_from_module='ns.internet', parent=root_module['ns3::IpL4Protocol'])
module.add_container('ns3::WifiModeList', 'ns3::WifiMode', container_type='vector')
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')
typehandlers.add_type_alias('uint8_t', 'ns3::WifiInformationElementId')
typehandlers.add_type_alias('uint8_t*', 'ns3::WifiInformationElementId*')
typehandlers.add_type_alias('uint8_t&', 'ns3::WifiInformationElementId&')
typehandlers.add_type_alias('__gnu_cxx::__normal_iterator< ns3::WifiMode const *, std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > > >', 'ns3::WifiModeListIterator')
typehandlers.add_type_alias('__gnu_cxx::__normal_iterator< ns3::WifiMode const *, std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > > >*', 'ns3::WifiModeListIterator*')
typehandlers.add_type_alias('__gnu_cxx::__normal_iterator< ns3::WifiMode const *, std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > > >&', 'ns3::WifiModeListIterator&')
typehandlers.add_type_alias('std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > >', 'ns3::WifiModeList')
typehandlers.add_type_alias('std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > >*', 'ns3::WifiModeList*')
typehandlers.add_type_alias('std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > >&', 'ns3::WifiModeList&')
## 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 dsr
nested_module = module.add_cpp_namespace('dsr')
register_types_ns3_dsr(nested_module)
## Register a nested module for the namespace internal
nested_module = module.add_cpp_namespace('internal')
register_types_ns3_internal(nested_module)
def register_types_ns3_FatalImpl(module):
root_module = module.get_root()
def register_types_ns3_dsr(module):
root_module = module.get_root()
## dsr-option-header.h (module 'dsr'): ns3::dsr::ErrorType [enumeration]
module.add_enum('ErrorType', ['NODE_UNREACHABLE', 'FLOW_STATE_NOT_SUPPORTED', 'OPTION_NOT_SUPPORTED'])
## dsr-network-queue.h (module 'dsr'): ns3::dsr::DsrMessageType [enumeration]
module.add_enum('DsrMessageType', ['DSR_CONTROL_PACKET', 'DSR_DATA_PACKET'])
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::LinkStates [enumeration]
module.add_enum('LinkStates', ['PROBABLE', 'QUESTIONABLE'])
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::BlackList [struct]
module.add_class('BlackList')
## dsr-fs-header.h (module 'dsr'): ns3::dsr::DsrFsHeader [class]
module.add_class('DsrFsHeader', parent=root_module['ns3::Header'])
## dsr-network-queue.h (module 'dsr'): ns3::dsr::DsrNetworkQueue [class]
module.add_class('DsrNetworkQueue', parent=root_module['ns3::Object'])
## dsr-network-queue.h (module 'dsr'): ns3::dsr::DsrNetworkQueueEntry [class]
module.add_class('DsrNetworkQueueEntry')
## dsr-fs-header.h (module 'dsr'): ns3::dsr::DsrOptionField [class]
module.add_class('DsrOptionField')
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionHeader [class]
module.add_class('DsrOptionHeader', parent=root_module['ns3::Header'])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionHeader::Alignment [struct]
module.add_class('Alignment', outer_class=root_module['ns3::dsr::DsrOptionHeader'])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionPad1Header [class]
module.add_class('DsrOptionPad1Header', parent=root_module['ns3::dsr::DsrOptionHeader'])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionPadnHeader [class]
module.add_class('DsrOptionPadnHeader', parent=root_module['ns3::dsr::DsrOptionHeader'])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionRerrHeader [class]
module.add_class('DsrOptionRerrHeader', parent=root_module['ns3::dsr::DsrOptionHeader'])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionRerrUnreachHeader [class]
module.add_class('DsrOptionRerrUnreachHeader', parent=root_module['ns3::dsr::DsrOptionRerrHeader'])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionRerrUnsupportHeader [class]
module.add_class('DsrOptionRerrUnsupportHeader', parent=root_module['ns3::dsr::DsrOptionRerrHeader'])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionRrepHeader [class]
module.add_class('DsrOptionRrepHeader', parent=root_module['ns3::dsr::DsrOptionHeader'])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionRreqHeader [class]
module.add_class('DsrOptionRreqHeader', parent=root_module['ns3::dsr::DsrOptionHeader'])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionSRHeader [class]
module.add_class('DsrOptionSRHeader', parent=root_module['ns3::dsr::DsrOptionHeader'])
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptions [class]
module.add_class('DsrOptions', parent=root_module['ns3::Object'])
## dsr-routing.h (module 'dsr'): ns3::dsr::DsrRouting [class]
module.add_class('DsrRouting', parent=root_module['ns3::IpL4Protocol'])
## dsr-fs-header.h (module 'dsr'): ns3::dsr::DsrRoutingHeader [class]
module.add_class('DsrRoutingHeader', parent=[root_module['ns3::dsr::DsrFsHeader'], root_module['ns3::dsr::DsrOptionField']])
## dsr-errorbuff.h (module 'dsr'): ns3::dsr::ErrorBuffEntry [class]
module.add_class('ErrorBuffEntry')
## dsr-errorbuff.h (module 'dsr'): ns3::dsr::ErrorBuffer [class]
module.add_class('ErrorBuffer')
## dsr-gratuitous-reply-table.h (module 'dsr'): ns3::dsr::GraReply [class]
module.add_class('GraReply', parent=root_module['ns3::Object'])
## dsr-gratuitous-reply-table.h (module 'dsr'): ns3::dsr::GraReplyEntry [struct]
module.add_class('GraReplyEntry')
## dsr-rcache.h (module 'dsr'): ns3::dsr::Link [struct]
module.add_class('Link')
## dsr-rcache.h (module 'dsr'): ns3::dsr::LinkStab [class]
module.add_class('LinkStab')
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::MaintainBuffEntry [class]
module.add_class('MaintainBuffEntry')
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::MaintainBuffer [class]
module.add_class('MaintainBuffer')
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::NetworkKey [struct]
module.add_class('NetworkKey')
## dsr-rcache.h (module 'dsr'): ns3::dsr::NodeStab [class]
module.add_class('NodeStab')
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::PassiveKey [struct]
module.add_class('PassiveKey')
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCache [class]
module.add_class('RouteCache', parent=root_module['ns3::Object'])
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCache::Neighbor [struct]
module.add_class('Neighbor', outer_class=root_module['ns3::dsr::RouteCache'])
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCacheEntry [class]
module.add_class('RouteCacheEntry')
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::RreqTable [class]
module.add_class('RreqTable', parent=root_module['ns3::Object'])
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::RreqTableEntry [struct]
module.add_class('RreqTableEntry')
## dsr-rsendbuff.h (module 'dsr'): ns3::dsr::SendBuffEntry [class]
module.add_class('SendBuffEntry')
## dsr-rsendbuff.h (module 'dsr'): ns3::dsr::SendBuffer [class]
module.add_class('SendBuffer')
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::SourceRreqEntry [struct]
module.add_class('SourceRreqEntry')
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionAck [class]
module.add_class('DsrOptionAck', parent=root_module['ns3::dsr::DsrOptions'])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionAckHeader [class]
module.add_class('DsrOptionAckHeader', parent=root_module['ns3::dsr::DsrOptionHeader'])
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionAckReq [class]
module.add_class('DsrOptionAckReq', parent=root_module['ns3::dsr::DsrOptions'])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionAckReqHeader [class]
module.add_class('DsrOptionAckReqHeader', parent=root_module['ns3::dsr::DsrOptionHeader'])
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionPad1 [class]
module.add_class('DsrOptionPad1', parent=root_module['ns3::dsr::DsrOptions'])
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionPadn [class]
module.add_class('DsrOptionPadn', parent=root_module['ns3::dsr::DsrOptions'])
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionRerr [class]
module.add_class('DsrOptionRerr', parent=root_module['ns3::dsr::DsrOptions'])
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionRrep [class]
module.add_class('DsrOptionRrep', parent=root_module['ns3::dsr::DsrOptions'])
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionRreq [class]
module.add_class('DsrOptionRreq', parent=root_module['ns3::dsr::DsrOptions'])
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionSR [class]
module.add_class('DsrOptionSR', parent=root_module['ns3::dsr::DsrOptions'])
module.add_container('std::vector< ns3::dsr::DsrNetworkQueueEntry >', 'ns3::dsr::DsrNetworkQueueEntry', container_type='vector')
module.add_container('std::vector< ns3::Ipv4Address >', 'ns3::Ipv4Address', container_type='vector')
module.add_container('std::vector< ns3::dsr::ErrorBuffEntry >', 'ns3::dsr::ErrorBuffEntry', container_type='vector')
module.add_container('std::vector< ns3::dsr::RouteCache::Neighbor >', 'ns3::dsr::RouteCache::Neighbor', container_type='vector')
module.add_container('std::vector< ns3::Ptr< ns3::ArpCache > >', 'ns3::Ptr< ns3::ArpCache >', container_type='vector')
module.add_container('std::list< std::vector< ns3::Ipv4Address > >', 'std::vector< ns3::Ipv4Address >', container_type='list')
module.add_container('std::list< ns3::dsr::RouteCacheEntry >', 'ns3::dsr::RouteCacheEntry', container_type='list')
module.add_container('std::map< ns3::Ipv4Address, ns3::dsr::RreqTableEntry >', ('ns3::Ipv4Address', 'ns3::dsr::RreqTableEntry'), container_type='map')
module.add_container('std::vector< ns3::dsr::SendBuffEntry >', 'ns3::dsr::SendBuffEntry', container_type='vector')
def register_types_ns3_internal(module):
root_module = module.get_root()
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_Ns3DsrHelper_methods(root_module, root_module['ns3::DsrHelper'])
register_Ns3DsrMainHelper_methods(root_module, root_module['ns3::DsrMainHelper'])
register_Ns3EventGarbageCollector_methods(root_module, root_module['ns3::EventGarbageCollector'])
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_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_Ns3SystemWallClockMs_methods(root_module, root_module['ns3::SystemWallClockMs'])
register_Ns3Tag_methods(root_module, root_module['ns3::Tag'])
register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer'])
register_Ns3Timer_methods(root_module, root_module['ns3::Timer'])
register_Ns3TimerImpl_methods(root_module, root_module['ns3::TimerImpl'])
register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId'])
register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation'])
register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation'])
register_Ns3WifiMode_methods(root_module, root_module['ns3::WifiMode'])
register_Ns3WifiModeFactory_methods(root_module, root_module['ns3::WifiModeFactory'])
register_Ns3WifiPhyListener_methods(root_module, root_module['ns3::WifiPhyListener'])
register_Ns3WifiRemoteStation_methods(root_module, root_module['ns3::WifiRemoteStation'])
register_Ns3WifiRemoteStationInfo_methods(root_module, root_module['ns3::WifiRemoteStationInfo'])
register_Ns3WifiRemoteStationState_methods(root_module, root_module['ns3::WifiRemoteStationState'])
register_Ns3Empty_methods(root_module, root_module['ns3::empty'])
register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t'])
register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk'])
register_Ns3Header_methods(root_module, root_module['ns3::Header'])
register_Ns3Icmpv4DestinationUnreachable_methods(root_module, root_module['ns3::Icmpv4DestinationUnreachable'])
register_Ns3Icmpv4Echo_methods(root_module, root_module['ns3::Icmpv4Echo'])
register_Ns3Icmpv4Header_methods(root_module, root_module['ns3::Icmpv4Header'])
register_Ns3Icmpv4TimeExceeded_methods(root_module, root_module['ns3::Icmpv4TimeExceeded'])
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_Ns3SimpleRefCount__Ns3WifiInformationElement_Ns3Empty_Ns3DefaultDeleter__lt__ns3WifiInformationElement__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> >'])
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_Ns3WifiInformationElement_methods(root_module, root_module['ns3::WifiInformationElement'])
register_Ns3WifiMac_methods(root_module, root_module['ns3::WifiMac'])
register_Ns3WifiMacHeader_methods(root_module, root_module['ns3::WifiMacHeader'])
register_Ns3WifiPhy_methods(root_module, root_module['ns3::WifiPhy'])
register_Ns3WifiRemoteStationManager_methods(root_module, root_module['ns3::WifiRemoteStationManager'])
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_Ns3Ssid_methods(root_module, root_module['ns3::Ssid'])
register_Ns3SsidChecker_methods(root_module, root_module['ns3::SsidChecker'])
register_Ns3SsidValue_methods(root_module, root_module['ns3::SsidValue'])
register_Ns3TcpL4Protocol_methods(root_module, root_module['ns3::TcpL4Protocol'])
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_Ns3UdpL4Protocol_methods(root_module, root_module['ns3::UdpL4Protocol'])
register_Ns3UintegerValue_methods(root_module, root_module['ns3::UintegerValue'])
register_Ns3WifiModeChecker_methods(root_module, root_module['ns3::WifiModeChecker'])
register_Ns3WifiModeValue_methods(root_module, root_module['ns3::WifiModeValue'])
register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker'])
register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue'])
register_Ns3Icmpv4L4Protocol_methods(root_module, root_module['ns3::Icmpv4L4Protocol'])
register_Ns3DsrBlackList_methods(root_module, root_module['ns3::dsr::BlackList'])
register_Ns3DsrDsrFsHeader_methods(root_module, root_module['ns3::dsr::DsrFsHeader'])
register_Ns3DsrDsrNetworkQueue_methods(root_module, root_module['ns3::dsr::DsrNetworkQueue'])
register_Ns3DsrDsrNetworkQueueEntry_methods(root_module, root_module['ns3::dsr::DsrNetworkQueueEntry'])
register_Ns3DsrDsrOptionField_methods(root_module, root_module['ns3::dsr::DsrOptionField'])
register_Ns3DsrDsrOptionHeader_methods(root_module, root_module['ns3::dsr::DsrOptionHeader'])
register_Ns3DsrDsrOptionHeaderAlignment_methods(root_module, root_module['ns3::dsr::DsrOptionHeader::Alignment'])
register_Ns3DsrDsrOptionPad1Header_methods(root_module, root_module['ns3::dsr::DsrOptionPad1Header'])
register_Ns3DsrDsrOptionPadnHeader_methods(root_module, root_module['ns3::dsr::DsrOptionPadnHeader'])
register_Ns3DsrDsrOptionRerrHeader_methods(root_module, root_module['ns3::dsr::DsrOptionRerrHeader'])
register_Ns3DsrDsrOptionRerrUnreachHeader_methods(root_module, root_module['ns3::dsr::DsrOptionRerrUnreachHeader'])
register_Ns3DsrDsrOptionRerrUnsupportHeader_methods(root_module, root_module['ns3::dsr::DsrOptionRerrUnsupportHeader'])
register_Ns3DsrDsrOptionRrepHeader_methods(root_module, root_module['ns3::dsr::DsrOptionRrepHeader'])
register_Ns3DsrDsrOptionRreqHeader_methods(root_module, root_module['ns3::dsr::DsrOptionRreqHeader'])
register_Ns3DsrDsrOptionSRHeader_methods(root_module, root_module['ns3::dsr::DsrOptionSRHeader'])
register_Ns3DsrDsrOptions_methods(root_module, root_module['ns3::dsr::DsrOptions'])
register_Ns3DsrDsrRouting_methods(root_module, root_module['ns3::dsr::DsrRouting'])
register_Ns3DsrDsrRoutingHeader_methods(root_module, root_module['ns3::dsr::DsrRoutingHeader'])
register_Ns3DsrErrorBuffEntry_methods(root_module, root_module['ns3::dsr::ErrorBuffEntry'])
register_Ns3DsrErrorBuffer_methods(root_module, root_module['ns3::dsr::ErrorBuffer'])
register_Ns3DsrGraReply_methods(root_module, root_module['ns3::dsr::GraReply'])
register_Ns3DsrGraReplyEntry_methods(root_module, root_module['ns3::dsr::GraReplyEntry'])
register_Ns3DsrLink_methods(root_module, root_module['ns3::dsr::Link'])
register_Ns3DsrLinkStab_methods(root_module, root_module['ns3::dsr::LinkStab'])
register_Ns3DsrMaintainBuffEntry_methods(root_module, root_module['ns3::dsr::MaintainBuffEntry'])
register_Ns3DsrMaintainBuffer_methods(root_module, root_module['ns3::dsr::MaintainBuffer'])
register_Ns3DsrNetworkKey_methods(root_module, root_module['ns3::dsr::NetworkKey'])
register_Ns3DsrNodeStab_methods(root_module, root_module['ns3::dsr::NodeStab'])
register_Ns3DsrPassiveKey_methods(root_module, root_module['ns3::dsr::PassiveKey'])
register_Ns3DsrRouteCache_methods(root_module, root_module['ns3::dsr::RouteCache'])
register_Ns3DsrRouteCacheNeighbor_methods(root_module, root_module['ns3::dsr::RouteCache::Neighbor'])
register_Ns3DsrRouteCacheEntry_methods(root_module, root_module['ns3::dsr::RouteCacheEntry'])
register_Ns3DsrRreqTable_methods(root_module, root_module['ns3::dsr::RreqTable'])
register_Ns3DsrRreqTableEntry_methods(root_module, root_module['ns3::dsr::RreqTableEntry'])
register_Ns3DsrSendBuffEntry_methods(root_module, root_module['ns3::dsr::SendBuffEntry'])
register_Ns3DsrSendBuffer_methods(root_module, root_module['ns3::dsr::SendBuffer'])
register_Ns3DsrSourceRreqEntry_methods(root_module, root_module['ns3::dsr::SourceRreqEntry'])
register_Ns3DsrDsrOptionAck_methods(root_module, root_module['ns3::dsr::DsrOptionAck'])
register_Ns3DsrDsrOptionAckHeader_methods(root_module, root_module['ns3::dsr::DsrOptionAckHeader'])
register_Ns3DsrDsrOptionAckReq_methods(root_module, root_module['ns3::dsr::DsrOptionAckReq'])
register_Ns3DsrDsrOptionAckReqHeader_methods(root_module, root_module['ns3::dsr::DsrOptionAckReqHeader'])
register_Ns3DsrDsrOptionPad1_methods(root_module, root_module['ns3::dsr::DsrOptionPad1'])
register_Ns3DsrDsrOptionPadn_methods(root_module, root_module['ns3::dsr::DsrOptionPadn'])
register_Ns3DsrDsrOptionRerr_methods(root_module, root_module['ns3::dsr::DsrOptionRerr'])
register_Ns3DsrDsrOptionRrep_methods(root_module, root_module['ns3::dsr::DsrOptionRrep'])
register_Ns3DsrDsrOptionRreq_methods(root_module, root_module['ns3::dsr::DsrOptionRreq'])
register_Ns3DsrDsrOptionSR_methods(root_module, root_module['ns3::dsr::DsrOptionSR'])
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_Ns3DsrHelper_methods(root_module, cls):
## dsr-helper.h (module 'dsr'): ns3::DsrHelper::DsrHelper() [constructor]
cls.add_constructor([])
## dsr-helper.h (module 'dsr'): ns3::DsrHelper::DsrHelper(ns3::DsrHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DsrHelper const &', 'arg0')])
## dsr-helper.h (module 'dsr'): ns3::DsrHelper * ns3::DsrHelper::Copy() const [member function]
cls.add_method('Copy',
'ns3::DsrHelper *',
[],
is_const=True)
## dsr-helper.h (module 'dsr'): ns3::Ptr<ns3::dsr::DsrRouting> ns3::DsrHelper::Create(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::dsr::DsrRouting >',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## dsr-helper.h (module 'dsr'): void ns3::DsrHelper::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_Ns3DsrMainHelper_methods(root_module, cls):
## dsr-main-helper.h (module 'dsr'): ns3::DsrMainHelper::DsrMainHelper() [constructor]
cls.add_constructor([])
## dsr-main-helper.h (module 'dsr'): ns3::DsrMainHelper::DsrMainHelper(ns3::DsrMainHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DsrMainHelper const &', 'arg0')])
## dsr-main-helper.h (module 'dsr'): void ns3::DsrMainHelper::Install(ns3::DsrHelper & dsrHelper, ns3::NodeContainer nodes) [member function]
cls.add_method('Install',
'void',
[param('ns3::DsrHelper &', 'dsrHelper'), param('ns3::NodeContainer', 'nodes')])
## dsr-main-helper.h (module 'dsr'): void ns3::DsrMainHelper::SetDsrHelper(ns3::DsrHelper & dsrHelper) [member function]
cls.add_method('SetDsrHelper',
'void',
[param('ns3::DsrHelper &', 'dsrHelper')])
## dsr-main-helper.h (module 'dsr'): void ns3::DsrMainHelper::SetRouteCache(ns3::Ptr<ns3::dsr::RouteCache> routeCache) [member function]
cls.add_method('SetRouteCache',
'void',
[param('ns3::Ptr< ns3::dsr::RouteCache >', 'routeCache')])
## dsr-main-helper.h (module 'dsr'): void ns3::DsrMainHelper::SetRreqTable(ns3::Ptr<ns3::dsr::RreqTable> rreqTable) [member function]
cls.add_method('SetRreqTable',
'void',
[param('ns3::Ptr< ns3::dsr::RreqTable >', 'rreqTable')])
return
def register_Ns3EventGarbageCollector_methods(root_module, cls):
## event-garbage-collector.h (module 'tools'): ns3::EventGarbageCollector::EventGarbageCollector(ns3::EventGarbageCollector const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EventGarbageCollector const &', 'arg0')])
## event-garbage-collector.h (module 'tools'): ns3::EventGarbageCollector::EventGarbageCollector() [constructor]
cls.add_constructor([])
## event-garbage-collector.h (module 'tools'): void ns3::EventGarbageCollector::Track(ns3::EventId event) [member function]
cls.add_method('Track',
'void',
[param('ns3::EventId', 'event')])
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_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_Ns3SystemWallClockMs_methods(root_module, cls):
## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs(ns3::SystemWallClockMs const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SystemWallClockMs const &', 'arg0')])
## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs() [constructor]
cls.add_constructor([])
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::End() [member function]
cls.add_method('End',
'int64_t',
[])
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedReal() const [member function]
cls.add_method('GetElapsedReal',
'int64_t',
[],
is_const=True)
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedSystem() const [member function]
cls.add_method('GetElapsedSystem',
'int64_t',
[],
is_const=True)
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedUser() const [member function]
cls.add_method('GetElapsedUser',
'int64_t',
[],
is_const=True)
## system-wall-clock-ms.h (module 'core'): void ns3::SystemWallClockMs::Start() [member function]
cls.add_method('Start',
'void',
[])
return
def register_Ns3Tag_methods(root_module, cls):
## tag.h (module 'network'): ns3::Tag::Tag() [constructor]
cls.add_constructor([])
## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Tag const &', 'arg0')])
## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_virtual=True)
## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3TagBuffer_methods(root_module, cls):
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')])
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor]
cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function]
cls.add_method('CopyFrom',
'void',
[param('ns3::TagBuffer', 'o')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function]
cls.add_method('ReadDouble',
'double',
[])
## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function]
cls.add_method('TrimAtEnd',
'void',
[param('uint32_t', 'trim')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function]
cls.add_method('WriteDouble',
'void',
[param('double', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'v')])
return
def register_Ns3Timer_methods(root_module, cls):
## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Timer const &', 'arg0')])
## timer.h (module 'core'): ns3::Timer::Timer() [constructor]
cls.add_constructor([])
## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer::DestroyPolicy destroyPolicy) [constructor]
cls.add_constructor([param('ns3::Timer::DestroyPolicy', 'destroyPolicy')])
## timer.h (module 'core'): void ns3::Timer::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelay() const [member function]
cls.add_method('GetDelay',
'ns3::Time',
[],
is_const=True)
## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelayLeft() const [member function]
cls.add_method('GetDelayLeft',
'ns3::Time',
[],
is_const=True)
## timer.h (module 'core'): ns3::Timer::State ns3::Timer::GetState() const [member function]
cls.add_method('GetState',
'ns3::Timer::State',
[],
is_const=True)
## timer.h (module 'core'): bool ns3::Timer::IsExpired() const [member function]
cls.add_method('IsExpired',
'bool',
[],
is_const=True)
## timer.h (module 'core'): bool ns3::Timer::IsRunning() const [member function]
cls.add_method('IsRunning',
'bool',
[],
is_const=True)
## timer.h (module 'core'): bool ns3::Timer::IsSuspended() const [member function]
cls.add_method('IsSuspended',
'bool',
[],
is_const=True)
## timer.h (module 'core'): void ns3::Timer::Remove() [member function]
cls.add_method('Remove',
'void',
[])
## timer.h (module 'core'): void ns3::Timer::Resume() [member function]
cls.add_method('Resume',
'void',
[])
## timer.h (module 'core'): void ns3::Timer::Schedule() [member function]
cls.add_method('Schedule',
'void',
[])
## timer.h (module 'core'): void ns3::Timer::Schedule(ns3::Time delay) [member function]
cls.add_method('Schedule',
'void',
[param('ns3::Time', 'delay')])
## timer.h (module 'core'): void ns3::Timer::SetDelay(ns3::Time const & delay) [member function]
cls.add_method('SetDelay',
'void',
[param('ns3::Time const &', 'delay')])
## timer.h (module 'core'): void ns3::Timer::Suspend() [member function]
cls.add_method('Suspend',
'void',
[])
return
def register_Ns3TimerImpl_methods(root_module, cls):
## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl() [constructor]
cls.add_constructor([])
## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl(ns3::TimerImpl const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimerImpl const &', 'arg0')])
## timer-impl.h (module 'core'): void ns3::TimerImpl::Invoke() [member function]
cls.add_method('Invoke',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## timer-impl.h (module 'core'): ns3::EventId ns3::TimerImpl::Schedule(ns3::Time const & delay) [member function]
cls.add_method('Schedule',
'ns3::EventId',
[param('ns3::Time const &', 'delay')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3TypeId_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor]
cls.add_constructor([param('char const *', 'name')])
## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor]
cls.add_constructor([param('ns3::TypeId const &', 'o')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('AddAttribute',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('AddAttribute',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function]
cls.add_method('AddTraceSource',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function]
cls.add_method('GetAttribute',
'ns3::TypeId::AttributeInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function]
cls.add_method('GetAttributeFullName',
'std::string',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function]
cls.add_method('GetAttributeN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function]
cls.add_method('GetConstructor',
'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function]
cls.add_method('GetGroupName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): 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_Ns3WifiMode_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## wifi-mode.h (module 'wifi'): ns3::WifiMode::WifiMode(ns3::WifiMode const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiMode const &', 'arg0')])
## wifi-mode.h (module 'wifi'): ns3::WifiMode::WifiMode() [constructor]
cls.add_constructor([])
## wifi-mode.h (module 'wifi'): ns3::WifiMode::WifiMode(std::string name) [constructor]
cls.add_constructor([param('std::string', 'name')])
## wifi-mode.h (module 'wifi'): uint32_t ns3::WifiMode::GetBandwidth() const [member function]
cls.add_method('GetBandwidth',
'uint32_t',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): ns3::WifiCodeRate ns3::WifiMode::GetCodeRate() const [member function]
cls.add_method('GetCodeRate',
'ns3::WifiCodeRate',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): uint8_t ns3::WifiMode::GetConstellationSize() const [member function]
cls.add_method('GetConstellationSize',
'uint8_t',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): uint64_t ns3::WifiMode::GetDataRate() const [member function]
cls.add_method('GetDataRate',
'uint64_t',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): ns3::WifiModulationClass ns3::WifiMode::GetModulationClass() const [member function]
cls.add_method('GetModulationClass',
'ns3::WifiModulationClass',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): uint64_t ns3::WifiMode::GetPhyRate() const [member function]
cls.add_method('GetPhyRate',
'uint64_t',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): uint32_t ns3::WifiMode::GetUid() const [member function]
cls.add_method('GetUid',
'uint32_t',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): std::string ns3::WifiMode::GetUniqueName() const [member function]
cls.add_method('GetUniqueName',
'std::string',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): bool ns3::WifiMode::IsMandatory() const [member function]
cls.add_method('IsMandatory',
'bool',
[],
is_const=True)
return
def register_Ns3WifiModeFactory_methods(root_module, cls):
## wifi-mode.h (module 'wifi'): ns3::WifiModeFactory::WifiModeFactory(ns3::WifiModeFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiModeFactory const &', 'arg0')])
## wifi-mode.h (module 'wifi'): static ns3::WifiMode ns3::WifiModeFactory::CreateWifiMode(std::string uniqueName, ns3::WifiModulationClass modClass, bool isMandatory, uint32_t bandwidth, uint32_t dataRate, ns3::WifiCodeRate codingRate, uint8_t constellationSize) [member function]
cls.add_method('CreateWifiMode',
'ns3::WifiMode',
[param('std::string', 'uniqueName'), param('ns3::WifiModulationClass', 'modClass'), param('bool', 'isMandatory'), param('uint32_t', 'bandwidth'), param('uint32_t', 'dataRate'), param('ns3::WifiCodeRate', 'codingRate'), param('uint8_t', 'constellationSize')],
is_static=True)
return
def register_Ns3WifiPhyListener_methods(root_module, cls):
## wifi-phy.h (module 'wifi'): ns3::WifiPhyListener::WifiPhyListener() [constructor]
cls.add_constructor([])
## wifi-phy.h (module 'wifi'): ns3::WifiPhyListener::WifiPhyListener(ns3::WifiPhyListener const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiPhyListener const &', 'arg0')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyMaybeCcaBusyStart(ns3::Time duration) [member function]
cls.add_method('NotifyMaybeCcaBusyStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyRxEndError() [member function]
cls.add_method('NotifyRxEndError',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyRxEndOk() [member function]
cls.add_method('NotifyRxEndOk',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyRxStart(ns3::Time duration) [member function]
cls.add_method('NotifyRxStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifySwitchingStart(ns3::Time duration) [member function]
cls.add_method('NotifySwitchingStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyTxStart(ns3::Time duration) [member function]
cls.add_method('NotifyTxStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3WifiRemoteStation_methods(root_module, cls):
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation::WifiRemoteStation() [constructor]
cls.add_constructor([])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation::WifiRemoteStation(ns3::WifiRemoteStation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiRemoteStation const &', 'arg0')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation::m_slrc [variable]
cls.add_instance_attribute('m_slrc', 'uint32_t', is_const=False)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation::m_ssrc [variable]
cls.add_instance_attribute('m_ssrc', 'uint32_t', is_const=False)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation::m_state [variable]
cls.add_instance_attribute('m_state', 'ns3::WifiRemoteStationState *', is_const=False)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation::m_tid [variable]
cls.add_instance_attribute('m_tid', 'uint8_t', is_const=False)
return
def register_Ns3WifiRemoteStationInfo_methods(root_module, cls):
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationInfo::WifiRemoteStationInfo(ns3::WifiRemoteStationInfo const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiRemoteStationInfo const &', 'arg0')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationInfo::WifiRemoteStationInfo() [constructor]
cls.add_constructor([])
## wifi-remote-station-manager.h (module 'wifi'): double ns3::WifiRemoteStationInfo::GetFrameErrorRate() const [member function]
cls.add_method('GetFrameErrorRate',
'double',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationInfo::NotifyTxFailed() [member function]
cls.add_method('NotifyTxFailed',
'void',
[])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationInfo::NotifyTxSuccess(uint32_t retryCounter) [member function]
cls.add_method('NotifyTxSuccess',
'void',
[param('uint32_t', 'retryCounter')])
return
def register_Ns3WifiRemoteStationState_methods(root_module, cls):
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState::WifiRemoteStationState() [constructor]
cls.add_constructor([])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState::WifiRemoteStationState(ns3::WifiRemoteStationState const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiRemoteStationState const &', 'arg0')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState::m_address [variable]
cls.add_instance_attribute('m_address', 'ns3::Mac48Address', is_const=False)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState::m_info [variable]
cls.add_instance_attribute('m_info', 'ns3::WifiRemoteStationInfo', is_const=False)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState::m_operationalRateSet [variable]
cls.add_instance_attribute('m_operationalRateSet', 'ns3::WifiModeList', 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_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_Ns3Icmpv4DestinationUnreachable_methods(root_module, cls):
## icmpv4.h (module 'internet'): ns3::Icmpv4DestinationUnreachable::Icmpv4DestinationUnreachable(ns3::Icmpv4DestinationUnreachable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Icmpv4DestinationUnreachable const &', 'arg0')])
## icmpv4.h (module 'internet'): ns3::Icmpv4DestinationUnreachable::Icmpv4DestinationUnreachable() [constructor]
cls.add_constructor([])
## icmpv4.h (module 'internet'): void ns3::Icmpv4DestinationUnreachable::GetData(uint8_t * payload) const [member function]
cls.add_method('GetData',
'void',
[param('uint8_t *', 'payload')],
is_const=True)
## icmpv4.h (module 'internet'): ns3::Ipv4Header ns3::Icmpv4DestinationUnreachable::GetHeader() const [member function]
cls.add_method('GetHeader',
'ns3::Ipv4Header',
[],
is_const=True)
## icmpv4.h (module 'internet'): uint16_t ns3::Icmpv4DestinationUnreachable::GetNextHopMtu() const [member function]
cls.add_method('GetNextHopMtu',
'uint16_t',
[],
is_const=True)
## icmpv4.h (module 'internet'): static ns3::TypeId ns3::Icmpv4DestinationUnreachable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## icmpv4.h (module 'internet'): void ns3::Icmpv4DestinationUnreachable::SetData(ns3::Ptr<ns3::Packet const> data) [member function]
cls.add_method('SetData',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'data')])
## icmpv4.h (module 'internet'): void ns3::Icmpv4DestinationUnreachable::SetHeader(ns3::Ipv4Header header) [member function]
cls.add_method('SetHeader',
'void',
[param('ns3::Ipv4Header', 'header')])
## icmpv4.h (module 'internet'): void ns3::Icmpv4DestinationUnreachable::SetNextHopMtu(uint16_t mtu) [member function]
cls.add_method('SetNextHopMtu',
'void',
[param('uint16_t', 'mtu')])
## icmpv4.h (module 'internet'): uint32_t ns3::Icmpv4DestinationUnreachable::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
visibility='private', is_virtual=True)
## icmpv4.h (module 'internet'): ns3::TypeId ns3::Icmpv4DestinationUnreachable::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, visibility='private', is_virtual=True)
## icmpv4.h (module 'internet'): uint32_t ns3::Icmpv4DestinationUnreachable::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, visibility='private', is_virtual=True)
## icmpv4.h (module 'internet'): void ns3::Icmpv4DestinationUnreachable::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, visibility='private', is_virtual=True)
## icmpv4.h (module 'internet'): void ns3::Icmpv4DestinationUnreachable::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3Icmpv4Echo_methods(root_module, cls):
## icmpv4.h (module 'internet'): ns3::Icmpv4Echo::Icmpv4Echo(ns3::Icmpv4Echo const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Icmpv4Echo const &', 'arg0')])
## icmpv4.h (module 'internet'): ns3::Icmpv4Echo::Icmpv4Echo() [constructor]
cls.add_constructor([])
## icmpv4.h (module 'internet'): uint32_t ns3::Icmpv4Echo::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## icmpv4.h (module 'internet'): uint32_t ns3::Icmpv4Echo::GetData(uint8_t * payload) const [member function]
cls.add_method('GetData',
'uint32_t',
[param('uint8_t *', 'payload')],
is_const=True)
## icmpv4.h (module 'internet'): uint32_t ns3::Icmpv4Echo::GetDataSize() const [member function]
cls.add_method('GetDataSize',
'uint32_t',
[],
is_const=True)
## icmpv4.h (module 'internet'): uint16_t ns3::Icmpv4Echo::GetIdentifier() const [member function]
cls.add_method('GetIdentifier',
'uint16_t',
[],
is_const=True)
## icmpv4.h (module 'internet'): ns3::TypeId ns3::Icmpv4Echo::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## icmpv4.h (module 'internet'): uint16_t ns3::Icmpv4Echo::GetSequenceNumber() const [member function]
cls.add_method('GetSequenceNumber',
'uint16_t',
[],
is_const=True)
## icmpv4.h (module 'internet'): uint32_t ns3::Icmpv4Echo::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## icmpv4.h (module 'internet'): static ns3::TypeId ns3::Icmpv4Echo::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## icmpv4.h (module 'internet'): void ns3::Icmpv4Echo::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## icmpv4.h (module 'internet'): void ns3::Icmpv4Echo::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## icmpv4.h (module 'internet'): void ns3::Icmpv4Echo::SetData(ns3::Ptr<ns3::Packet const> data) [member function]
cls.add_method('SetData',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'data')])
## icmpv4.h (module 'internet'): void ns3::Icmpv4Echo::SetIdentifier(uint16_t id) [member function]
cls.add_method('SetIdentifier',
'void',
[param('uint16_t', 'id')])
## icmpv4.h (module 'internet'): void ns3::Icmpv4Echo::SetSequenceNumber(uint16_t seq) [member function]
cls.add_method('SetSequenceNumber',
'void',
[param('uint16_t', 'seq')])
return
def register_Ns3Icmpv4Header_methods(root_module, cls):
## icmpv4.h (module 'internet'): ns3::Icmpv4Header::Icmpv4Header(ns3::Icmpv4Header const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Icmpv4Header const &', 'arg0')])
## icmpv4.h (module 'internet'): ns3::Icmpv4Header::Icmpv4Header() [constructor]
cls.add_constructor([])
## icmpv4.h (module 'internet'): uint32_t ns3::Icmpv4Header::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## icmpv4.h (module 'internet'): void ns3::Icmpv4Header::EnableChecksum() [member function]
cls.add_method('EnableChecksum',
'void',
[])
## icmpv4.h (module 'internet'): uint8_t ns3::Icmpv4Header::GetCode() const [member function]
cls.add_method('GetCode',
'uint8_t',
[],
is_const=True)
## icmpv4.h (module 'internet'): ns3::TypeId ns3::Icmpv4Header::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## icmpv4.h (module 'internet'): uint32_t ns3::Icmpv4Header::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## icmpv4.h (module 'internet'): uint8_t ns3::Icmpv4Header::GetType() const [member function]
cls.add_method('GetType',
'uint8_t',
[],
is_const=True)
## icmpv4.h (module 'internet'): static ns3::TypeId ns3::Icmpv4Header::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## icmpv4.h (module 'internet'): void ns3::Icmpv4Header::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## icmpv4.h (module 'internet'): void ns3::Icmpv4Header::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## icmpv4.h (module 'internet'): void ns3::Icmpv4Header::SetCode(uint8_t code) [member function]
cls.add_method('SetCode',
'void',
[param('uint8_t', 'code')])
## icmpv4.h (module 'internet'): void ns3::Icmpv4Header::SetType(uint8_t type) [member function]
cls.add_method('SetType',
'void',
[param('uint8_t', 'type')])
return
def register_Ns3Icmpv4TimeExceeded_methods(root_module, cls):
## icmpv4.h (module 'internet'): ns3::Icmpv4TimeExceeded::Icmpv4TimeExceeded(ns3::Icmpv4TimeExceeded const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Icmpv4TimeExceeded const &', 'arg0')])
## icmpv4.h (module 'internet'): ns3::Icmpv4TimeExceeded::Icmpv4TimeExceeded() [constructor]
cls.add_constructor([])
## icmpv4.h (module 'internet'): uint32_t ns3::Icmpv4TimeExceeded::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## icmpv4.h (module 'internet'): void ns3::Icmpv4TimeExceeded::GetData(uint8_t * payload) const [member function]
cls.add_method('GetData',
'void',
[param('uint8_t *', 'payload')],
is_const=True)
## icmpv4.h (module 'internet'): ns3::Ipv4Header ns3::Icmpv4TimeExceeded::GetHeader() const [member function]
cls.add_method('GetHeader',
'ns3::Ipv4Header',
[],
is_const=True)
## icmpv4.h (module 'internet'): ns3::TypeId ns3::Icmpv4TimeExceeded::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## icmpv4.h (module 'internet'): uint32_t ns3::Icmpv4TimeExceeded::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## icmpv4.h (module 'internet'): static ns3::TypeId ns3::Icmpv4TimeExceeded::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## icmpv4.h (module 'internet'): void ns3::Icmpv4TimeExceeded::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## icmpv4.h (module 'internet'): void ns3::Icmpv4TimeExceeded::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## icmpv4.h (module 'internet'): void ns3::Icmpv4TimeExceeded::SetData(ns3::Ptr<ns3::Packet const> data) [member function]
cls.add_method('SetData',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'data')])
## icmpv4.h (module 'internet'): void ns3::Icmpv4TimeExceeded::SetHeader(ns3::Ipv4Header header) [member function]
cls.add_method('SetHeader',
'void',
[param('ns3::Ipv4Header', 'header')])
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_Ns3SimpleRefCount__Ns3WifiInformationElement_Ns3Empty_Ns3DefaultDeleter__lt__ns3WifiInformationElement__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> >::SimpleRefCount(ns3::SimpleRefCount<ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter< ns3::WifiInformationElement > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> >::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_Ns3WifiInformationElement_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('==')
## wifi-information-element.h (module 'wifi'): ns3::WifiInformationElement::WifiInformationElement() [constructor]
cls.add_constructor([])
## wifi-information-element.h (module 'wifi'): ns3::WifiInformationElement::WifiInformationElement(ns3::WifiInformationElement const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiInformationElement const &', 'arg0')])
## wifi-information-element.h (module 'wifi'): ns3::Buffer::Iterator ns3::WifiInformationElement::Deserialize(ns3::Buffer::Iterator i) [member function]
cls.add_method('Deserialize',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'i')])
## wifi-information-element.h (module 'wifi'): ns3::Buffer::Iterator ns3::WifiInformationElement::DeserializeIfPresent(ns3::Buffer::Iterator i) [member function]
cls.add_method('DeserializeIfPresent',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'i')])
## wifi-information-element.h (module 'wifi'): uint8_t ns3::WifiInformationElement::DeserializeInformationField(ns3::Buffer::Iterator start, uint8_t length) [member function]
cls.add_method('DeserializeInformationField',
'uint8_t',
[param('ns3::Buffer::Iterator', 'start'), param('uint8_t', 'length')],
is_pure_virtual=True, is_virtual=True)
## wifi-information-element.h (module 'wifi'): ns3::WifiInformationElementId ns3::WifiInformationElement::ElementId() const [member function]
cls.add_method('ElementId',
'ns3::WifiInformationElementId',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-information-element.h (module 'wifi'): uint8_t ns3::WifiInformationElement::GetInformationFieldSize() const [member function]
cls.add_method('GetInformationFieldSize',
'uint8_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-information-element.h (module 'wifi'): uint16_t ns3::WifiInformationElement::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint16_t',
[],
is_const=True)
## wifi-information-element.h (module 'wifi'): void ns3::WifiInformationElement::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## wifi-information-element.h (module 'wifi'): ns3::Buffer::Iterator ns3::WifiInformationElement::Serialize(ns3::Buffer::Iterator i) const [member function]
cls.add_method('Serialize',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'i')],
is_const=True)
## wifi-information-element.h (module 'wifi'): void ns3::WifiInformationElement::SerializeInformationField(ns3::Buffer::Iterator start) const [member function]
cls.add_method('SerializeInformationField',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3WifiMac_methods(root_module, cls):
## wifi-mac.h (module 'wifi'): ns3::WifiMac::WifiMac() [constructor]
cls.add_constructor([])
## wifi-mac.h (module 'wifi'): ns3::WifiMac::WifiMac(ns3::WifiMac const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiMac const &', 'arg0')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::ConfigureStandard(ns3::WifiPhyStandard standard) [member function]
cls.add_method('ConfigureStandard',
'void',
[param('ns3::WifiPhyStandard', 'standard')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to, ns3::Mac48Address from) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetAckTimeout() const [member function]
cls.add_method('GetAckTimeout',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Mac48Address ns3::WifiMac::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Mac48Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetBasicBlockAckTimeout() const [member function]
cls.add_method('GetBasicBlockAckTimeout',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Mac48Address ns3::WifiMac::GetBssid() const [member function]
cls.add_method('GetBssid',
'ns3::Mac48Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetCompressedBlockAckTimeout() const [member function]
cls.add_method('GetCompressedBlockAckTimeout',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetCtsTimeout() const [member function]
cls.add_method('GetCtsTimeout',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetEifsNoDifs() const [member function]
cls.add_method('GetEifsNoDifs',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetMaxPropagationDelay() const [member function]
cls.add_method('GetMaxPropagationDelay',
'ns3::Time',
[],
is_const=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetMsduLifetime() const [member function]
cls.add_method('GetMsduLifetime',
'ns3::Time',
[],
is_const=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetPifs() const [member function]
cls.add_method('GetPifs',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetSifs() const [member function]
cls.add_method('GetSifs',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetSlot() const [member function]
cls.add_method('GetSlot',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Ssid ns3::WifiMac::GetSsid() const [member function]
cls.add_method('GetSsid',
'ns3::Ssid',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): static ns3::TypeId ns3::WifiMac::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::NotifyPromiscRx(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyPromiscRx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::NotifyRx(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyRx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::NotifyRxDrop(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyRxDrop',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::NotifyTx(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyTx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::NotifyTxDrop(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyTxDrop',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetAckTimeout(ns3::Time ackTimeout) [member function]
cls.add_method('SetAckTimeout',
'void',
[param('ns3::Time', 'ackTimeout')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetAddress(ns3::Mac48Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Mac48Address', 'address')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetBasicBlockAckTimeout(ns3::Time blockAckTimeout) [member function]
cls.add_method('SetBasicBlockAckTimeout',
'void',
[param('ns3::Time', 'blockAckTimeout')],
is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetCompressedBlockAckTimeout(ns3::Time blockAckTimeout) [member function]
cls.add_method('SetCompressedBlockAckTimeout',
'void',
[param('ns3::Time', 'blockAckTimeout')],
is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetCtsTimeout(ns3::Time ctsTimeout) [member function]
cls.add_method('SetCtsTimeout',
'void',
[param('ns3::Time', 'ctsTimeout')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetEifsNoDifs(ns3::Time eifsNoDifs) [member function]
cls.add_method('SetEifsNoDifs',
'void',
[param('ns3::Time', 'eifsNoDifs')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetForwardUpCallback(ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Mac48Address,ns3::Mac48Address,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> upCallback) [member function]
cls.add_method('SetForwardUpCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'upCallback')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetLinkDownCallback(ns3::Callback<void,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> linkDown) [member function]
cls.add_method('SetLinkDownCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkDown')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetLinkUpCallback(ns3::Callback<void,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> linkUp) [member function]
cls.add_method('SetLinkUpCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkUp')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetMaxPropagationDelay(ns3::Time delay) [member function]
cls.add_method('SetMaxPropagationDelay',
'void',
[param('ns3::Time', 'delay')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetPifs(ns3::Time pifs) [member function]
cls.add_method('SetPifs',
'void',
[param('ns3::Time', 'pifs')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetPromisc() [member function]
cls.add_method('SetPromisc',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetSifs(ns3::Time sifs) [member function]
cls.add_method('SetSifs',
'void',
[param('ns3::Time', 'sifs')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetSlot(ns3::Time slotTime) [member function]
cls.add_method('SetSlot',
'void',
[param('ns3::Time', 'slotTime')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetSsid(ns3::Ssid ssid) [member function]
cls.add_method('SetSsid',
'void',
[param('ns3::Ssid', 'ssid')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetWifiPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function]
cls.add_method('SetWifiPhy',
'void',
[param('ns3::Ptr< ns3::WifiPhy >', 'phy')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> stationManager) [member function]
cls.add_method('SetWifiRemoteStationManager',
'void',
[param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'stationManager')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): bool ns3::WifiMac::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::ConfigureCCHDcf(ns3::Ptr<ns3::Dcf> dcf, uint32_t cwmin, uint32_t cwmax, ns3::AcIndex ac) [member function]
cls.add_method('ConfigureCCHDcf',
'void',
[param('ns3::Ptr< ns3::Dcf >', 'dcf'), param('uint32_t', 'cwmin'), param('uint32_t', 'cwmax'), param('ns3::AcIndex', 'ac')],
visibility='protected')
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::ConfigureDcf(ns3::Ptr<ns3::Dcf> dcf, uint32_t cwmin, uint32_t cwmax, ns3::AcIndex ac) [member function]
cls.add_method('ConfigureDcf',
'void',
[param('ns3::Ptr< ns3::Dcf >', 'dcf'), param('uint32_t', 'cwmin'), param('uint32_t', 'cwmax'), param('ns3::AcIndex', 'ac')],
visibility='protected')
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::FinishConfigureStandard(ns3::WifiPhyStandard standard) [member function]
cls.add_method('FinishConfigureStandard',
'void',
[param('ns3::WifiPhyStandard', 'standard')],
is_pure_virtual=True, visibility='private', 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_Ns3WifiPhy_methods(root_module, cls):
## wifi-phy.h (module 'wifi'): ns3::WifiPhy::WifiPhy(ns3::WifiPhy const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiPhy const &', 'arg0')])
## wifi-phy.h (module 'wifi'): ns3::WifiPhy::WifiPhy() [constructor]
cls.add_constructor([])
## wifi-phy.h (module 'wifi'): int64_t ns3::WifiPhy::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): double ns3::WifiPhy::CalculateSnr(ns3::WifiMode txMode, double ber) const [member function]
cls.add_method('CalculateSnr',
'double',
[param('ns3::WifiMode', 'txMode'), param('double', 'ber')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): static ns3::Time ns3::WifiPhy::CalculateTxDuration(uint32_t size, ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function]
cls.add_method('CalculateTxDuration',
'ns3::Time',
[param('uint32_t', 'size'), param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')],
is_static=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::ConfigureStandard(ns3::WifiPhyStandard standard) [member function]
cls.add_method('ConfigureStandard',
'void',
[param('ns3::WifiPhyStandard', 'standard')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): ns3::Ptr<ns3::WifiChannel> ns3::WifiPhy::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::WifiChannel >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): uint16_t ns3::WifiPhy::GetChannelNumber() const [member function]
cls.add_method('GetChannelNumber',
'uint16_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): ns3::Time ns3::WifiPhy::GetDelayUntilIdle() [member function]
cls.add_method('GetDelayUntilIdle',
'ns3::Time',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetDsssRate11Mbps() [member function]
cls.add_method('GetDsssRate11Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetDsssRate1Mbps() [member function]
cls.add_method('GetDsssRate1Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetDsssRate2Mbps() [member function]
cls.add_method('GetDsssRate2Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetDsssRate5_5Mbps() [member function]
cls.add_method('GetDsssRate5_5Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate12Mbps() [member function]
cls.add_method('GetErpOfdmRate12Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate18Mbps() [member function]
cls.add_method('GetErpOfdmRate18Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate24Mbps() [member function]
cls.add_method('GetErpOfdmRate24Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate36Mbps() [member function]
cls.add_method('GetErpOfdmRate36Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate48Mbps() [member function]
cls.add_method('GetErpOfdmRate48Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate54Mbps() [member function]
cls.add_method('GetErpOfdmRate54Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate6Mbps() [member function]
cls.add_method('GetErpOfdmRate6Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate9Mbps() [member function]
cls.add_method('GetErpOfdmRate9Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): ns3::Time ns3::WifiPhy::GetLastRxStartTime() const [member function]
cls.add_method('GetLastRxStartTime',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): ns3::WifiMode ns3::WifiPhy::GetMode(uint32_t mode) const [member function]
cls.add_method('GetMode',
'ns3::WifiMode',
[param('uint32_t', 'mode')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): uint32_t ns3::WifiPhy::GetNModes() const [member function]
cls.add_method('GetNModes',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): uint32_t ns3::WifiPhy::GetNTxPower() const [member function]
cls.add_method('GetNTxPower',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate12Mbps() [member function]
cls.add_method('GetOfdmRate12Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate12MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate12MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate12MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate12MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate13_5MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate13_5MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate18Mbps() [member function]
cls.add_method('GetOfdmRate18Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate18MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate18MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate1_5MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate1_5MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate24Mbps() [member function]
cls.add_method('GetOfdmRate24Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate24MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate24MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate27MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate27MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate2_25MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate2_25MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate36Mbps() [member function]
cls.add_method('GetOfdmRate36Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate3MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate3MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate3MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate3MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate48Mbps() [member function]
cls.add_method('GetOfdmRate48Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate4_5MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate4_5MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate4_5MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate4_5MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate54Mbps() [member function]
cls.add_method('GetOfdmRate54Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate6Mbps() [member function]
cls.add_method('GetOfdmRate6Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate6MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate6MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate6MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate6MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate9Mbps() [member function]
cls.add_method('GetOfdmRate9Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate9MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate9MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate9MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate9MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static uint32_t ns3::WifiPhy::GetPayloadDurationMicroSeconds(uint32_t size, ns3::WifiMode payloadMode) [member function]
cls.add_method('GetPayloadDurationMicroSeconds',
'uint32_t',
[param('uint32_t', 'size'), param('ns3::WifiMode', 'payloadMode')],
is_static=True)
## wifi-phy.h (module 'wifi'): static uint32_t ns3::WifiPhy::GetPlcpHeaderDurationMicroSeconds(ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function]
cls.add_method('GetPlcpHeaderDurationMicroSeconds',
'uint32_t',
[param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetPlcpHeaderMode(ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function]
cls.add_method('GetPlcpHeaderMode',
'ns3::WifiMode',
[param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')],
is_static=True)
## wifi-phy.h (module 'wifi'): static uint32_t ns3::WifiPhy::GetPlcpPreambleDurationMicroSeconds(ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function]
cls.add_method('GetPlcpPreambleDurationMicroSeconds',
'uint32_t',
[param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')],
is_static=True)
## wifi-phy.h (module 'wifi'): ns3::Time ns3::WifiPhy::GetStateDuration() [member function]
cls.add_method('GetStateDuration',
'ns3::Time',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): double ns3::WifiPhy::GetTxPowerEnd() const [member function]
cls.add_method('GetTxPowerEnd',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): double ns3::WifiPhy::GetTxPowerStart() const [member function]
cls.add_method('GetTxPowerStart',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): static ns3::TypeId ns3::WifiPhy::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateBusy() [member function]
cls.add_method('IsStateBusy',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateCcaBusy() [member function]
cls.add_method('IsStateCcaBusy',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateIdle() [member function]
cls.add_method('IsStateIdle',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateRx() [member function]
cls.add_method('IsStateRx',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateSwitching() [member function]
cls.add_method('IsStateSwitching',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateTx() [member function]
cls.add_method('IsStateTx',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyMonitorSniffRx(ns3::Ptr<ns3::Packet const> packet, uint16_t channelFreqMhz, uint16_t channelNumber, uint32_t rate, bool isShortPreamble, double signalDbm, double noiseDbm) [member function]
cls.add_method('NotifyMonitorSniffRx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'channelFreqMhz'), param('uint16_t', 'channelNumber'), param('uint32_t', 'rate'), param('bool', 'isShortPreamble'), param('double', 'signalDbm'), param('double', 'noiseDbm')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyMonitorSniffTx(ns3::Ptr<ns3::Packet const> packet, uint16_t channelFreqMhz, uint16_t channelNumber, uint32_t rate, bool isShortPreamble) [member function]
cls.add_method('NotifyMonitorSniffTx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'channelFreqMhz'), param('uint16_t', 'channelNumber'), param('uint32_t', 'rate'), param('bool', 'isShortPreamble')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyRxBegin(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyRxBegin',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyRxDrop(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyRxDrop',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyRxEnd(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyRxEnd',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyTxBegin(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyTxBegin',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyTxDrop(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyTxDrop',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyTxEnd(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyTxEnd',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::RegisterListener(ns3::WifiPhyListener * listener) [member function]
cls.add_method('RegisterListener',
'void',
[param('ns3::WifiPhyListener *', 'listener')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SendPacket(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMode mode, ns3::WifiPreamble preamble, uint8_t txPowerLevel) [member function]
cls.add_method('SendPacket',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMode', 'mode'), param('ns3::WifiPreamble', 'preamble'), param('uint8_t', 'txPowerLevel')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetChannelNumber(uint16_t id) [member function]
cls.add_method('SetChannelNumber',
'void',
[param('uint16_t', 'id')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetReceiveErrorCallback(ns3::Callback<void,ns3::Ptr<const ns3::Packet>,double,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function]
cls.add_method('SetReceiveErrorCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetReceiveOkCallback(ns3::Callback<void,ns3::Ptr<ns3::Packet>,double,ns3::WifiMode,ns3::WifiPreamble,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function]
cls.add_method('SetReceiveOkCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::WifiMode, ns3::WifiPreamble, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3WifiRemoteStationManager_methods(root_module, cls):
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationManager::WifiRemoteStationManager(ns3::WifiRemoteStationManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiRemoteStationManager const &', 'arg0')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationManager::WifiRemoteStationManager() [constructor]
cls.add_constructor([])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::AddBasicMode(ns3::WifiMode mode) [member function]
cls.add_method('AddBasicMode',
'void',
[param('ns3::WifiMode', 'mode')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::AddSupportedMode(ns3::Mac48Address address, ns3::WifiMode mode) [member function]
cls.add_method('AddSupportedMode',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMode', 'mode')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetAckMode(ns3::Mac48Address address, ns3::WifiMode dataMode) [member function]
cls.add_method('GetAckMode',
'ns3::WifiMode',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMode', 'dataMode')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetBasicMode(uint32_t i) const [member function]
cls.add_method('GetBasicMode',
'ns3::WifiMode',
[param('uint32_t', 'i')],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetCtsMode(ns3::Mac48Address address, ns3::WifiMode rtsMode) [member function]
cls.add_method('GetCtsMode',
'ns3::WifiMode',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMode', 'rtsMode')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetDataMode(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fullPacketSize) [member function]
cls.add_method('GetDataMode',
'ns3::WifiMode',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fullPacketSize')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetDefaultMode() const [member function]
cls.add_method('GetDefaultMode',
'ns3::WifiMode',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetFragmentOffset(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fragmentNumber) [member function]
cls.add_method('GetFragmentOffset',
'uint32_t',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fragmentNumber')])
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetFragmentSize(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fragmentNumber) [member function]
cls.add_method('GetFragmentSize',
'uint32_t',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fragmentNumber')])
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetFragmentationThreshold() const [member function]
cls.add_method('GetFragmentationThreshold',
'uint32_t',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationInfo ns3::WifiRemoteStationManager::GetInfo(ns3::Mac48Address address) [member function]
cls.add_method('GetInfo',
'ns3::WifiRemoteStationInfo',
[param('ns3::Mac48Address', 'address')])
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetMaxSlrc() const [member function]
cls.add_method('GetMaxSlrc',
'uint32_t',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetMaxSsrc() const [member function]
cls.add_method('GetMaxSsrc',
'uint32_t',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetNBasicModes() const [member function]
cls.add_method('GetNBasicModes',
'uint32_t',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetNonUnicastMode() const [member function]
cls.add_method('GetNonUnicastMode',
'ns3::WifiMode',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetRtsCtsThreshold() const [member function]
cls.add_method('GetRtsCtsThreshold',
'uint32_t',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetRtsMode(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('GetRtsMode',
'ns3::WifiMode',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-remote-station-manager.h (module 'wifi'): static ns3::TypeId ns3::WifiRemoteStationManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::IsAssociated(ns3::Mac48Address address) const [member function]
cls.add_method('IsAssociated',
'bool',
[param('ns3::Mac48Address', 'address')],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::IsBrandNew(ns3::Mac48Address address) const [member function]
cls.add_method('IsBrandNew',
'bool',
[param('ns3::Mac48Address', 'address')],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::IsLastFragment(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fragmentNumber) [member function]
cls.add_method('IsLastFragment',
'bool',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fragmentNumber')])
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::IsWaitAssocTxOk(ns3::Mac48Address address) const [member function]
cls.add_method('IsWaitAssocTxOk',
'bool',
[param('ns3::Mac48Address', 'address')],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::NeedDataRetransmission(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NeedDataRetransmission',
'bool',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::NeedFragmentation(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NeedFragmentation',
'bool',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::NeedRts(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NeedRts',
'bool',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::NeedRtsRetransmission(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NeedRtsRetransmission',
'bool',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::PrepareForQueue(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fullPacketSize) [member function]
cls.add_method('PrepareForQueue',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fullPacketSize')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::RecordDisassociated(ns3::Mac48Address address) [member function]
cls.add_method('RecordDisassociated',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::RecordGotAssocTxFailed(ns3::Mac48Address address) [member function]
cls.add_method('RecordGotAssocTxFailed',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::RecordGotAssocTxOk(ns3::Mac48Address address) [member function]
cls.add_method('RecordGotAssocTxOk',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::RecordWaitAssocTxOk(ns3::Mac48Address address) [member function]
cls.add_method('RecordWaitAssocTxOk',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportDataFailed(ns3::Mac48Address address, ns3::WifiMacHeader const * header) [member function]
cls.add_method('ReportDataFailed',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportDataOk(ns3::Mac48Address address, ns3::WifiMacHeader const * header, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('ReportDataOk',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportFinalDataFailed(ns3::Mac48Address address, ns3::WifiMacHeader const * header) [member function]
cls.add_method('ReportFinalDataFailed',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportFinalRtsFailed(ns3::Mac48Address address, ns3::WifiMacHeader const * header) [member function]
cls.add_method('ReportFinalRtsFailed',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportRtsFailed(ns3::Mac48Address address, ns3::WifiMacHeader const * header) [member function]
cls.add_method('ReportRtsFailed',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportRtsOk(ns3::Mac48Address address, ns3::WifiMacHeader const * header, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('ReportRtsOk',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportRxOk(ns3::Mac48Address address, ns3::WifiMacHeader const * header, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('ReportRxOk',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::Reset() [member function]
cls.add_method('Reset',
'void',
[])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::Reset(ns3::Mac48Address address) [member function]
cls.add_method('Reset',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::SetFragmentationThreshold(uint32_t threshold) [member function]
cls.add_method('SetFragmentationThreshold',
'void',
[param('uint32_t', 'threshold')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::SetMaxSlrc(uint32_t maxSlrc) [member function]
cls.add_method('SetMaxSlrc',
'void',
[param('uint32_t', 'maxSlrc')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::SetMaxSsrc(uint32_t maxSsrc) [member function]
cls.add_method('SetMaxSsrc',
'void',
[param('uint32_t', 'maxSsrc')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::SetRtsCtsThreshold(uint32_t threshold) [member function]
cls.add_method('SetRtsCtsThreshold',
'void',
[param('uint32_t', 'threshold')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::SetupPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function]
cls.add_method('SetupPhy',
'void',
[param('ns3::Ptr< ns3::WifiPhy >', 'phy')],
is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetNSupported(ns3::WifiRemoteStation const * station) const [member function]
cls.add_method('GetNSupported',
'uint32_t',
[param('ns3::WifiRemoteStation const *', 'station')],
is_const=True, visibility='protected')
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetSupported(ns3::WifiRemoteStation const * station, uint32_t i) const [member function]
cls.add_method('GetSupported',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation const *', 'station'), param('uint32_t', 'i')],
is_const=True, visibility='protected')
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::WifiRemoteStationManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::DoNeedDataRetransmission(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function]
cls.add_method('DoNeedDataRetransmission',
'bool',
[param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')],
visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::DoNeedFragmentation(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function]
cls.add_method('DoNeedFragmentation',
'bool',
[param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')],
visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::DoNeedRts(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function]
cls.add_method('DoNeedRts',
'bool',
[param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')],
visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::DoNeedRtsRetransmission(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function]
cls.add_method('DoNeedRtsRetransmission',
'bool',
[param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')],
visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3ZetaRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZetaRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable::ZetaRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue(double alpha) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'alpha')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger(uint32_t alpha) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'alpha')])
## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ZipfRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZipfRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable::ZipfRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue(uint32_t n, double alpha) [member function]
cls.add_method('GetValue',
'double',
[param('uint32_t', 'n'), param('double', 'alpha')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger(uint32_t n, uint32_t alpha) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'n'), param('uint32_t', 'alpha')])
## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_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<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ucb, ns3::Callback<void,ns3::Ptr<ns3::Ipv4MulticastRoute>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> mcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,unsigned int,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> lcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::Socket::SocketErrno,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ecb) [member function]
cls.add_method('RouteInput',
'bool',
[param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function]
cls.add_method('RouteOutput',
'ns3::Ptr< ns3::Ipv4Route >',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function]
cls.add_method('SetIpv4',
'void',
[param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3Ipv6AddressChecker_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')])
return
def register_Ns3Ipv6AddressValue_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor]
cls.add_constructor([param('ns3::Ipv6Address const &', 'value')])
## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv6Address',
[],
is_const=True)
## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv6Address const &', 'value')])
return
def register_Ns3Ipv6Interface_methods(root_module, cls):
## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface::Ipv6Interface(ns3::Ipv6Interface const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Interface const &', 'arg0')])
## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface::Ipv6Interface() [constructor]
cls.add_constructor([])
## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::AddAddress(ns3::Ipv6InterfaceAddress iface) [member function]
cls.add_method('AddAddress',
'bool',
[param('ns3::Ipv6InterfaceAddress', 'iface')])
## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetAddress(uint32_t index) const [member function]
cls.add_method('GetAddress',
'ns3::Ipv6InterfaceAddress',
[param('uint32_t', 'index')],
is_const=True)
## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetAddressMatchingDestination(ns3::Ipv6Address dst) [member function]
cls.add_method('GetAddressMatchingDestination',
'ns3::Ipv6InterfaceAddress',
[param('ns3::Ipv6Address', 'dst')])
## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetBaseReachableTime() const [member function]
cls.add_method('GetBaseReachableTime',
'uint16_t',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): uint8_t ns3::Ipv6Interface::GetCurHopLimit() const [member function]
cls.add_method('GetCurHopLimit',
'uint8_t',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv6Interface::GetDevice() const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[],
is_const=True, is_virtual=True)
## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetLinkLocalAddress() const [member function]
cls.add_method('GetLinkLocalAddress',
'ns3::Ipv6InterfaceAddress',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetMetric() const [member function]
cls.add_method('GetMetric',
'uint16_t',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): uint32_t ns3::Ipv6Interface::GetNAddresses() const [member function]
cls.add_method('GetNAddresses',
'uint32_t',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetReachableTime() const [member function]
cls.add_method('GetReachableTime',
'uint16_t',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetRetransTimer() const [member function]
cls.add_method('GetRetransTimer',
'uint16_t',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): static ns3::TypeId ns3::Ipv6Interface::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsDown() const [member function]
cls.add_method('IsDown',
'bool',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsForwarding() const [member function]
cls.add_method('IsForwarding',
'bool',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsUp() const [member function]
cls.add_method('IsUp',
'bool',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::RemoveAddress(uint32_t index) [member function]
cls.add_method('RemoveAddress',
'ns3::Ipv6InterfaceAddress',
[param('uint32_t', 'index')])
## ipv6-interface.h (module 'internet'): 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=ns3::NormalRandomVariable::INFINITE_VALUE) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'variance'), param('double', 'bound', default_value='ns3::NormalRandomVariable::INFINITE_VALUE')])
## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger(uint32_t mean, uint32_t variance, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'variance'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ObjectFactoryChecker_methods(root_module, cls):
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [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_Ns3Ssid_methods(root_module, cls):
cls.add_output_stream_operator()
## ssid.h (module 'wifi'): ns3::Ssid::Ssid(ns3::Ssid const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ssid const &', 'arg0')])
## ssid.h (module 'wifi'): ns3::Ssid::Ssid() [constructor]
cls.add_constructor([])
## ssid.h (module 'wifi'): ns3::Ssid::Ssid(std::string s) [constructor]
cls.add_constructor([param('std::string', 's')])
## ssid.h (module 'wifi'): ns3::Ssid::Ssid(char const * ssid, uint8_t length) [constructor]
cls.add_constructor([param('char const *', 'ssid'), param('uint8_t', 'length')])
## ssid.h (module 'wifi'): uint8_t ns3::Ssid::DeserializeInformationField(ns3::Buffer::Iterator start, uint8_t length) [member function]
cls.add_method('DeserializeInformationField',
'uint8_t',
[param('ns3::Buffer::Iterator', 'start'), param('uint8_t', 'length')],
is_virtual=True)
## ssid.h (module 'wifi'): ns3::WifiInformationElementId ns3::Ssid::ElementId() const [member function]
cls.add_method('ElementId',
'ns3::WifiInformationElementId',
[],
is_const=True, is_virtual=True)
## ssid.h (module 'wifi'): uint8_t ns3::Ssid::GetInformationFieldSize() const [member function]
cls.add_method('GetInformationFieldSize',
'uint8_t',
[],
is_const=True, is_virtual=True)
## ssid.h (module 'wifi'): bool ns3::Ssid::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True)
## ssid.h (module 'wifi'): bool ns3::Ssid::IsEqual(ns3::Ssid const & o) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ssid const &', 'o')],
is_const=True)
## ssid.h (module 'wifi'): char * ns3::Ssid::PeekString() const [member function]
cls.add_method('PeekString',
'char *',
[],
is_const=True)
## ssid.h (module 'wifi'): void ns3::Ssid::SerializeInformationField(ns3::Buffer::Iterator start) const [member function]
cls.add_method('SerializeInformationField',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
return
def register_Ns3SsidChecker_methods(root_module, cls):
## ssid.h (module 'wifi'): ns3::SsidChecker::SsidChecker() [constructor]
cls.add_constructor([])
## ssid.h (module 'wifi'): ns3::SsidChecker::SsidChecker(ns3::SsidChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SsidChecker const &', 'arg0')])
return
def register_Ns3SsidValue_methods(root_module, cls):
## ssid.h (module 'wifi'): ns3::SsidValue::SsidValue() [constructor]
cls.add_constructor([])
## ssid.h (module 'wifi'): ns3::SsidValue::SsidValue(ns3::SsidValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SsidValue const &', 'arg0')])
## ssid.h (module 'wifi'): ns3::SsidValue::SsidValue(ns3::Ssid const & value) [constructor]
cls.add_constructor([param('ns3::Ssid const &', 'value')])
## ssid.h (module 'wifi'): ns3::Ptr<ns3::AttributeValue> ns3::SsidValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ssid.h (module 'wifi'): bool ns3::SsidValue::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)
## ssid.h (module 'wifi'): ns3::Ssid ns3::SsidValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ssid',
[],
is_const=True)
## ssid.h (module 'wifi'): std::string ns3::SsidValue::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)
## ssid.h (module 'wifi'): void ns3::SsidValue::Set(ns3::Ssid const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ssid const &', 'value')])
return
def register_Ns3TcpL4Protocol_methods(root_module, cls):
## tcp-l4-protocol.h (module 'internet'): ns3::TcpL4Protocol::PROT_NUMBER [variable]
cls.add_static_attribute('PROT_NUMBER', 'uint8_t const', is_const=True)
## tcp-l4-protocol.h (module 'internet'): static ns3::TypeId ns3::TcpL4Protocol::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## tcp-l4-protocol.h (module 'internet'): ns3::TcpL4Protocol::TcpL4Protocol() [constructor]
cls.add_constructor([])
## tcp-l4-protocol.h (module 'internet'): void ns3::TcpL4Protocol::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## tcp-l4-protocol.h (module 'internet'): int ns3::TcpL4Protocol::GetProtocolNumber() const [member function]
cls.add_method('GetProtocolNumber',
'int',
[],
is_const=True, is_virtual=True)
## tcp-l4-protocol.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::TcpL4Protocol::CreateSocket() [member function]
cls.add_method('CreateSocket',
'ns3::Ptr< ns3::Socket >',
[])
## tcp-l4-protocol.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::TcpL4Protocol::CreateSocket(ns3::TypeId socketTypeId) [member function]
cls.add_method('CreateSocket',
'ns3::Ptr< ns3::Socket >',
[param('ns3::TypeId', 'socketTypeId')])
## tcp-l4-protocol.h (module 'internet'): ns3::Ipv4EndPoint * ns3::TcpL4Protocol::Allocate() [member function]
cls.add_method('Allocate',
'ns3::Ipv4EndPoint *',
[])
## tcp-l4-protocol.h (module 'internet'): ns3::Ipv4EndPoint * ns3::TcpL4Protocol::Allocate(ns3::Ipv4Address address) [member function]
cls.add_method('Allocate',
'ns3::Ipv4EndPoint *',
[param('ns3::Ipv4Address', 'address')])
## tcp-l4-protocol.h (module 'internet'): ns3::Ipv4EndPoint * ns3::TcpL4Protocol::Allocate(uint16_t port) [member function]
cls.add_method('Allocate',
'ns3::Ipv4EndPoint *',
[param('uint16_t', 'port')])
## tcp-l4-protocol.h (module 'internet'): ns3::Ipv4EndPoint * ns3::TcpL4Protocol::Allocate(ns3::Ipv4Address address, uint16_t port) [member function]
cls.add_method('Allocate',
'ns3::Ipv4EndPoint *',
[param('ns3::Ipv4Address', 'address'), param('uint16_t', 'port')])
## tcp-l4-protocol.h (module 'internet'): ns3::Ipv4EndPoint * ns3::TcpL4Protocol::Allocate(ns3::Ipv4Address localAddress, uint16_t localPort, ns3::Ipv4Address peerAddress, uint16_t peerPort) [member function]
cls.add_method('Allocate',
'ns3::Ipv4EndPoint *',
[param('ns3::Ipv4Address', 'localAddress'), param('uint16_t', 'localPort'), param('ns3::Ipv4Address', 'peerAddress'), param('uint16_t', 'peerPort')])
## tcp-l4-protocol.h (module 'internet'): ns3::Ipv6EndPoint * ns3::TcpL4Protocol::Allocate6() [member function]
cls.add_method('Allocate6',
'ns3::Ipv6EndPoint *',
[])
## tcp-l4-protocol.h (module 'internet'): ns3::Ipv6EndPoint * ns3::TcpL4Protocol::Allocate6(ns3::Ipv6Address address) [member function]
cls.add_method('Allocate6',
'ns3::Ipv6EndPoint *',
[param('ns3::Ipv6Address', 'address')])
## tcp-l4-protocol.h (module 'internet'): ns3::Ipv6EndPoint * ns3::TcpL4Protocol::Allocate6(uint16_t port) [member function]
cls.add_method('Allocate6',
'ns3::Ipv6EndPoint *',
[param('uint16_t', 'port')])
## tcp-l4-protocol.h (module 'internet'): ns3::Ipv6EndPoint * ns3::TcpL4Protocol::Allocate6(ns3::Ipv6Address address, uint16_t port) [member function]
cls.add_method('Allocate6',
'ns3::Ipv6EndPoint *',
[param('ns3::Ipv6Address', 'address'), param('uint16_t', 'port')])
## tcp-l4-protocol.h (module 'internet'): ns3::Ipv6EndPoint * ns3::TcpL4Protocol::Allocate6(ns3::Ipv6Address localAddress, uint16_t localPort, ns3::Ipv6Address peerAddress, uint16_t peerPort) [member function]
cls.add_method('Allocate6',
'ns3::Ipv6EndPoint *',
[param('ns3::Ipv6Address', 'localAddress'), param('uint16_t', 'localPort'), param('ns3::Ipv6Address', 'peerAddress'), param('uint16_t', 'peerPort')])
## tcp-l4-protocol.h (module 'internet'): void ns3::TcpL4Protocol::DeAllocate(ns3::Ipv4EndPoint * endPoint) [member function]
cls.add_method('DeAllocate',
'void',
[param('ns3::Ipv4EndPoint *', 'endPoint')])
## tcp-l4-protocol.h (module 'internet'): void ns3::TcpL4Protocol::DeAllocate(ns3::Ipv6EndPoint * endPoint) [member function]
cls.add_method('DeAllocate',
'void',
[param('ns3::Ipv6EndPoint *', 'endPoint')])
## tcp-l4-protocol.h (module 'internet'): void ns3::TcpL4Protocol::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address saddr, ns3::Ipv4Address daddr, uint16_t sport, uint16_t dport, ns3::Ptr<ns3::NetDevice> oif=0) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'saddr'), param('ns3::Ipv4Address', 'daddr'), param('uint16_t', 'sport'), param('uint16_t', 'dport'), param('ns3::Ptr< ns3::NetDevice >', 'oif', default_value='0')])
## tcp-l4-protocol.h (module 'internet'): void ns3::TcpL4Protocol::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv6Address saddr, ns3::Ipv6Address daddr, uint16_t sport, uint16_t dport, ns3::Ptr<ns3::NetDevice> oif=0) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv6Address', 'saddr'), param('ns3::Ipv6Address', 'daddr'), param('uint16_t', 'sport'), param('uint16_t', 'dport'), param('ns3::Ptr< ns3::NetDevice >', 'oif', default_value='0')])
## tcp-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::TcpL4Protocol::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_virtual=True)
## tcp-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::TcpL4Protocol::Receive(ns3::Ptr<ns3::Packet> p, ns3::Ipv6Address & src, ns3::Ipv6Address & dst, ns3::Ptr<ns3::Ipv6Interface> interface) [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 >', 'interface')],
is_virtual=True)
## tcp-l4-protocol.h (module 'internet'): void ns3::TcpL4Protocol::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)
## tcp-l4-protocol.h (module 'internet'): void ns3::TcpL4Protocol::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)
## tcp-l4-protocol.h (module 'internet'): void ns3::TcpL4Protocol::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_virtual=True)
## tcp-l4-protocol.h (module 'internet'): void ns3::TcpL4Protocol::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_virtual=True)
## tcp-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::TcpL4Protocol::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_const=True, is_virtual=True)
## tcp-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::TcpL4Protocol::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_const=True, is_virtual=True)
## tcp-l4-protocol.h (module 'internet'): void ns3::TcpL4Protocol::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## tcp-l4-protocol.h (module 'internet'): void ns3::TcpL4Protocol::NotifyNewAggregate() [member function]
cls.add_method('NotifyNewAggregate',
'void',
[],
visibility='protected', 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_Ns3UdpL4Protocol_methods(root_module, cls):
## udp-l4-protocol.h (module 'internet'): ns3::UdpL4Protocol::PROT_NUMBER [variable]
cls.add_static_attribute('PROT_NUMBER', 'uint8_t const', is_const=True)
## udp-l4-protocol.h (module 'internet'): static ns3::TypeId ns3::UdpL4Protocol::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## udp-l4-protocol.h (module 'internet'): ns3::UdpL4Protocol::UdpL4Protocol() [constructor]
cls.add_constructor([])
## udp-l4-protocol.h (module 'internet'): void ns3::UdpL4Protocol::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## udp-l4-protocol.h (module 'internet'): int ns3::UdpL4Protocol::GetProtocolNumber() const [member function]
cls.add_method('GetProtocolNumber',
'int',
[],
is_const=True, is_virtual=True)
## udp-l4-protocol.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::UdpL4Protocol::CreateSocket() [member function]
cls.add_method('CreateSocket',
'ns3::Ptr< ns3::Socket >',
[])
## udp-l4-protocol.h (module 'internet'): ns3::Ipv4EndPoint * ns3::UdpL4Protocol::Allocate() [member function]
cls.add_method('Allocate',
'ns3::Ipv4EndPoint *',
[])
## udp-l4-protocol.h (module 'internet'): ns3::Ipv4EndPoint * ns3::UdpL4Protocol::Allocate(ns3::Ipv4Address address) [member function]
cls.add_method('Allocate',
'ns3::Ipv4EndPoint *',
[param('ns3::Ipv4Address', 'address')])
## udp-l4-protocol.h (module 'internet'): ns3::Ipv4EndPoint * ns3::UdpL4Protocol::Allocate(uint16_t port) [member function]
cls.add_method('Allocate',
'ns3::Ipv4EndPoint *',
[param('uint16_t', 'port')])
## udp-l4-protocol.h (module 'internet'): ns3::Ipv4EndPoint * ns3::UdpL4Protocol::Allocate(ns3::Ipv4Address address, uint16_t port) [member function]
cls.add_method('Allocate',
'ns3::Ipv4EndPoint *',
[param('ns3::Ipv4Address', 'address'), param('uint16_t', 'port')])
## udp-l4-protocol.h (module 'internet'): ns3::Ipv4EndPoint * ns3::UdpL4Protocol::Allocate(ns3::Ipv4Address localAddress, uint16_t localPort, ns3::Ipv4Address peerAddress, uint16_t peerPort) [member function]
cls.add_method('Allocate',
'ns3::Ipv4EndPoint *',
[param('ns3::Ipv4Address', 'localAddress'), param('uint16_t', 'localPort'), param('ns3::Ipv4Address', 'peerAddress'), param('uint16_t', 'peerPort')])
## udp-l4-protocol.h (module 'internet'): ns3::Ipv6EndPoint * ns3::UdpL4Protocol::Allocate6() [member function]
cls.add_method('Allocate6',
'ns3::Ipv6EndPoint *',
[])
## udp-l4-protocol.h (module 'internet'): ns3::Ipv6EndPoint * ns3::UdpL4Protocol::Allocate6(ns3::Ipv6Address address) [member function]
cls.add_method('Allocate6',
'ns3::Ipv6EndPoint *',
[param('ns3::Ipv6Address', 'address')])
## udp-l4-protocol.h (module 'internet'): ns3::Ipv6EndPoint * ns3::UdpL4Protocol::Allocate6(uint16_t port) [member function]
cls.add_method('Allocate6',
'ns3::Ipv6EndPoint *',
[param('uint16_t', 'port')])
## udp-l4-protocol.h (module 'internet'): ns3::Ipv6EndPoint * ns3::UdpL4Protocol::Allocate6(ns3::Ipv6Address address, uint16_t port) [member function]
cls.add_method('Allocate6',
'ns3::Ipv6EndPoint *',
[param('ns3::Ipv6Address', 'address'), param('uint16_t', 'port')])
## udp-l4-protocol.h (module 'internet'): ns3::Ipv6EndPoint * ns3::UdpL4Protocol::Allocate6(ns3::Ipv6Address localAddress, uint16_t localPort, ns3::Ipv6Address peerAddress, uint16_t peerPort) [member function]
cls.add_method('Allocate6',
'ns3::Ipv6EndPoint *',
[param('ns3::Ipv6Address', 'localAddress'), param('uint16_t', 'localPort'), param('ns3::Ipv6Address', 'peerAddress'), param('uint16_t', 'peerPort')])
## udp-l4-protocol.h (module 'internet'): void ns3::UdpL4Protocol::DeAllocate(ns3::Ipv4EndPoint * endPoint) [member function]
cls.add_method('DeAllocate',
'void',
[param('ns3::Ipv4EndPoint *', 'endPoint')])
## udp-l4-protocol.h (module 'internet'): void ns3::UdpL4Protocol::DeAllocate(ns3::Ipv6EndPoint * endPoint) [member function]
cls.add_method('DeAllocate',
'void',
[param('ns3::Ipv6EndPoint *', 'endPoint')])
## udp-l4-protocol.h (module 'internet'): void ns3::UdpL4Protocol::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address saddr, ns3::Ipv4Address daddr, uint16_t sport, uint16_t dport) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'saddr'), param('ns3::Ipv4Address', 'daddr'), param('uint16_t', 'sport'), param('uint16_t', 'dport')])
## udp-l4-protocol.h (module 'internet'): void ns3::UdpL4Protocol::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address saddr, ns3::Ipv4Address daddr, uint16_t sport, uint16_t dport, ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'saddr'), param('ns3::Ipv4Address', 'daddr'), param('uint16_t', 'sport'), param('uint16_t', 'dport'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')])
## udp-l4-protocol.h (module 'internet'): void ns3::UdpL4Protocol::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv6Address saddr, ns3::Ipv6Address daddr, uint16_t sport, uint16_t dport) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv6Address', 'saddr'), param('ns3::Ipv6Address', 'daddr'), param('uint16_t', 'sport'), param('uint16_t', 'dport')])
## udp-l4-protocol.h (module 'internet'): void ns3::UdpL4Protocol::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv6Address saddr, ns3::Ipv6Address daddr, uint16_t sport, uint16_t dport, ns3::Ptr<ns3::Ipv6Route> route) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv6Address', 'saddr'), param('ns3::Ipv6Address', 'daddr'), param('uint16_t', 'sport'), param('uint16_t', 'dport'), param('ns3::Ptr< ns3::Ipv6Route >', 'route')])
## udp-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::UdpL4Protocol::Receive(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::Ipv4Interface> interface) [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 >', 'interface')],
is_virtual=True)
## udp-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::UdpL4Protocol::Receive(ns3::Ptr<ns3::Packet> p, ns3::Ipv6Address & src, ns3::Ipv6Address & dst, ns3::Ptr<ns3::Ipv6Interface> interface) [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 >', 'interface')],
is_virtual=True)
## udp-l4-protocol.h (module 'internet'): void ns3::UdpL4Protocol::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)
## udp-l4-protocol.h (module 'internet'): void ns3::UdpL4Protocol::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)
## udp-l4-protocol.h (module 'internet'): void ns3::UdpL4Protocol::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_virtual=True)
## udp-l4-protocol.h (module 'internet'): void ns3::UdpL4Protocol::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_virtual=True)
## udp-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::UdpL4Protocol::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_const=True, is_virtual=True)
## udp-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::UdpL4Protocol::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_const=True, is_virtual=True)
## udp-l4-protocol.h (module 'internet'): void ns3::UdpL4Protocol::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## udp-l4-protocol.h (module 'internet'): void ns3::UdpL4Protocol::NotifyNewAggregate() [member function]
cls.add_method('NotifyNewAggregate',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3UintegerValue_methods(root_module, cls):
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue() [constructor]
cls.add_constructor([])
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(ns3::UintegerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UintegerValue const &', 'arg0')])
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(uint64_t const & value) [constructor]
cls.add_constructor([param('uint64_t const &', 'value')])
## uinteger.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::UintegerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## uinteger.h (module 'core'): bool ns3::UintegerValue::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)
## uinteger.h (module 'core'): uint64_t ns3::UintegerValue::Get() const [member function]
cls.add_method('Get',
'uint64_t',
[],
is_const=True)
## uinteger.h (module 'core'): std::string ns3::UintegerValue::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)
## uinteger.h (module 'core'): void ns3::UintegerValue::Set(uint64_t const & value) [member function]
cls.add_method('Set',
'void',
[param('uint64_t const &', 'value')])
return
def register_Ns3WifiModeChecker_methods(root_module, cls):
## wifi-mode.h (module 'wifi'): ns3::WifiModeChecker::WifiModeChecker() [constructor]
cls.add_constructor([])
## wifi-mode.h (module 'wifi'): ns3::WifiModeChecker::WifiModeChecker(ns3::WifiModeChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiModeChecker const &', 'arg0')])
return
def register_Ns3WifiModeValue_methods(root_module, cls):
## wifi-mode.h (module 'wifi'): ns3::WifiModeValue::WifiModeValue() [constructor]
cls.add_constructor([])
## wifi-mode.h (module 'wifi'): ns3::WifiModeValue::WifiModeValue(ns3::WifiModeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiModeValue const &', 'arg0')])
## wifi-mode.h (module 'wifi'): ns3::WifiModeValue::WifiModeValue(ns3::WifiMode const & value) [constructor]
cls.add_constructor([param('ns3::WifiMode const &', 'value')])
## wifi-mode.h (module 'wifi'): ns3::Ptr<ns3::AttributeValue> ns3::WifiModeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## wifi-mode.h (module 'wifi'): bool ns3::WifiModeValue::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)
## wifi-mode.h (module 'wifi'): ns3::WifiMode ns3::WifiModeValue::Get() const [member function]
cls.add_method('Get',
'ns3::WifiMode',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): std::string ns3::WifiModeValue::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)
## wifi-mode.h (module 'wifi'): void ns3::WifiModeValue::Set(ns3::WifiMode const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::WifiMode 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_Ns3Icmpv4L4Protocol_methods(root_module, cls):
## icmpv4-l4-protocol.h (module 'internet'): ns3::Icmpv4L4Protocol::Icmpv4L4Protocol(ns3::Icmpv4L4Protocol const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Icmpv4L4Protocol const &', 'arg0')])
## icmpv4-l4-protocol.h (module 'internet'): ns3::Icmpv4L4Protocol::Icmpv4L4Protocol() [constructor]
cls.add_constructor([])
## icmpv4-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::Icmpv4L4Protocol::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_const=True, is_virtual=True)
## icmpv4-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::Icmpv4L4Protocol::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_const=True, is_virtual=True)
## icmpv4-l4-protocol.h (module 'internet'): int ns3::Icmpv4L4Protocol::GetProtocolNumber() const [member function]
cls.add_method('GetProtocolNumber',
'int',
[],
is_const=True, is_virtual=True)
## icmpv4-l4-protocol.h (module 'internet'): static uint16_t ns3::Icmpv4L4Protocol::GetStaticProtocolNumber() [member function]
cls.add_method('GetStaticProtocolNumber',
'uint16_t',
[],
is_static=True)
## icmpv4-l4-protocol.h (module 'internet'): static ns3::TypeId ns3::Icmpv4L4Protocol::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## icmpv4-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::Icmpv4L4Protocol::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_virtual=True)
## icmpv4-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::Icmpv4L4Protocol::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_virtual=True)
## icmpv4-l4-protocol.h (module 'internet'): void ns3::Icmpv4L4Protocol::SendDestUnreachFragNeeded(ns3::Ipv4Header header, ns3::Ptr<ns3::Packet const> orgData, uint16_t nextHopMtu) [member function]
cls.add_method('SendDestUnreachFragNeeded',
'void',
[param('ns3::Ipv4Header', 'header'), param('ns3::Ptr< ns3::Packet const >', 'orgData'), param('uint16_t', 'nextHopMtu')])
## icmpv4-l4-protocol.h (module 'internet'): void ns3::Icmpv4L4Protocol::SendDestUnreachPort(ns3::Ipv4Header header, ns3::Ptr<ns3::Packet const> orgData) [member function]
cls.add_method('SendDestUnreachPort',
'void',
[param('ns3::Ipv4Header', 'header'), param('ns3::Ptr< ns3::Packet const >', 'orgData')])
## icmpv4-l4-protocol.h (module 'internet'): void ns3::Icmpv4L4Protocol::SendTimeExceededTtl(ns3::Ipv4Header header, ns3::Ptr<ns3::Packet const> orgData) [member function]
cls.add_method('SendTimeExceededTtl',
'void',
[param('ns3::Ipv4Header', 'header'), param('ns3::Ptr< ns3::Packet const >', 'orgData')])
## icmpv4-l4-protocol.h (module 'internet'): void ns3::Icmpv4L4Protocol::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_virtual=True)
## icmpv4-l4-protocol.h (module 'internet'): void ns3::Icmpv4L4Protocol::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_virtual=True)
## icmpv4-l4-protocol.h (module 'internet'): void ns3::Icmpv4L4Protocol::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## icmpv4-l4-protocol.h (module 'internet'): ns3::Icmpv4L4Protocol::PROT_NUMBER [variable]
cls.add_static_attribute('PROT_NUMBER', 'uint8_t const', is_const=True)
## icmpv4-l4-protocol.h (module 'internet'): void ns3::Icmpv4L4Protocol::NotifyNewAggregate() [member function]
cls.add_method('NotifyNewAggregate',
'void',
[],
visibility='protected', is_virtual=True)
## icmpv4-l4-protocol.h (module 'internet'): void ns3::Icmpv4L4Protocol::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3DsrBlackList_methods(root_module, cls):
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::BlackList::BlackList(ns3::dsr::BlackList const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::BlackList const &', 'arg0')])
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::BlackList::BlackList(ns3::Ipv4Address ip, ns3::Time t) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'ip'), param('ns3::Time', 't')])
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::BlackList::m_expireTime [variable]
cls.add_instance_attribute('m_expireTime', 'ns3::Time', is_const=False)
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::BlackList::m_linkStates [variable]
cls.add_instance_attribute('m_linkStates', 'ns3::dsr::LinkStates', is_const=False)
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::BlackList::m_neighborAddress [variable]
cls.add_instance_attribute('m_neighborAddress', 'ns3::Ipv4Address', is_const=False)
return
def register_Ns3DsrDsrFsHeader_methods(root_module, cls):
## dsr-fs-header.h (module 'dsr'): ns3::dsr::DsrFsHeader::DsrFsHeader(ns3::dsr::DsrFsHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrFsHeader const &', 'arg0')])
## dsr-fs-header.h (module 'dsr'): ns3::dsr::DsrFsHeader::DsrFsHeader() [constructor]
cls.add_constructor([])
## dsr-fs-header.h (module 'dsr'): uint32_t ns3::dsr::DsrFsHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## dsr-fs-header.h (module 'dsr'): uint16_t ns3::dsr::DsrFsHeader::GetDestId() const [member function]
cls.add_method('GetDestId',
'uint16_t',
[],
is_const=True)
## dsr-fs-header.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrFsHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-fs-header.h (module 'dsr'): uint8_t ns3::dsr::DsrFsHeader::GetMessageType() const [member function]
cls.add_method('GetMessageType',
'uint8_t',
[],
is_const=True)
## dsr-fs-header.h (module 'dsr'): uint8_t ns3::dsr::DsrFsHeader::GetNextHeader() const [member function]
cls.add_method('GetNextHeader',
'uint8_t',
[],
is_const=True)
## dsr-fs-header.h (module 'dsr'): uint16_t ns3::dsr::DsrFsHeader::GetPayloadLength() const [member function]
cls.add_method('GetPayloadLength',
'uint16_t',
[],
is_const=True)
## dsr-fs-header.h (module 'dsr'): uint32_t ns3::dsr::DsrFsHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dsr-fs-header.h (module 'dsr'): uint16_t ns3::dsr::DsrFsHeader::GetSourceId() const [member function]
cls.add_method('GetSourceId',
'uint16_t',
[],
is_const=True)
## dsr-fs-header.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrFsHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-fs-header.h (module 'dsr'): void ns3::dsr::DsrFsHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## dsr-fs-header.h (module 'dsr'): void ns3::dsr::DsrFsHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## dsr-fs-header.h (module 'dsr'): void ns3::dsr::DsrFsHeader::SetDestId(uint16_t destId) [member function]
cls.add_method('SetDestId',
'void',
[param('uint16_t', 'destId')])
## dsr-fs-header.h (module 'dsr'): void ns3::dsr::DsrFsHeader::SetMessageType(uint8_t messageType) [member function]
cls.add_method('SetMessageType',
'void',
[param('uint8_t', 'messageType')])
## dsr-fs-header.h (module 'dsr'): void ns3::dsr::DsrFsHeader::SetNextHeader(uint8_t protocol) [member function]
cls.add_method('SetNextHeader',
'void',
[param('uint8_t', 'protocol')])
## dsr-fs-header.h (module 'dsr'): void ns3::dsr::DsrFsHeader::SetPayloadLength(uint16_t length) [member function]
cls.add_method('SetPayloadLength',
'void',
[param('uint16_t', 'length')])
## dsr-fs-header.h (module 'dsr'): void ns3::dsr::DsrFsHeader::SetSourceId(uint16_t sourceId) [member function]
cls.add_method('SetSourceId',
'void',
[param('uint16_t', 'sourceId')])
return
def register_Ns3DsrDsrNetworkQueue_methods(root_module, cls):
## dsr-network-queue.h (module 'dsr'): ns3::dsr::DsrNetworkQueue::DsrNetworkQueue(ns3::dsr::DsrNetworkQueue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrNetworkQueue const &', 'arg0')])
## dsr-network-queue.h (module 'dsr'): ns3::dsr::DsrNetworkQueue::DsrNetworkQueue() [constructor]
cls.add_constructor([])
## dsr-network-queue.h (module 'dsr'): ns3::dsr::DsrNetworkQueue::DsrNetworkQueue(uint32_t maxLen, ns3::Time maxDelay) [constructor]
cls.add_constructor([param('uint32_t', 'maxLen'), param('ns3::Time', 'maxDelay')])
## dsr-network-queue.h (module 'dsr'): bool ns3::dsr::DsrNetworkQueue::Dequeue(ns3::dsr::DsrNetworkQueueEntry & entry) [member function]
cls.add_method('Dequeue',
'bool',
[param('ns3::dsr::DsrNetworkQueueEntry &', 'entry')])
## dsr-network-queue.h (module 'dsr'): bool ns3::dsr::DsrNetworkQueue::Enqueue(ns3::dsr::DsrNetworkQueueEntry & entry) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::dsr::DsrNetworkQueueEntry &', 'entry')])
## dsr-network-queue.h (module 'dsr'): void ns3::dsr::DsrNetworkQueue::Flush() [member function]
cls.add_method('Flush',
'void',
[])
## dsr-network-queue.h (module 'dsr'): ns3::Time ns3::dsr::DsrNetworkQueue::GetMaxNetworkDelay() const [member function]
cls.add_method('GetMaxNetworkDelay',
'ns3::Time',
[],
is_const=True)
## dsr-network-queue.h (module 'dsr'): uint32_t ns3::dsr::DsrNetworkQueue::GetMaxNetworkSize() const [member function]
cls.add_method('GetMaxNetworkSize',
'uint32_t',
[],
is_const=True)
## dsr-network-queue.h (module 'dsr'): std::vector<ns3::dsr::DsrNetworkQueueEntry, std::allocator<ns3::dsr::DsrNetworkQueueEntry> > & ns3::dsr::DsrNetworkQueue::GetQueue() [member function]
cls.add_method('GetQueue',
'std::vector< ns3::dsr::DsrNetworkQueueEntry > &',
[])
## dsr-network-queue.h (module 'dsr'): uint32_t ns3::dsr::DsrNetworkQueue::GetSize() [member function]
cls.add_method('GetSize',
'uint32_t',
[])
## dsr-network-queue.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrNetworkQueue::GetTypeID() [member function]
cls.add_method('GetTypeID',
'ns3::TypeId',
[],
is_static=True)
## dsr-network-queue.h (module 'dsr'): void ns3::dsr::DsrNetworkQueue::SetMaxNetworkDelay(ns3::Time delay) [member function]
cls.add_method('SetMaxNetworkDelay',
'void',
[param('ns3::Time', 'delay')])
## dsr-network-queue.h (module 'dsr'): void ns3::dsr::DsrNetworkQueue::SetMaxNetworkSize(uint32_t maxSize) [member function]
cls.add_method('SetMaxNetworkSize',
'void',
[param('uint32_t', 'maxSize')])
return
def register_Ns3DsrDsrNetworkQueueEntry_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
## dsr-network-queue.h (module 'dsr'): ns3::dsr::DsrNetworkQueueEntry::DsrNetworkQueueEntry(ns3::dsr::DsrNetworkQueueEntry const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrNetworkQueueEntry const &', 'arg0')])
## dsr-network-queue.h (module 'dsr'): ns3::dsr::DsrNetworkQueueEntry::DsrNetworkQueueEntry(ns3::Ptr<ns3::Packet const> pa=0, ns3::Ipv4Address s=ns3::Ipv4Address(), ns3::Ipv4Address n=ns3::Ipv4Address(), ns3::Time exp=ns3::Simulator::Now( ), ns3::Ptr<ns3::Ipv4Route> r=0) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Packet const >', 'pa', default_value='0'), param('ns3::Ipv4Address', 's', default_value='ns3::Ipv4Address()'), param('ns3::Ipv4Address', 'n', default_value='ns3::Ipv4Address()'), param('ns3::Time', 'exp', default_value='ns3::Simulator::Now( )'), param('ns3::Ptr< ns3::Ipv4Route >', 'r', default_value='0')])
## dsr-network-queue.h (module 'dsr'): ns3::Time ns3::dsr::DsrNetworkQueueEntry::GetInsertedTimeStamp() const [member function]
cls.add_method('GetInsertedTimeStamp',
'ns3::Time',
[],
is_const=True)
## dsr-network-queue.h (module 'dsr'): ns3::Ptr<ns3::Ipv4Route> ns3::dsr::DsrNetworkQueueEntry::GetIpv4Route() const [member function]
cls.add_method('GetIpv4Route',
'ns3::Ptr< ns3::Ipv4Route >',
[],
is_const=True)
## dsr-network-queue.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrNetworkQueueEntry::GetNextHopAddress() const [member function]
cls.add_method('GetNextHopAddress',
'ns3::Ipv4Address',
[],
is_const=True)
## dsr-network-queue.h (module 'dsr'): ns3::Ptr<ns3::Packet const> ns3::dsr::DsrNetworkQueueEntry::GetPacket() const [member function]
cls.add_method('GetPacket',
'ns3::Ptr< ns3::Packet const >',
[],
is_const=True)
## dsr-network-queue.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrNetworkQueueEntry::GetSourceAddress() const [member function]
cls.add_method('GetSourceAddress',
'ns3::Ipv4Address',
[],
is_const=True)
## dsr-network-queue.h (module 'dsr'): void ns3::dsr::DsrNetworkQueueEntry::SetInsertedTimeStamp(ns3::Time time) [member function]
cls.add_method('SetInsertedTimeStamp',
'void',
[param('ns3::Time', 'time')])
## dsr-network-queue.h (module 'dsr'): void ns3::dsr::DsrNetworkQueueEntry::SetIpv4Route(ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('SetIpv4Route',
'void',
[param('ns3::Ptr< ns3::Ipv4Route >', 'route')])
## dsr-network-queue.h (module 'dsr'): void ns3::dsr::DsrNetworkQueueEntry::SetNextHopAddress(ns3::Ipv4Address addr) [member function]
cls.add_method('SetNextHopAddress',
'void',
[param('ns3::Ipv4Address', 'addr')])
## dsr-network-queue.h (module 'dsr'): void ns3::dsr::DsrNetworkQueueEntry::SetPacket(ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('SetPacket',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'p')])
## dsr-network-queue.h (module 'dsr'): void ns3::dsr::DsrNetworkQueueEntry::SetSourceAddress(ns3::Ipv4Address addr) [member function]
cls.add_method('SetSourceAddress',
'void',
[param('ns3::Ipv4Address', 'addr')])
return
def register_Ns3DsrDsrOptionField_methods(root_module, cls):
## dsr-fs-header.h (module 'dsr'): ns3::dsr::DsrOptionField::DsrOptionField(ns3::dsr::DsrOptionField const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionField const &', 'arg0')])
## dsr-fs-header.h (module 'dsr'): ns3::dsr::DsrOptionField::DsrOptionField(uint32_t optionsOffset) [constructor]
cls.add_constructor([param('uint32_t', 'optionsOffset')])
## dsr-fs-header.h (module 'dsr'): void ns3::dsr::DsrOptionField::AddDsrOption(ns3::dsr::DsrOptionHeader const & option) [member function]
cls.add_method('AddDsrOption',
'void',
[param('ns3::dsr::DsrOptionHeader const &', 'option')])
## dsr-fs-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionField::Deserialize(ns3::Buffer::Iterator start, uint32_t length) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'length')])
## dsr-fs-header.h (module 'dsr'): ns3::Buffer ns3::dsr::DsrOptionField::GetDsrOptionBuffer() [member function]
cls.add_method('GetDsrOptionBuffer',
'ns3::Buffer',
[])
## dsr-fs-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionField::GetDsrOptionsOffset() [member function]
cls.add_method('GetDsrOptionsOffset',
'uint32_t',
[])
## dsr-fs-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionField::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## dsr-fs-header.h (module 'dsr'): void ns3::dsr::DsrOptionField::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True)
return
def register_Ns3DsrDsrOptionHeader_methods(root_module, cls):
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionHeader::DsrOptionHeader(ns3::dsr::DsrOptionHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionHeader const &', 'arg0')])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionHeader::DsrOptionHeader() [constructor]
cls.add_constructor([])
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionHeader::Alignment ns3::dsr::DsrOptionHeader::GetAlignment() const [member function]
cls.add_method('GetAlignment',
'ns3::dsr::DsrOptionHeader::Alignment',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrOptionHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionHeader::GetLength() const [member function]
cls.add_method('GetLength',
'uint8_t',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionHeader::GetType() const [member function]
cls.add_method('GetType',
'uint8_t',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionHeader::SetLength(uint8_t length) [member function]
cls.add_method('SetLength',
'void',
[param('uint8_t', 'length')])
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionHeader::SetType(uint8_t type) [member function]
cls.add_method('SetType',
'void',
[param('uint8_t', 'type')])
return
def register_Ns3DsrDsrOptionHeaderAlignment_methods(root_module, cls):
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionHeader::Alignment::Alignment() [constructor]
cls.add_constructor([])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionHeader::Alignment::Alignment(ns3::dsr::DsrOptionHeader::Alignment const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionHeader::Alignment const &', 'arg0')])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionHeader::Alignment::factor [variable]
cls.add_instance_attribute('factor', 'uint8_t', is_const=False)
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionHeader::Alignment::offset [variable]
cls.add_instance_attribute('offset', 'uint8_t', is_const=False)
return
def register_Ns3DsrDsrOptionPad1Header_methods(root_module, cls):
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionPad1Header::DsrOptionPad1Header(ns3::dsr::DsrOptionPad1Header const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionPad1Header const &', 'arg0')])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionPad1Header::DsrOptionPad1Header() [constructor]
cls.add_constructor([])
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionPad1Header::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrOptionPad1Header::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionPad1Header::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionPad1Header::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionPad1Header::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionPad1Header::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_Ns3DsrDsrOptionPadnHeader_methods(root_module, cls):
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionPadnHeader::DsrOptionPadnHeader(ns3::dsr::DsrOptionPadnHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionPadnHeader const &', 'arg0')])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionPadnHeader::DsrOptionPadnHeader(uint32_t pad=2) [constructor]
cls.add_constructor([param('uint32_t', 'pad', default_value='2')])
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionPadnHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrOptionPadnHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionPadnHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionPadnHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionPadnHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionPadnHeader::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_Ns3DsrDsrOptionRerrHeader_methods(root_module, cls):
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionRerrHeader::DsrOptionRerrHeader(ns3::dsr::DsrOptionRerrHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionRerrHeader const &', 'arg0')])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionRerrHeader::DsrOptionRerrHeader() [constructor]
cls.add_constructor([])
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionRerrHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionHeader::Alignment ns3::dsr::DsrOptionRerrHeader::GetAlignment() const [member function]
cls.add_method('GetAlignment',
'ns3::dsr::DsrOptionHeader::Alignment',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrOptionRerrHeader::GetErrorDst() const [member function]
cls.add_method('GetErrorDst',
'ns3::Ipv4Address',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrOptionRerrHeader::GetErrorSrc() const [member function]
cls.add_method('GetErrorSrc',
'ns3::Ipv4Address',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionRerrHeader::GetErrorType() const [member function]
cls.add_method('GetErrorType',
'uint8_t',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrOptionRerrHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionRerrHeader::GetSalvage() const [member function]
cls.add_method('GetSalvage',
'uint8_t',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionRerrHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionRerrHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrHeader::SetErrorDst(ns3::Ipv4Address errorDstAddress) [member function]
cls.add_method('SetErrorDst',
'void',
[param('ns3::Ipv4Address', 'errorDstAddress')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrHeader::SetErrorSrc(ns3::Ipv4Address errorSrcAddress) [member function]
cls.add_method('SetErrorSrc',
'void',
[param('ns3::Ipv4Address', 'errorSrcAddress')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrHeader::SetErrorType(uint8_t errorType) [member function]
cls.add_method('SetErrorType',
'void',
[param('uint8_t', 'errorType')])
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrHeader::SetSalvage(uint8_t salvage) [member function]
cls.add_method('SetSalvage',
'void',
[param('uint8_t', 'salvage')],
is_virtual=True)
return
def register_Ns3DsrDsrOptionRerrUnreachHeader_methods(root_module, cls):
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionRerrUnreachHeader::DsrOptionRerrUnreachHeader(ns3::dsr::DsrOptionRerrUnreachHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionRerrUnreachHeader const &', 'arg0')])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionRerrUnreachHeader::DsrOptionRerrUnreachHeader() [constructor]
cls.add_constructor([])
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionRerrUnreachHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionHeader::Alignment ns3::dsr::DsrOptionRerrUnreachHeader::GetAlignment() const [member function]
cls.add_method('GetAlignment',
'ns3::dsr::DsrOptionHeader::Alignment',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrOptionRerrUnreachHeader::GetErrorDst() const [member function]
cls.add_method('GetErrorDst',
'ns3::Ipv4Address',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrOptionRerrUnreachHeader::GetErrorSrc() const [member function]
cls.add_method('GetErrorSrc',
'ns3::Ipv4Address',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrOptionRerrUnreachHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrOptionRerrUnreachHeader::GetOriginalDst() const [member function]
cls.add_method('GetOriginalDst',
'ns3::Ipv4Address',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionRerrUnreachHeader::GetSalvage() const [member function]
cls.add_method('GetSalvage',
'uint8_t',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionRerrUnreachHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionRerrUnreachHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-option-header.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrOptionRerrUnreachHeader::GetUnreachNode() const [member function]
cls.add_method('GetUnreachNode',
'ns3::Ipv4Address',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrUnreachHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrUnreachHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrUnreachHeader::SetErrorDst(ns3::Ipv4Address errorDstAddress) [member function]
cls.add_method('SetErrorDst',
'void',
[param('ns3::Ipv4Address', 'errorDstAddress')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrUnreachHeader::SetErrorSrc(ns3::Ipv4Address errorSrcAddress) [member function]
cls.add_method('SetErrorSrc',
'void',
[param('ns3::Ipv4Address', 'errorSrcAddress')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrUnreachHeader::SetOriginalDst(ns3::Ipv4Address originalDst) [member function]
cls.add_method('SetOriginalDst',
'void',
[param('ns3::Ipv4Address', 'originalDst')])
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrUnreachHeader::SetSalvage(uint8_t salvage) [member function]
cls.add_method('SetSalvage',
'void',
[param('uint8_t', 'salvage')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrUnreachHeader::SetUnreachNode(ns3::Ipv4Address unreachNode) [member function]
cls.add_method('SetUnreachNode',
'void',
[param('ns3::Ipv4Address', 'unreachNode')])
return
def register_Ns3DsrDsrOptionRerrUnsupportHeader_methods(root_module, cls):
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionRerrUnsupportHeader::DsrOptionRerrUnsupportHeader(ns3::dsr::DsrOptionRerrUnsupportHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionRerrUnsupportHeader const &', 'arg0')])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionRerrUnsupportHeader::DsrOptionRerrUnsupportHeader() [constructor]
cls.add_constructor([])
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionRerrUnsupportHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionHeader::Alignment ns3::dsr::DsrOptionRerrUnsupportHeader::GetAlignment() const [member function]
cls.add_method('GetAlignment',
'ns3::dsr::DsrOptionHeader::Alignment',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrOptionRerrUnsupportHeader::GetErrorDst() const [member function]
cls.add_method('GetErrorDst',
'ns3::Ipv4Address',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrOptionRerrUnsupportHeader::GetErrorSrc() const [member function]
cls.add_method('GetErrorSrc',
'ns3::Ipv4Address',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrOptionRerrUnsupportHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionRerrUnsupportHeader::GetSalvage() const [member function]
cls.add_method('GetSalvage',
'uint8_t',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionRerrUnsupportHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionRerrUnsupportHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-option-header.h (module 'dsr'): uint16_t ns3::dsr::DsrOptionRerrUnsupportHeader::GetUnsupported() const [member function]
cls.add_method('GetUnsupported',
'uint16_t',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrUnsupportHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrUnsupportHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrUnsupportHeader::SetErrorDst(ns3::Ipv4Address errorDstAddress) [member function]
cls.add_method('SetErrorDst',
'void',
[param('ns3::Ipv4Address', 'errorDstAddress')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrUnsupportHeader::SetErrorSrc(ns3::Ipv4Address errorSrcAddress) [member function]
cls.add_method('SetErrorSrc',
'void',
[param('ns3::Ipv4Address', 'errorSrcAddress')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrUnsupportHeader::SetSalvage(uint8_t salvage) [member function]
cls.add_method('SetSalvage',
'void',
[param('uint8_t', 'salvage')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRerrUnsupportHeader::SetUnsupported(uint16_t optionType) [member function]
cls.add_method('SetUnsupported',
'void',
[param('uint16_t', 'optionType')])
return
def register_Ns3DsrDsrOptionRrepHeader_methods(root_module, cls):
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionRrepHeader::DsrOptionRrepHeader(ns3::dsr::DsrOptionRrepHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionRrepHeader const &', 'arg0')])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionRrepHeader::DsrOptionRrepHeader() [constructor]
cls.add_constructor([])
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionRrepHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionHeader::Alignment ns3::dsr::DsrOptionRrepHeader::GetAlignment() const [member function]
cls.add_method('GetAlignment',
'ns3::dsr::DsrOptionHeader::Alignment',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrOptionRrepHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrOptionRrepHeader::GetNodeAddress(uint8_t index) const [member function]
cls.add_method('GetNodeAddress',
'ns3::Ipv4Address',
[param('uint8_t', 'index')],
is_const=True)
## dsr-option-header.h (module 'dsr'): std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > ns3::dsr::DsrOptionRrepHeader::GetNodesAddress() const [member function]
cls.add_method('GetNodesAddress',
'std::vector< ns3::Ipv4Address >',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionRrepHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrOptionRrepHeader::GetTargetAddress(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > ipv4Address) const [member function]
cls.add_method('GetTargetAddress',
'ns3::Ipv4Address',
[param('std::vector< ns3::Ipv4Address >', 'ipv4Address')],
is_const=True)
## dsr-option-header.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionRrepHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRrepHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrOptionRrepHeader::SearchNextHop(ns3::Ipv4Address ipv4Address) [member function]
cls.add_method('SearchNextHop',
'ns3::Ipv4Address',
[param('ns3::Ipv4Address', 'ipv4Address')])
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRrepHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRrepHeader::SetNodeAddress(uint8_t index, ns3::Ipv4Address addr) [member function]
cls.add_method('SetNodeAddress',
'void',
[param('uint8_t', 'index'), param('ns3::Ipv4Address', 'addr')])
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRrepHeader::SetNodesAddress(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > ipv4Address) [member function]
cls.add_method('SetNodesAddress',
'void',
[param('std::vector< ns3::Ipv4Address >', 'ipv4Address')])
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRrepHeader::SetNumberAddress(uint8_t n) [member function]
cls.add_method('SetNumberAddress',
'void',
[param('uint8_t', 'n')])
return
def register_Ns3DsrDsrOptionRreqHeader_methods(root_module, cls):
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionRreqHeader::DsrOptionRreqHeader(ns3::dsr::DsrOptionRreqHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionRreqHeader const &', 'arg0')])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionRreqHeader::DsrOptionRreqHeader() [constructor]
cls.add_constructor([])
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRreqHeader::AddNodeAddress(ns3::Ipv4Address ipv4) [member function]
cls.add_method('AddNodeAddress',
'void',
[param('ns3::Ipv4Address', 'ipv4')])
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionRreqHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionHeader::Alignment ns3::dsr::DsrOptionRreqHeader::GetAlignment() const [member function]
cls.add_method('GetAlignment',
'ns3::dsr::DsrOptionHeader::Alignment',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionRreqHeader::GetDataLength() const [member function]
cls.add_method('GetDataLength',
'uint32_t',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): uint16_t ns3::dsr::DsrOptionRreqHeader::GetId() const [member function]
cls.add_method('GetId',
'uint16_t',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrOptionRreqHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrOptionRreqHeader::GetNodeAddress(uint8_t index) const [member function]
cls.add_method('GetNodeAddress',
'ns3::Ipv4Address',
[param('uint8_t', 'index')],
is_const=True)
## dsr-option-header.h (module 'dsr'): std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > ns3::dsr::DsrOptionRreqHeader::GetNodesAddresses() const [member function]
cls.add_method('GetNodesAddresses',
'std::vector< ns3::Ipv4Address >',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionRreqHeader::GetNodesNumber() const [member function]
cls.add_method('GetNodesNumber',
'uint32_t',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionRreqHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrOptionRreqHeader::GetTarget() [member function]
cls.add_method('GetTarget',
'ns3::Ipv4Address',
[])
## dsr-option-header.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionRreqHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRreqHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRreqHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRreqHeader::SetDataLength(uint32_t dataLength) [member function]
cls.add_method('SetDataLength',
'void',
[param('uint32_t', 'dataLength')])
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRreqHeader::SetId(uint16_t identification) [member function]
cls.add_method('SetId',
'void',
[param('uint16_t', 'identification')])
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRreqHeader::SetNodeAddress(uint8_t index, ns3::Ipv4Address addr) [member function]
cls.add_method('SetNodeAddress',
'void',
[param('uint8_t', 'index'), param('ns3::Ipv4Address', 'addr')])
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRreqHeader::SetNodesAddress(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > ipv4Address) [member function]
cls.add_method('SetNodesAddress',
'void',
[param('std::vector< ns3::Ipv4Address >', 'ipv4Address')])
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRreqHeader::SetNumberAddress(uint8_t n) [member function]
cls.add_method('SetNumberAddress',
'void',
[param('uint8_t', 'n')])
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionRreqHeader::SetTarget(ns3::Ipv4Address target) [member function]
cls.add_method('SetTarget',
'void',
[param('ns3::Ipv4Address', 'target')])
return
def register_Ns3DsrDsrOptionSRHeader_methods(root_module, cls):
cls.add_output_stream_operator()
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionSRHeader::DsrOptionSRHeader(ns3::dsr::DsrOptionSRHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionSRHeader const &', 'arg0')])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionSRHeader::DsrOptionSRHeader() [constructor]
cls.add_constructor([])
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionSRHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionHeader::Alignment ns3::dsr::DsrOptionSRHeader::GetAlignment() const [member function]
cls.add_method('GetAlignment',
'ns3::dsr::DsrOptionHeader::Alignment',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrOptionSRHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrOptionSRHeader::GetNodeAddress(uint8_t index) const [member function]
cls.add_method('GetNodeAddress',
'ns3::Ipv4Address',
[param('uint8_t', 'index')],
is_const=True)
## dsr-option-header.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionSRHeader::GetNodeListSize() const [member function]
cls.add_method('GetNodeListSize',
'uint8_t',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > ns3::dsr::DsrOptionSRHeader::GetNodesAddress() const [member function]
cls.add_method('GetNodesAddress',
'std::vector< ns3::Ipv4Address >',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionSRHeader::GetSalvage() const [member function]
cls.add_method('GetSalvage',
'uint8_t',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionSRHeader::GetSegmentsLeft() const [member function]
cls.add_method('GetSegmentsLeft',
'uint8_t',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionSRHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionSRHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionSRHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionSRHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionSRHeader::SetNodeAddress(uint8_t index, ns3::Ipv4Address addr) [member function]
cls.add_method('SetNodeAddress',
'void',
[param('uint8_t', 'index'), param('ns3::Ipv4Address', 'addr')])
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionSRHeader::SetNodesAddress(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > ipv4Address) [member function]
cls.add_method('SetNodesAddress',
'void',
[param('std::vector< ns3::Ipv4Address >', 'ipv4Address')])
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionSRHeader::SetNumberAddress(uint8_t n) [member function]
cls.add_method('SetNumberAddress',
'void',
[param('uint8_t', 'n')])
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionSRHeader::SetSalvage(uint8_t salvage) [member function]
cls.add_method('SetSalvage',
'void',
[param('uint8_t', 'salvage')])
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionSRHeader::SetSegmentsLeft(uint8_t segmentsLeft) [member function]
cls.add_method('SetSegmentsLeft',
'void',
[param('uint8_t', 'segmentsLeft')])
return
def register_Ns3DsrDsrOptions_methods(root_module, cls):
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptions::DsrOptions(ns3::dsr::DsrOptions const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptions const &', 'arg0')])
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptions::DsrOptions() [constructor]
cls.add_constructor([])
## dsr-options.h (module 'dsr'): bool ns3::dsr::DsrOptions::CheckDuplicates(ns3::Ipv4Address ipv4Address, std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > & vec) [member function]
cls.add_method('CheckDuplicates',
'bool',
[param('ns3::Ipv4Address', 'ipv4Address'), param('std::vector< ns3::Ipv4Address > &', 'vec')])
## dsr-options.h (module 'dsr'): bool ns3::dsr::DsrOptions::ContainAddressAfter(ns3::Ipv4Address ipv4Address, ns3::Ipv4Address destAddress, std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > & nodeList) [member function]
cls.add_method('ContainAddressAfter',
'bool',
[param('ns3::Ipv4Address', 'ipv4Address'), param('ns3::Ipv4Address', 'destAddress'), param('std::vector< ns3::Ipv4Address > &', 'nodeList')])
## dsr-options.h (module 'dsr'): std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > ns3::dsr::DsrOptions::CutRoute(ns3::Ipv4Address ipv4Address, std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > & nodeList) [member function]
cls.add_method('CutRoute',
'std::vector< ns3::Ipv4Address >',
[param('ns3::Ipv4Address', 'ipv4Address'), param('std::vector< ns3::Ipv4Address > &', 'nodeList')])
## dsr-options.h (module 'dsr'): uint32_t ns3::dsr::DsrOptions::GetIDfromIP(ns3::Ipv4Address address) [member function]
cls.add_method('GetIDfromIP',
'uint32_t',
[param('ns3::Ipv4Address', 'address')])
## dsr-options.h (module 'dsr'): ns3::Ptr<ns3::Node> ns3::dsr::DsrOptions::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True)
## dsr-options.h (module 'dsr'): ns3::Ptr<ns3::Node> ns3::dsr::DsrOptions::GetNodeWithAddress(ns3::Ipv4Address ipv4Address) [member function]
cls.add_method('GetNodeWithAddress',
'ns3::Ptr< ns3::Node >',
[param('ns3::Ipv4Address', 'ipv4Address')])
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptions::GetOptionNumber() const [member function]
cls.add_method('GetOptionNumber',
'uint8_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## dsr-options.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptions::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-options.h (module 'dsr'): bool ns3::dsr::DsrOptions::IfDuplicates(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > & vec, std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > & vec2) [member function]
cls.add_method('IfDuplicates',
'bool',
[param('std::vector< ns3::Ipv4Address > &', 'vec'), param('std::vector< ns3::Ipv4Address > &', 'vec2')])
## dsr-options.h (module 'dsr'): void ns3::dsr::DsrOptions::PrintVector(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > & vec) [member function]
cls.add_method('PrintVector',
'void',
[param('std::vector< ns3::Ipv4Address > &', 'vec')])
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptions::Process(ns3::Ptr<ns3::Packet> packet, ns3::Ptr<ns3::Packet> dsrP, ns3::Ipv4Address ipv4Address, ns3::Ipv4Address source, ns3::Ipv4Header const & ipv4Header, uint8_t protocol, bool & isPromisc) [member function]
cls.add_method('Process',
'uint8_t',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ptr< ns3::Packet >', 'dsrP'), param('ns3::Ipv4Address', 'ipv4Address'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Header const &', 'ipv4Header'), param('uint8_t', 'protocol'), param('bool &', 'isPromisc')],
is_pure_virtual=True, is_virtual=True)
## dsr-options.h (module 'dsr'): void ns3::dsr::DsrOptions::RemoveDuplicates(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > & vec) [member function]
cls.add_method('RemoveDuplicates',
'void',
[param('std::vector< ns3::Ipv4Address > &', 'vec')])
## dsr-options.h (module 'dsr'): bool ns3::dsr::DsrOptions::ReverseRoutes(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > & vec) [member function]
cls.add_method('ReverseRoutes',
'bool',
[param('std::vector< ns3::Ipv4Address > &', 'vec')])
## dsr-options.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrOptions::ReverseSearchNextHop(ns3::Ipv4Address ipv4Address, std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > & vec) [member function]
cls.add_method('ReverseSearchNextHop',
'ns3::Ipv4Address',
[param('ns3::Ipv4Address', 'ipv4Address'), param('std::vector< ns3::Ipv4Address > &', 'vec')])
## dsr-options.h (module 'dsr'): void ns3::dsr::DsrOptions::ScheduleReply(ns3::Ptr<ns3::Packet> & packet, std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > & nodeList, ns3::Ipv4Address & source, ns3::Ipv4Address & destination) [member function]
cls.add_method('ScheduleReply',
'void',
[param('ns3::Ptr< ns3::Packet > &', 'packet'), param('std::vector< ns3::Ipv4Address > &', 'nodeList'), param('ns3::Ipv4Address &', 'source'), param('ns3::Ipv4Address &', 'destination')])
## dsr-options.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrOptions::SearchNextHop(ns3::Ipv4Address ipv4Address, std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > & vec) [member function]
cls.add_method('SearchNextHop',
'ns3::Ipv4Address',
[param('ns3::Ipv4Address', 'ipv4Address'), param('std::vector< ns3::Ipv4Address > &', 'vec')])
## dsr-options.h (module 'dsr'): void ns3::dsr::DsrOptions::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## dsr-options.h (module 'dsr'): ns3::Ptr<ns3::Ipv4Route> ns3::dsr::DsrOptions::SetRoute(ns3::Ipv4Address nextHop, ns3::Ipv4Address srcAddress) [member function]
cls.add_method('SetRoute',
'ns3::Ptr< ns3::Ipv4Route >',
[param('ns3::Ipv4Address', 'nextHop'), param('ns3::Ipv4Address', 'srcAddress')],
is_virtual=True)
return
def register_Ns3DsrDsrRouting_methods(root_module, cls):
## dsr-routing.h (module 'dsr'): ns3::dsr::DsrRouting::DsrRouting(ns3::dsr::DsrRouting const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrRouting const &', 'arg0')])
## dsr-routing.h (module 'dsr'): ns3::dsr::DsrRouting::DsrRouting() [constructor]
cls.add_constructor([])
## dsr-routing.h (module 'dsr'): uint16_t ns3::dsr::DsrRouting::AddAckReqHeader(ns3::Ptr<ns3::Packet> & packet, ns3::Ipv4Address nextHop) [member function]
cls.add_method('AddAckReqHeader',
'uint16_t',
[param('ns3::Ptr< ns3::Packet > &', 'packet'), param('ns3::Ipv4Address', 'nextHop')])
## dsr-routing.h (module 'dsr'): bool ns3::dsr::DsrRouting::AddRoute(ns3::dsr::RouteCacheEntry & rt) [member function]
cls.add_method('AddRoute',
'bool',
[param('ns3::dsr::RouteCacheEntry &', 'rt')])
## dsr-routing.h (module 'dsr'): bool ns3::dsr::DsrRouting::AddRoute_Link(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > nodelist, ns3::Ipv4Address source) [member function]
cls.add_method('AddRoute_Link',
'bool',
[param('std::vector< ns3::Ipv4Address >', 'nodelist'), param('ns3::Ipv4Address', 'source')])
## dsr-routing.h (module 'dsr'): int64_t ns3::dsr::DsrRouting::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::CallCancelPacketTimer(uint16_t ackId, ns3::Ipv4Header const & ipv4Header, ns3::Ipv4Address realSrc, ns3::Ipv4Address realDst) [member function]
cls.add_method('CallCancelPacketTimer',
'void',
[param('uint16_t', 'ackId'), param('ns3::Ipv4Header const &', 'ipv4Header'), param('ns3::Ipv4Address', 'realSrc'), param('ns3::Ipv4Address', 'realDst')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::CancelNetworkPacketTimer(ns3::dsr::MaintainBuffEntry & mb) [member function]
cls.add_method('CancelNetworkPacketTimer',
'void',
[param('ns3::dsr::MaintainBuffEntry &', 'mb')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::CancelPacketTimerNextHop(ns3::Ipv4Address nextHop, uint8_t protocol) [member function]
cls.add_method('CancelPacketTimerNextHop',
'void',
[param('ns3::Ipv4Address', 'nextHop'), param('uint8_t', 'protocol')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::CancelPassivePacketTimer(ns3::dsr::MaintainBuffEntry & mb) [member function]
cls.add_method('CancelPassivePacketTimer',
'void',
[param('ns3::dsr::MaintainBuffEntry &', 'mb')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::CancelRreqTimer(ns3::Ipv4Address dst, bool isRemove) [member function]
cls.add_method('CancelRreqTimer',
'void',
[param('ns3::Ipv4Address', 'dst'), param('bool', 'isRemove')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::CheckSendBuffer() [member function]
cls.add_method('CheckSendBuffer',
'void',
[])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::DeleteAllRoutesIncludeLink(ns3::Ipv4Address errorSrc, ns3::Ipv4Address unreachNode, ns3::Ipv4Address node) [member function]
cls.add_method('DeleteAllRoutesIncludeLink',
'void',
[param('ns3::Ipv4Address', 'errorSrc'), param('ns3::Ipv4Address', 'unreachNode'), param('ns3::Ipv4Address', 'node')])
## dsr-routing.h (module 'dsr'): bool ns3::dsr::DsrRouting::FindSamePackets(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t segsLeft) [member function]
cls.add_method('FindSamePackets',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'segsLeft')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::ForwardErrPacket(ns3::dsr::DsrOptionRerrUnreachHeader & rerr, ns3::dsr::DsrOptionSRHeader & sourceRoute, ns3::Ipv4Address nextHop, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('ForwardErrPacket',
'void',
[param('ns3::dsr::DsrOptionRerrUnreachHeader &', 'rerr'), param('ns3::dsr::DsrOptionSRHeader &', 'sourceRoute'), param('ns3::Ipv4Address', 'nextHop'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::ForwardPacket(ns3::Ptr<ns3::Packet const> packet, ns3::dsr::DsrOptionSRHeader & sourceRoute, ns3::Ipv4Header const & ipv4Header, ns3::Ipv4Address source, ns3::Ipv4Address destination, ns3::Ipv4Address targetAddress, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('ForwardPacket',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::dsr::DsrOptionSRHeader &', 'sourceRoute'), param('ns3::Ipv4Header const &', 'ipv4Header'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('ns3::Ipv4Address', 'targetAddress'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')])
## dsr-routing.h (module 'dsr'): 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::dsr::DsrRouting::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_const=True, is_virtual=True)
## dsr-routing.h (module 'dsr'): 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::dsr::DsrRouting::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_const=True, is_virtual=True)
## dsr-routing.h (module 'dsr'): uint8_t ns3::dsr::DsrRouting::GetExtensionNumber() const [member function]
cls.add_method('GetExtensionNumber',
'uint8_t',
[],
is_const=True)
## dsr-routing.h (module 'dsr'): uint16_t ns3::dsr::DsrRouting::GetIDfromIP(ns3::Ipv4Address address) [member function]
cls.add_method('GetIDfromIP',
'uint16_t',
[param('ns3::Ipv4Address', 'address')])
## dsr-routing.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrRouting::GetIPfromID(uint16_t id) [member function]
cls.add_method('GetIPfromID',
'ns3::Ipv4Address',
[param('uint16_t', 'id')])
## dsr-routing.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrRouting::GetIPfromMAC(ns3::Mac48Address address) [member function]
cls.add_method('GetIPfromMAC',
'ns3::Ipv4Address',
[param('ns3::Mac48Address', 'address')])
## dsr-routing.h (module 'dsr'): ns3::Ptr<ns3::Node> ns3::dsr::DsrRouting::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True)
## dsr-routing.h (module 'dsr'): ns3::Ptr<ns3::Node> ns3::dsr::DsrRouting::GetNodeWithAddress(ns3::Ipv4Address ipv4Address) [member function]
cls.add_method('GetNodeWithAddress',
'ns3::Ptr< ns3::Node >',
[param('ns3::Ipv4Address', 'ipv4Address')])
## dsr-routing.h (module 'dsr'): ns3::Ptr<ns3::dsr::DsrOptions> ns3::dsr::DsrRouting::GetOption(int optionNumber) [member function]
cls.add_method('GetOption',
'ns3::Ptr< ns3::dsr::DsrOptions >',
[param('int', 'optionNumber')])
## dsr-routing.h (module 'dsr'): uint32_t ns3::dsr::DsrRouting::GetPriority(ns3::dsr::DsrMessageType messageType) [member function]
cls.add_method('GetPriority',
'uint32_t',
[param('ns3::dsr::DsrMessageType', 'messageType')])
## dsr-routing.h (module 'dsr'): int ns3::dsr::DsrRouting::GetProtocolNumber() const [member function]
cls.add_method('GetProtocolNumber',
'int',
[],
is_const=True, is_virtual=True)
## dsr-routing.h (module 'dsr'): ns3::Ptr<ns3::dsr::RreqTable> ns3::dsr::DsrRouting::GetRequestTable() const [member function]
cls.add_method('GetRequestTable',
'ns3::Ptr< ns3::dsr::RreqTable >',
[],
is_const=True)
## dsr-routing.h (module 'dsr'): ns3::Ptr<ns3::dsr::RouteCache> ns3::dsr::DsrRouting::GetRouteCache() const [member function]
cls.add_method('GetRouteCache',
'ns3::Ptr< ns3::dsr::RouteCache >',
[],
is_const=True)
## dsr-routing.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrRouting::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::IncreaseRetransTimer() [member function]
cls.add_method('IncreaseRetransTimer',
'void',
[])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::Insert(ns3::Ptr<ns3::dsr::DsrOptions> option) [member function]
cls.add_method('Insert',
'void',
[param('ns3::Ptr< ns3::dsr::DsrOptions >', 'option')])
## dsr-routing.h (module 'dsr'): bool ns3::dsr::DsrRouting::IsLinkCache() [member function]
cls.add_method('IsLinkCache',
'bool',
[])
## dsr-routing.h (module 'dsr'): bool ns3::dsr::DsrRouting::LookupRoute(ns3::Ipv4Address id, ns3::dsr::RouteCacheEntry & rt) [member function]
cls.add_method('LookupRoute',
'bool',
[param('ns3::Ipv4Address', 'id'), param('ns3::dsr::RouteCacheEntry &', 'rt')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::NetworkScheduleTimerExpire(ns3::dsr::MaintainBuffEntry & mb, uint8_t protocol) [member function]
cls.add_method('NetworkScheduleTimerExpire',
'void',
[param('ns3::dsr::MaintainBuffEntry &', 'mb'), param('uint8_t', 'protocol')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::PacketNewRoute(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol) [member function]
cls.add_method('PacketNewRoute',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::PassiveScheduleTimerExpire(ns3::dsr::MaintainBuffEntry & mb, bool onlyPassive, uint8_t protocol) [member function]
cls.add_method('PassiveScheduleTimerExpire',
'void',
[param('ns3::dsr::MaintainBuffEntry &', 'mb'), param('bool', 'onlyPassive'), param('uint8_t', 'protocol')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::PrintVector(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > & vec) [member function]
cls.add_method('PrintVector',
'void',
[param('std::vector< ns3::Ipv4Address > &', 'vec')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::PriorityScheduler(uint32_t priority, bool continueWithFirst) [member function]
cls.add_method('PriorityScheduler',
'void',
[param('uint32_t', 'priority'), param('bool', 'continueWithFirst')])
## dsr-routing.h (module 'dsr'): uint8_t ns3::dsr::DsrRouting::Process(ns3::Ptr<ns3::Packet> & packet, ns3::Ipv4Header const & ipv4Header, ns3::Ipv4Address dst, uint8_t * nextHeader, uint8_t protocol, bool & isDropped) [member function]
cls.add_method('Process',
'uint8_t',
[param('ns3::Ptr< ns3::Packet > &', 'packet'), param('ns3::Ipv4Header const &', 'ipv4Header'), param('ns3::Ipv4Address', 'dst'), param('uint8_t *', 'nextHeader'), param('uint8_t', 'protocol'), param('bool &', 'isDropped')])
## dsr-routing.h (module 'dsr'): ns3::IpL4Protocol::RxStatus ns3::dsr::DsrRouting::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_virtual=True)
## dsr-routing.h (module 'dsr'): ns3::IpL4Protocol::RxStatus ns3::dsr::DsrRouting::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_virtual=True)
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::RouteRequestTimerExpire(ns3::Ptr<ns3::Packet> packet, std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > address, uint32_t requestId, uint8_t protocol) [member function]
cls.add_method('RouteRequestTimerExpire',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('std::vector< ns3::Ipv4Address >', 'address'), param('uint32_t', 'requestId'), param('uint8_t', 'protocol')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::SalvagePacket(ns3::Ptr<ns3::Packet const> packet, ns3::Ipv4Address source, ns3::Ipv4Address dst, uint8_t protocol) [member function]
cls.add_method('SalvagePacket',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'dst'), param('uint8_t', 'protocol')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::ScheduleCachedReply(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, ns3::Ptr<ns3::Ipv4Route> route, double hops) [member function]
cls.add_method('ScheduleCachedReply',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('ns3::Ptr< ns3::Ipv4Route >', 'route'), param('double', 'hops')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::ScheduleInitialReply(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address nextHop, ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('ScheduleInitialReply',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'nextHop'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::ScheduleInterRequest(ns3::Ptr<ns3::Packet> packet) [member function]
cls.add_method('ScheduleInterRequest',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::ScheduleNetworkPacketRetry(ns3::dsr::MaintainBuffEntry & mb, bool isFirst, uint8_t protocol) [member function]
cls.add_method('ScheduleNetworkPacketRetry',
'void',
[param('ns3::dsr::MaintainBuffEntry &', 'mb'), param('bool', 'isFirst'), param('uint8_t', 'protocol')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::SchedulePassivePacketRetry(ns3::dsr::MaintainBuffEntry & mb, bool onlyPassive, uint8_t protocol) [member function]
cls.add_method('SchedulePassivePacketRetry',
'void',
[param('ns3::dsr::MaintainBuffEntry &', 'mb'), param('bool', 'onlyPassive'), param('uint8_t', 'protocol')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::ScheduleRreqRetry(ns3::Ptr<ns3::Packet> packet, std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > address, bool nonProp, uint32_t requestId, uint8_t protocol) [member function]
cls.add_method('ScheduleRreqRetry',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('std::vector< ns3::Ipv4Address >', 'address'), param('bool', 'nonProp'), param('uint32_t', 'requestId'), param('uint8_t', 'protocol')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::Scheduler(uint32_t priority) [member function]
cls.add_method('Scheduler',
'void',
[param('uint32_t', 'priority')])
## dsr-routing.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrRouting::SearchNextHop(ns3::Ipv4Address ipv4Address, std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > & vec) [member function]
cls.add_method('SearchNextHop',
'ns3::Ipv4Address',
[param('ns3::Ipv4Address', 'ipv4Address'), param('std::vector< ns3::Ipv4Address > &', 'vec')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::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')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::SendAck(uint16_t ackId, ns3::Ipv4Address destination, ns3::Ipv4Address realSrc, ns3::Ipv4Address realDst, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('SendAck',
'void',
[param('uint16_t', 'ackId'), param('ns3::Ipv4Address', 'destination'), param('ns3::Ipv4Address', 'realSrc'), param('ns3::Ipv4Address', 'realDst'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::SendBuffTimerExpire() [member function]
cls.add_method('SendBuffTimerExpire',
'void',
[])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::SendErrorRequest(ns3::dsr::DsrOptionRerrUnreachHeader & rerr, uint8_t protocol) [member function]
cls.add_method('SendErrorRequest',
'void',
[param('ns3::dsr::DsrOptionRerrUnreachHeader &', 'rerr'), param('uint8_t', 'protocol')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::SendGratuitousReply(ns3::Ipv4Address replyTo, ns3::Ipv4Address replyFrom, std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > & nodeList, uint8_t protocol) [member function]
cls.add_method('SendGratuitousReply',
'void',
[param('ns3::Ipv4Address', 'replyTo'), param('ns3::Ipv4Address', 'replyFrom'), param('std::vector< ns3::Ipv4Address > &', 'nodeList'), param('uint8_t', 'protocol')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::SendInitialRequest(ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol) [member function]
cls.add_method('SendInitialRequest',
'void',
[param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::SendPacket(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address nextHop, uint8_t protocol) [member function]
cls.add_method('SendPacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'nextHop'), param('uint8_t', 'protocol')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::SendPacketFromBuffer(ns3::dsr::DsrOptionSRHeader const & sourceRoute, ns3::Ipv4Address nextHop, uint8_t protocol) [member function]
cls.add_method('SendPacketFromBuffer',
'void',
[param('ns3::dsr::DsrOptionSRHeader const &', 'sourceRoute'), param('ns3::Ipv4Address', 'nextHop'), param('uint8_t', 'protocol')])
## dsr-routing.h (module 'dsr'): bool ns3::dsr::DsrRouting::SendRealDown(ns3::dsr::DsrNetworkQueueEntry & newEntry) [member function]
cls.add_method('SendRealDown',
'bool',
[param('ns3::dsr::DsrNetworkQueueEntry &', 'newEntry')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::SendReply(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address nextHop, ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('SendReply',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'nextHop'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::SendRequest(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source) [member function]
cls.add_method('SendRequest',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::SendRequestAndIncrement(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination) [member function]
cls.add_method('SendRequestAndIncrement',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::SendUnreachError(ns3::Ipv4Address errorHop, ns3::Ipv4Address destination, ns3::Ipv4Address originalDst, uint8_t salvage, uint8_t protocol) [member function]
cls.add_method('SendUnreachError',
'void',
[param('ns3::Ipv4Address', 'errorHop'), param('ns3::Ipv4Address', 'destination'), param('ns3::Ipv4Address', 'originalDst'), param('uint8_t', 'salvage'), param('uint8_t', 'protocol')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::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> callback) [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 >', 'callback')],
is_virtual=True)
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::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> callback) [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 >', 'callback')],
is_virtual=True)
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::SetRequestTable(ns3::Ptr<ns3::dsr::RreqTable> r) [member function]
cls.add_method('SetRequestTable',
'void',
[param('ns3::Ptr< ns3::dsr::RreqTable >', 'r')])
## dsr-routing.h (module 'dsr'): ns3::Ptr<ns3::Ipv4Route> ns3::dsr::DsrRouting::SetRoute(ns3::Ipv4Address nextHop, ns3::Ipv4Address srcAddress) [member function]
cls.add_method('SetRoute',
'ns3::Ptr< ns3::Ipv4Route >',
[param('ns3::Ipv4Address', 'nextHop'), param('ns3::Ipv4Address', 'srcAddress')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::SetRouteCache(ns3::Ptr<ns3::dsr::RouteCache> r) [member function]
cls.add_method('SetRouteCache',
'void',
[param('ns3::Ptr< ns3::dsr::RouteCache >', 'r')])
## dsr-routing.h (module 'dsr'): bool ns3::dsr::DsrRouting::UpdateRouteEntry(ns3::Ipv4Address dst) [member function]
cls.add_method('UpdateRouteEntry',
'bool',
[param('ns3::Ipv4Address', 'dst')])
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::UseExtends(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > rt) [member function]
cls.add_method('UseExtends',
'void',
[param('std::vector< ns3::Ipv4Address >', 'rt')])
## dsr-routing.h (module 'dsr'): ns3::dsr::DsrRouting::PROT_NUMBER [variable]
cls.add_static_attribute('PROT_NUMBER', 'uint8_t const', is_const=True)
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## dsr-routing.h (module 'dsr'): void ns3::dsr::DsrRouting::NotifyNewAggregate() [member function]
cls.add_method('NotifyNewAggregate',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3DsrDsrRoutingHeader_methods(root_module, cls):
cls.add_output_stream_operator()
## dsr-fs-header.h (module 'dsr'): ns3::dsr::DsrRoutingHeader::DsrRoutingHeader(ns3::dsr::DsrRoutingHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrRoutingHeader const &', 'arg0')])
## dsr-fs-header.h (module 'dsr'): ns3::dsr::DsrRoutingHeader::DsrRoutingHeader() [constructor]
cls.add_constructor([])
## dsr-fs-header.h (module 'dsr'): uint32_t ns3::dsr::DsrRoutingHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## dsr-fs-header.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrRoutingHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-fs-header.h (module 'dsr'): uint32_t ns3::dsr::DsrRoutingHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dsr-fs-header.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrRoutingHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-fs-header.h (module 'dsr'): void ns3::dsr::DsrRoutingHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## dsr-fs-header.h (module 'dsr'): void ns3::dsr::DsrRoutingHeader::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_Ns3DsrErrorBuffEntry_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
## dsr-errorbuff.h (module 'dsr'): ns3::dsr::ErrorBuffEntry::ErrorBuffEntry(ns3::dsr::ErrorBuffEntry const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::ErrorBuffEntry const &', 'arg0')])
## dsr-errorbuff.h (module 'dsr'): ns3::dsr::ErrorBuffEntry::ErrorBuffEntry(ns3::Ptr<ns3::Packet const> pa=0, ns3::Ipv4Address d=ns3::Ipv4Address(), ns3::Ipv4Address s=ns3::Ipv4Address(), ns3::Ipv4Address n=ns3::Ipv4Address(), ns3::Time exp=ns3::Simulator::Now( ), uint8_t p=0) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Packet const >', 'pa', default_value='0'), param('ns3::Ipv4Address', 'd', default_value='ns3::Ipv4Address()'), param('ns3::Ipv4Address', 's', default_value='ns3::Ipv4Address()'), param('ns3::Ipv4Address', 'n', default_value='ns3::Ipv4Address()'), param('ns3::Time', 'exp', default_value='ns3::Simulator::Now( )'), param('uint8_t', 'p', default_value='0')])
## dsr-errorbuff.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::ErrorBuffEntry::GetDestination() const [member function]
cls.add_method('GetDestination',
'ns3::Ipv4Address',
[],
is_const=True)
## dsr-errorbuff.h (module 'dsr'): ns3::Time ns3::dsr::ErrorBuffEntry::GetExpireTime() const [member function]
cls.add_method('GetExpireTime',
'ns3::Time',
[],
is_const=True)
## dsr-errorbuff.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::ErrorBuffEntry::GetNextHop() const [member function]
cls.add_method('GetNextHop',
'ns3::Ipv4Address',
[],
is_const=True)
## dsr-errorbuff.h (module 'dsr'): ns3::Ptr<ns3::Packet const> ns3::dsr::ErrorBuffEntry::GetPacket() const [member function]
cls.add_method('GetPacket',
'ns3::Ptr< ns3::Packet const >',
[],
is_const=True)
## dsr-errorbuff.h (module 'dsr'): uint8_t ns3::dsr::ErrorBuffEntry::GetProtocol() const [member function]
cls.add_method('GetProtocol',
'uint8_t',
[],
is_const=True)
## dsr-errorbuff.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::ErrorBuffEntry::GetSource() const [member function]
cls.add_method('GetSource',
'ns3::Ipv4Address',
[],
is_const=True)
## dsr-errorbuff.h (module 'dsr'): void ns3::dsr::ErrorBuffEntry::SetDestination(ns3::Ipv4Address d) [member function]
cls.add_method('SetDestination',
'void',
[param('ns3::Ipv4Address', 'd')])
## dsr-errorbuff.h (module 'dsr'): void ns3::dsr::ErrorBuffEntry::SetExpireTime(ns3::Time exp) [member function]
cls.add_method('SetExpireTime',
'void',
[param('ns3::Time', 'exp')])
## dsr-errorbuff.h (module 'dsr'): void ns3::dsr::ErrorBuffEntry::SetNextHop(ns3::Ipv4Address n) [member function]
cls.add_method('SetNextHop',
'void',
[param('ns3::Ipv4Address', 'n')])
## dsr-errorbuff.h (module 'dsr'): void ns3::dsr::ErrorBuffEntry::SetPacket(ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('SetPacket',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'p')])
## dsr-errorbuff.h (module 'dsr'): void ns3::dsr::ErrorBuffEntry::SetProtocol(uint8_t p) [member function]
cls.add_method('SetProtocol',
'void',
[param('uint8_t', 'p')])
## dsr-errorbuff.h (module 'dsr'): void ns3::dsr::ErrorBuffEntry::SetSource(ns3::Ipv4Address s) [member function]
cls.add_method('SetSource',
'void',
[param('ns3::Ipv4Address', 's')])
return
def register_Ns3DsrErrorBuffer_methods(root_module, cls):
## dsr-errorbuff.h (module 'dsr'): ns3::dsr::ErrorBuffer::ErrorBuffer(ns3::dsr::ErrorBuffer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::ErrorBuffer const &', 'arg0')])
## dsr-errorbuff.h (module 'dsr'): ns3::dsr::ErrorBuffer::ErrorBuffer() [constructor]
cls.add_constructor([])
## dsr-errorbuff.h (module 'dsr'): bool ns3::dsr::ErrorBuffer::Dequeue(ns3::Ipv4Address dst, ns3::dsr::ErrorBuffEntry & entry) [member function]
cls.add_method('Dequeue',
'bool',
[param('ns3::Ipv4Address', 'dst'), param('ns3::dsr::ErrorBuffEntry &', 'entry')])
## dsr-errorbuff.h (module 'dsr'): void ns3::dsr::ErrorBuffer::DropPacketForErrLink(ns3::Ipv4Address source, ns3::Ipv4Address nextHop) [member function]
cls.add_method('DropPacketForErrLink',
'void',
[param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'nextHop')])
## dsr-errorbuff.h (module 'dsr'): bool ns3::dsr::ErrorBuffer::Enqueue(ns3::dsr::ErrorBuffEntry & entry) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::dsr::ErrorBuffEntry &', 'entry')])
## dsr-errorbuff.h (module 'dsr'): bool ns3::dsr::ErrorBuffer::Find(ns3::Ipv4Address dst) [member function]
cls.add_method('Find',
'bool',
[param('ns3::Ipv4Address', 'dst')])
## dsr-errorbuff.h (module 'dsr'): std::vector<ns3::dsr::ErrorBuffEntry, std::allocator<ns3::dsr::ErrorBuffEntry> > & ns3::dsr::ErrorBuffer::GetBuffer() [member function]
cls.add_method('GetBuffer',
'std::vector< ns3::dsr::ErrorBuffEntry > &',
[])
## dsr-errorbuff.h (module 'dsr'): ns3::Time ns3::dsr::ErrorBuffer::GetErrorBufferTimeout() const [member function]
cls.add_method('GetErrorBufferTimeout',
'ns3::Time',
[],
is_const=True)
## dsr-errorbuff.h (module 'dsr'): uint32_t ns3::dsr::ErrorBuffer::GetMaxQueueLen() const [member function]
cls.add_method('GetMaxQueueLen',
'uint32_t',
[],
is_const=True)
## dsr-errorbuff.h (module 'dsr'): uint32_t ns3::dsr::ErrorBuffer::GetSize() [member function]
cls.add_method('GetSize',
'uint32_t',
[])
## dsr-errorbuff.h (module 'dsr'): void ns3::dsr::ErrorBuffer::SetErrorBufferTimeout(ns3::Time t) [member function]
cls.add_method('SetErrorBufferTimeout',
'void',
[param('ns3::Time', 't')])
## dsr-errorbuff.h (module 'dsr'): void ns3::dsr::ErrorBuffer::SetMaxQueueLen(uint32_t len) [member function]
cls.add_method('SetMaxQueueLen',
'void',
[param('uint32_t', 'len')])
return
def register_Ns3DsrGraReply_methods(root_module, cls):
## dsr-gratuitous-reply-table.h (module 'dsr'): ns3::dsr::GraReply::GraReply(ns3::dsr::GraReply const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::GraReply const &', 'arg0')])
## dsr-gratuitous-reply-table.h (module 'dsr'): ns3::dsr::GraReply::GraReply() [constructor]
cls.add_constructor([])
## dsr-gratuitous-reply-table.h (module 'dsr'): bool ns3::dsr::GraReply::AddEntry(ns3::dsr::GraReplyEntry & graTableEntry) [member function]
cls.add_method('AddEntry',
'bool',
[param('ns3::dsr::GraReplyEntry &', 'graTableEntry')])
## dsr-gratuitous-reply-table.h (module 'dsr'): void ns3::dsr::GraReply::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## dsr-gratuitous-reply-table.h (module 'dsr'): bool ns3::dsr::GraReply::FindAndUpdate(ns3::Ipv4Address replyTo, ns3::Ipv4Address replyFrom, ns3::Time gratReplyHoldoff) [member function]
cls.add_method('FindAndUpdate',
'bool',
[param('ns3::Ipv4Address', 'replyTo'), param('ns3::Ipv4Address', 'replyFrom'), param('ns3::Time', 'gratReplyHoldoff')])
## dsr-gratuitous-reply-table.h (module 'dsr'): uint32_t ns3::dsr::GraReply::GetGraTableSize() const [member function]
cls.add_method('GetGraTableSize',
'uint32_t',
[],
is_const=True)
## dsr-gratuitous-reply-table.h (module 'dsr'): static ns3::TypeId ns3::dsr::GraReply::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-gratuitous-reply-table.h (module 'dsr'): void ns3::dsr::GraReply::Purge() [member function]
cls.add_method('Purge',
'void',
[])
## dsr-gratuitous-reply-table.h (module 'dsr'): void ns3::dsr::GraReply::SetGraTableSize(uint32_t g) [member function]
cls.add_method('SetGraTableSize',
'void',
[param('uint32_t', 'g')])
return
def register_Ns3DsrGraReplyEntry_methods(root_module, cls):
## dsr-gratuitous-reply-table.h (module 'dsr'): ns3::dsr::GraReplyEntry::GraReplyEntry(ns3::dsr::GraReplyEntry const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::GraReplyEntry const &', 'arg0')])
## dsr-gratuitous-reply-table.h (module 'dsr'): ns3::dsr::GraReplyEntry::GraReplyEntry(ns3::Ipv4Address t, ns3::Ipv4Address f, ns3::Time h) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 't'), param('ns3::Ipv4Address', 'f'), param('ns3::Time', 'h')])
## dsr-gratuitous-reply-table.h (module 'dsr'): ns3::dsr::GraReplyEntry::m_gratReplyHoldoff [variable]
cls.add_instance_attribute('m_gratReplyHoldoff', 'ns3::Time', is_const=False)
## dsr-gratuitous-reply-table.h (module 'dsr'): ns3::dsr::GraReplyEntry::m_hearFrom [variable]
cls.add_instance_attribute('m_hearFrom', 'ns3::Ipv4Address', is_const=False)
## dsr-gratuitous-reply-table.h (module 'dsr'): ns3::dsr::GraReplyEntry::m_replyTo [variable]
cls.add_instance_attribute('m_replyTo', 'ns3::Ipv4Address', is_const=False)
return
def register_Ns3DsrLink_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
## dsr-rcache.h (module 'dsr'): ns3::dsr::Link::Link(ns3::dsr::Link const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::Link const &', 'arg0')])
## dsr-rcache.h (module 'dsr'): ns3::dsr::Link::Link(ns3::Ipv4Address ip1, ns3::Ipv4Address ip2) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'ip1'), param('ns3::Ipv4Address', 'ip2')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::Link::Print() const [member function]
cls.add_method('Print',
'void',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): ns3::dsr::Link::m_high [variable]
cls.add_instance_attribute('m_high', 'ns3::Ipv4Address', is_const=False)
## dsr-rcache.h (module 'dsr'): ns3::dsr::Link::m_low [variable]
cls.add_instance_attribute('m_low', 'ns3::Ipv4Address', is_const=False)
return
def register_Ns3DsrLinkStab_methods(root_module, cls):
## dsr-rcache.h (module 'dsr'): ns3::dsr::LinkStab::LinkStab(ns3::dsr::LinkStab const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::LinkStab const &', 'arg0')])
## dsr-rcache.h (module 'dsr'): ns3::dsr::LinkStab::LinkStab(ns3::Time linkStab=ns3::Simulator::Now( )) [constructor]
cls.add_constructor([param('ns3::Time', 'linkStab', default_value='ns3::Simulator::Now( )')])
## dsr-rcache.h (module 'dsr'): ns3::Time ns3::dsr::LinkStab::GetLinkStability() const [member function]
cls.add_method('GetLinkStability',
'ns3::Time',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): void ns3::dsr::LinkStab::Print() const [member function]
cls.add_method('Print',
'void',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): void ns3::dsr::LinkStab::SetLinkStability(ns3::Time linkStab) [member function]
cls.add_method('SetLinkStability',
'void',
[param('ns3::Time', 'linkStab')])
return
def register_Ns3DsrMaintainBuffEntry_methods(root_module, cls):
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::MaintainBuffEntry::MaintainBuffEntry(ns3::dsr::MaintainBuffEntry const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::MaintainBuffEntry const &', 'arg0')])
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::MaintainBuffEntry::MaintainBuffEntry(ns3::Ptr<ns3::Packet const> pa=0, ns3::Ipv4Address us=ns3::Ipv4Address(), ns3::Ipv4Address n=ns3::Ipv4Address(), ns3::Ipv4Address s=ns3::Ipv4Address(), ns3::Ipv4Address dst=ns3::Ipv4Address(), uint16_t ackId=0, uint8_t segs=0, ns3::Time exp=ns3::Simulator::Now( )) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Packet const >', 'pa', default_value='0'), param('ns3::Ipv4Address', 'us', default_value='ns3::Ipv4Address()'), param('ns3::Ipv4Address', 'n', default_value='ns3::Ipv4Address()'), param('ns3::Ipv4Address', 's', default_value='ns3::Ipv4Address()'), param('ns3::Ipv4Address', 'dst', default_value='ns3::Ipv4Address()'), param('uint16_t', 'ackId', default_value='0'), param('uint8_t', 'segs', default_value='0'), param('ns3::Time', 'exp', default_value='ns3::Simulator::Now( )')])
## dsr-maintain-buff.h (module 'dsr'): uint16_t ns3::dsr::MaintainBuffEntry::GetAckId() const [member function]
cls.add_method('GetAckId',
'uint16_t',
[],
is_const=True)
## dsr-maintain-buff.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::MaintainBuffEntry::GetDst() const [member function]
cls.add_method('GetDst',
'ns3::Ipv4Address',
[],
is_const=True)
## dsr-maintain-buff.h (module 'dsr'): ns3::Time ns3::dsr::MaintainBuffEntry::GetExpireTime() const [member function]
cls.add_method('GetExpireTime',
'ns3::Time',
[],
is_const=True)
## dsr-maintain-buff.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::MaintainBuffEntry::GetNextHop() const [member function]
cls.add_method('GetNextHop',
'ns3::Ipv4Address',
[],
is_const=True)
## dsr-maintain-buff.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::MaintainBuffEntry::GetOurAdd() const [member function]
cls.add_method('GetOurAdd',
'ns3::Ipv4Address',
[],
is_const=True)
## dsr-maintain-buff.h (module 'dsr'): ns3::Ptr<ns3::Packet const> ns3::dsr::MaintainBuffEntry::GetPacket() const [member function]
cls.add_method('GetPacket',
'ns3::Ptr< ns3::Packet const >',
[],
is_const=True)
## dsr-maintain-buff.h (module 'dsr'): uint8_t ns3::dsr::MaintainBuffEntry::GetSegsLeft() const [member function]
cls.add_method('GetSegsLeft',
'uint8_t',
[],
is_const=True)
## dsr-maintain-buff.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::MaintainBuffEntry::GetSrc() const [member function]
cls.add_method('GetSrc',
'ns3::Ipv4Address',
[],
is_const=True)
## dsr-maintain-buff.h (module 'dsr'): void ns3::dsr::MaintainBuffEntry::SetAckId(uint16_t ackId) [member function]
cls.add_method('SetAckId',
'void',
[param('uint16_t', 'ackId')])
## dsr-maintain-buff.h (module 'dsr'): void ns3::dsr::MaintainBuffEntry::SetDst(ns3::Ipv4Address n) [member function]
cls.add_method('SetDst',
'void',
[param('ns3::Ipv4Address', 'n')])
## dsr-maintain-buff.h (module 'dsr'): void ns3::dsr::MaintainBuffEntry::SetExpireTime(ns3::Time exp) [member function]
cls.add_method('SetExpireTime',
'void',
[param('ns3::Time', 'exp')])
## dsr-maintain-buff.h (module 'dsr'): void ns3::dsr::MaintainBuffEntry::SetNextHop(ns3::Ipv4Address n) [member function]
cls.add_method('SetNextHop',
'void',
[param('ns3::Ipv4Address', 'n')])
## dsr-maintain-buff.h (module 'dsr'): void ns3::dsr::MaintainBuffEntry::SetOurAdd(ns3::Ipv4Address us) [member function]
cls.add_method('SetOurAdd',
'void',
[param('ns3::Ipv4Address', 'us')])
## dsr-maintain-buff.h (module 'dsr'): void ns3::dsr::MaintainBuffEntry::SetPacket(ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('SetPacket',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'p')])
## dsr-maintain-buff.h (module 'dsr'): void ns3::dsr::MaintainBuffEntry::SetSegsLeft(uint8_t segs) [member function]
cls.add_method('SetSegsLeft',
'void',
[param('uint8_t', 'segs')])
## dsr-maintain-buff.h (module 'dsr'): void ns3::dsr::MaintainBuffEntry::SetSrc(ns3::Ipv4Address s) [member function]
cls.add_method('SetSrc',
'void',
[param('ns3::Ipv4Address', 's')])
return
def register_Ns3DsrMaintainBuffer_methods(root_module, cls):
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::MaintainBuffer::MaintainBuffer(ns3::dsr::MaintainBuffer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::MaintainBuffer const &', 'arg0')])
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::MaintainBuffer::MaintainBuffer() [constructor]
cls.add_constructor([])
## dsr-maintain-buff.h (module 'dsr'): bool ns3::dsr::MaintainBuffer::AllEqual(ns3::dsr::MaintainBuffEntry & entry) [member function]
cls.add_method('AllEqual',
'bool',
[param('ns3::dsr::MaintainBuffEntry &', 'entry')])
## dsr-maintain-buff.h (module 'dsr'): bool ns3::dsr::MaintainBuffer::Dequeue(ns3::Ipv4Address dst, ns3::dsr::MaintainBuffEntry & entry) [member function]
cls.add_method('Dequeue',
'bool',
[param('ns3::Ipv4Address', 'dst'), param('ns3::dsr::MaintainBuffEntry &', 'entry')])
## dsr-maintain-buff.h (module 'dsr'): void ns3::dsr::MaintainBuffer::DropPacketWithNextHop(ns3::Ipv4Address nextHop) [member function]
cls.add_method('DropPacketWithNextHop',
'void',
[param('ns3::Ipv4Address', 'nextHop')])
## dsr-maintain-buff.h (module 'dsr'): bool ns3::dsr::MaintainBuffer::Enqueue(ns3::dsr::MaintainBuffEntry & entry) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::dsr::MaintainBuffEntry &', 'entry')])
## dsr-maintain-buff.h (module 'dsr'): bool ns3::dsr::MaintainBuffer::Find(ns3::Ipv4Address nextHop) [member function]
cls.add_method('Find',
'bool',
[param('ns3::Ipv4Address', 'nextHop')])
## dsr-maintain-buff.h (module 'dsr'): bool ns3::dsr::MaintainBuffer::FindMaintainEntry(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address ourAdd, ns3::Ipv4Address src, ns3::Ipv4Address nextHop, ns3::Ipv4Address dst, ns3::dsr::NetworkKey networkKey) [member function]
cls.add_method('FindMaintainEntry',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'ourAdd'), param('ns3::Ipv4Address', 'src'), param('ns3::Ipv4Address', 'nextHop'), param('ns3::Ipv4Address', 'dst'), param('ns3::dsr::NetworkKey', 'networkKey')])
## dsr-maintain-buff.h (module 'dsr'): ns3::Time ns3::dsr::MaintainBuffer::GetMaintainBufferTimeout() const [member function]
cls.add_method('GetMaintainBufferTimeout',
'ns3::Time',
[],
is_const=True)
## dsr-maintain-buff.h (module 'dsr'): uint32_t ns3::dsr::MaintainBuffer::GetMaxQueueLen() const [member function]
cls.add_method('GetMaxQueueLen',
'uint32_t',
[],
is_const=True)
## dsr-maintain-buff.h (module 'dsr'): uint32_t ns3::dsr::MaintainBuffer::GetSize() [member function]
cls.add_method('GetSize',
'uint32_t',
[])
## dsr-maintain-buff.h (module 'dsr'): bool ns3::dsr::MaintainBuffer::NetworkEqual(ns3::dsr::MaintainBuffEntry & entry) [member function]
cls.add_method('NetworkEqual',
'bool',
[param('ns3::dsr::MaintainBuffEntry &', 'entry')])
## dsr-maintain-buff.h (module 'dsr'): bool ns3::dsr::MaintainBuffer::PromiscEqual(ns3::dsr::MaintainBuffEntry & entry) [member function]
cls.add_method('PromiscEqual',
'bool',
[param('ns3::dsr::MaintainBuffEntry &', 'entry')])
## dsr-maintain-buff.h (module 'dsr'): void ns3::dsr::MaintainBuffer::SetMaintainBufferTimeout(ns3::Time t) [member function]
cls.add_method('SetMaintainBufferTimeout',
'void',
[param('ns3::Time', 't')])
## dsr-maintain-buff.h (module 'dsr'): void ns3::dsr::MaintainBuffer::SetMaxQueueLen(uint32_t len) [member function]
cls.add_method('SetMaxQueueLen',
'void',
[param('uint32_t', 'len')])
return
def register_Ns3DsrNetworkKey_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::NetworkKey::NetworkKey() [constructor]
cls.add_constructor([])
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::NetworkKey::NetworkKey(ns3::dsr::NetworkKey const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::NetworkKey const &', 'arg0')])
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::NetworkKey::m_ackId [variable]
cls.add_instance_attribute('m_ackId', 'uint16_t', is_const=False)
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::NetworkKey::m_destination [variable]
cls.add_instance_attribute('m_destination', 'ns3::Ipv4Address', is_const=False)
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::NetworkKey::m_nextHop [variable]
cls.add_instance_attribute('m_nextHop', 'ns3::Ipv4Address', is_const=False)
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::NetworkKey::m_ourAdd [variable]
cls.add_instance_attribute('m_ourAdd', 'ns3::Ipv4Address', is_const=False)
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::NetworkKey::m_source [variable]
cls.add_instance_attribute('m_source', 'ns3::Ipv4Address', is_const=False)
return
def register_Ns3DsrNodeStab_methods(root_module, cls):
## dsr-rcache.h (module 'dsr'): ns3::dsr::NodeStab::NodeStab(ns3::dsr::NodeStab const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::NodeStab const &', 'arg0')])
## dsr-rcache.h (module 'dsr'): ns3::dsr::NodeStab::NodeStab(ns3::Time nodeStab=ns3::Simulator::Now( )) [constructor]
cls.add_constructor([param('ns3::Time', 'nodeStab', default_value='ns3::Simulator::Now( )')])
## dsr-rcache.h (module 'dsr'): ns3::Time ns3::dsr::NodeStab::GetNodeStability() const [member function]
cls.add_method('GetNodeStability',
'ns3::Time',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): void ns3::dsr::NodeStab::SetNodeStability(ns3::Time nodeStab) [member function]
cls.add_method('SetNodeStability',
'void',
[param('ns3::Time', 'nodeStab')])
return
def register_Ns3DsrPassiveKey_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::PassiveKey::PassiveKey() [constructor]
cls.add_constructor([])
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::PassiveKey::PassiveKey(ns3::dsr::PassiveKey const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::PassiveKey const &', 'arg0')])
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::PassiveKey::m_ackId [variable]
cls.add_instance_attribute('m_ackId', 'uint16_t', is_const=False)
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::PassiveKey::m_destination [variable]
cls.add_instance_attribute('m_destination', 'ns3::Ipv4Address', is_const=False)
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::PassiveKey::m_segsLeft [variable]
cls.add_instance_attribute('m_segsLeft', 'uint8_t', is_const=False)
## dsr-maintain-buff.h (module 'dsr'): ns3::dsr::PassiveKey::m_source [variable]
cls.add_instance_attribute('m_source', 'ns3::Ipv4Address', is_const=False)
return
def register_Ns3DsrRouteCache_methods(root_module, cls):
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCache::RouteCache(ns3::dsr::RouteCache const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::RouteCache const &', 'arg0')])
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCache::RouteCache() [constructor]
cls.add_constructor([])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::AddArpCache(ns3::Ptr<ns3::ArpCache> arg0) [member function]
cls.add_method('AddArpCache',
'void',
[param('ns3::Ptr< ns3::ArpCache >', 'arg0')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::AddNeighbor(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > nodeList, ns3::Ipv4Address ownAddress, ns3::Time expire) [member function]
cls.add_method('AddNeighbor',
'void',
[param('std::vector< ns3::Ipv4Address >', 'nodeList'), param('ns3::Ipv4Address', 'ownAddress'), param('ns3::Time', 'expire')])
## dsr-rcache.h (module 'dsr'): bool ns3::dsr::RouteCache::AddRoute(ns3::dsr::RouteCacheEntry & rt) [member function]
cls.add_method('AddRoute',
'bool',
[param('ns3::dsr::RouteCacheEntry &', 'rt')])
## dsr-rcache.h (module 'dsr'): bool ns3::dsr::RouteCache::AddRoute_Link(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > nodelist, ns3::Ipv4Address node) [member function]
cls.add_method('AddRoute_Link',
'bool',
[param('std::vector< ns3::Ipv4Address >', 'nodelist'), param('ns3::Ipv4Address', 'node')])
## dsr-rcache.h (module 'dsr'): uint16_t ns3::dsr::RouteCache::CheckUniqueAckId(ns3::Ipv4Address nextHop) [member function]
cls.add_method('CheckUniqueAckId',
'uint16_t',
[param('ns3::Ipv4Address', 'nextHop')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::ClearMac() [member function]
cls.add_method('ClearMac',
'void',
[])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::DelArpCache(ns3::Ptr<ns3::ArpCache> arg0) [member function]
cls.add_method('DelArpCache',
'void',
[param('ns3::Ptr< ns3::ArpCache >', 'arg0')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::DeleteAllRoutesIncludeLink(ns3::Ipv4Address errorSrc, ns3::Ipv4Address unreachNode, ns3::Ipv4Address node) [member function]
cls.add_method('DeleteAllRoutesIncludeLink',
'void',
[param('ns3::Ipv4Address', 'errorSrc'), param('ns3::Ipv4Address', 'unreachNode'), param('ns3::Ipv4Address', 'node')])
## dsr-rcache.h (module 'dsr'): bool ns3::dsr::RouteCache::DeleteRoute(ns3::Ipv4Address dst) [member function]
cls.add_method('DeleteRoute',
'bool',
[param('ns3::Ipv4Address', 'dst')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::DropPathWithDst(ns3::Ipv4Address dst) [member function]
cls.add_method('DropPathWithDst',
'void',
[param('ns3::Ipv4Address', 'dst')])
## dsr-rcache.h (module 'dsr'): bool ns3::dsr::RouteCache::FindSameRoute(ns3::dsr::RouteCacheEntry & rt, std::list<ns3::dsr::RouteCacheEntry, std::allocator<ns3::dsr::RouteCacheEntry> > & rtVector) [member function]
cls.add_method('FindSameRoute',
'bool',
[param('ns3::dsr::RouteCacheEntry &', 'rt'), param('std::list< ns3::dsr::RouteCacheEntry > &', 'rtVector')])
## dsr-rcache.h (module 'dsr'): uint16_t ns3::dsr::RouteCache::GetAckSize() [member function]
cls.add_method('GetAckSize',
'uint16_t',
[])
## dsr-rcache.h (module 'dsr'): ns3::Time ns3::dsr::RouteCache::GetBadLinkLifetime() const [member function]
cls.add_method('GetBadLinkLifetime',
'ns3::Time',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): ns3::Time ns3::dsr::RouteCache::GetCacheTimeout() const [member function]
cls.add_method('GetCacheTimeout',
'ns3::Time',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): ns3::Callback<void, ns3::Ipv4Address, unsigned char, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::dsr::RouteCache::GetCallback() const [member function]
cls.add_method('GetCallback',
'ns3::Callback< void, ns3::Ipv4Address, unsigned char, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::RouteCache::GetDestination() const [member function]
cls.add_method('GetDestination',
'ns3::Ipv4Address',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): ns3::Time ns3::dsr::RouteCache::GetExpireTime(ns3::Ipv4Address addr) [member function]
cls.add_method('GetExpireTime',
'ns3::Time',
[param('ns3::Ipv4Address', 'addr')])
## dsr-rcache.h (module 'dsr'): ns3::Time ns3::dsr::RouteCache::GetInitStability() const [member function]
cls.add_method('GetInitStability',
'ns3::Time',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): uint32_t ns3::dsr::RouteCache::GetMaxCacheLen() const [member function]
cls.add_method('GetMaxCacheLen',
'uint32_t',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): uint32_t ns3::dsr::RouteCache::GetMaxEntriesEachDst() const [member function]
cls.add_method('GetMaxEntriesEachDst',
'uint32_t',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): ns3::Time ns3::dsr::RouteCache::GetMinLifeTime() const [member function]
cls.add_method('GetMinLifeTime',
'ns3::Time',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): uint64_t ns3::dsr::RouteCache::GetStabilityDecrFactor() const [member function]
cls.add_method('GetStabilityDecrFactor',
'uint64_t',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): uint64_t ns3::dsr::RouteCache::GetStabilityIncrFactor() const [member function]
cls.add_method('GetStabilityIncrFactor',
'uint64_t',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): bool ns3::dsr::RouteCache::GetSubRoute() const [member function]
cls.add_method('GetSubRoute',
'bool',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): ns3::Callback<void, ns3::WifiMacHeader const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::dsr::RouteCache::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)
## dsr-rcache.h (module 'dsr'): static ns3::TypeId ns3::dsr::RouteCache::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-rcache.h (module 'dsr'): ns3::Time ns3::dsr::RouteCache::GetUseExtends() const [member function]
cls.add_method('GetUseExtends',
'ns3::Time',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): bool ns3::dsr::RouteCache::IsEqual(ns3::dsr::RouteCacheEntry ca) [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::dsr::RouteCacheEntry', 'ca')])
## dsr-rcache.h (module 'dsr'): bool ns3::dsr::RouteCache::IsLinkCache() [member function]
cls.add_method('IsLinkCache',
'bool',
[])
## dsr-rcache.h (module 'dsr'): bool ns3::dsr::RouteCache::IsNeighbor(ns3::Ipv4Address addr) [member function]
cls.add_method('IsNeighbor',
'bool',
[param('ns3::Ipv4Address', 'addr')])
## dsr-rcache.h (module 'dsr'): ns3::Mac48Address ns3::dsr::RouteCache::LookupMacAddress(ns3::Ipv4Address arg0) [member function]
cls.add_method('LookupMacAddress',
'ns3::Mac48Address',
[param('ns3::Ipv4Address', 'arg0')])
## dsr-rcache.h (module 'dsr'): bool ns3::dsr::RouteCache::LookupRoute(ns3::Ipv4Address id, ns3::dsr::RouteCacheEntry & rt) [member function]
cls.add_method('LookupRoute',
'bool',
[param('ns3::Ipv4Address', 'id'), param('ns3::dsr::RouteCacheEntry &', 'rt')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::Print(std::ostream & os) [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::PrintRouteVector(std::list<ns3::dsr::RouteCacheEntry, std::allocator<ns3::dsr::RouteCacheEntry> > route) [member function]
cls.add_method('PrintRouteVector',
'void',
[param('std::list< ns3::dsr::RouteCacheEntry >', 'route')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::PrintVector(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > & vec) [member function]
cls.add_method('PrintVector',
'void',
[param('std::vector< ns3::Ipv4Address > &', 'vec')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::ProcessTxError(ns3::WifiMacHeader const & arg0) [member function]
cls.add_method('ProcessTxError',
'void',
[param('ns3::WifiMacHeader const &', 'arg0')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::Purge() [member function]
cls.add_method('Purge',
'void',
[])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::PurgeLinkNode() [member function]
cls.add_method('PurgeLinkNode',
'void',
[])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::PurgeMac() [member function]
cls.add_method('PurgeMac',
'void',
[])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::RebuildBestRouteTable(ns3::Ipv4Address source) [member function]
cls.add_method('RebuildBestRouteTable',
'void',
[param('ns3::Ipv4Address', 'source')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::RemoveLastEntry(std::list<ns3::dsr::RouteCacheEntry, std::allocator<ns3::dsr::RouteCacheEntry> > & rtVector) [member function]
cls.add_method('RemoveLastEntry',
'void',
[param('std::list< ns3::dsr::RouteCacheEntry > &', 'rtVector')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::ScheduleTimer() [member function]
cls.add_method('ScheduleTimer',
'void',
[])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::SetBadLinkLifetime(ns3::Time t) [member function]
cls.add_method('SetBadLinkLifetime',
'void',
[param('ns3::Time', 't')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::SetCacheTimeout(ns3::Time t) [member function]
cls.add_method('SetCacheTimeout',
'void',
[param('ns3::Time', 't')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::SetCacheType(std::string type) [member function]
cls.add_method('SetCacheType',
'void',
[param('std::string', 'type')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::SetCallback(ns3::Callback<void, ns3::Ipv4Address, unsigned char, 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, unsigned char, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::SetInitStability(ns3::Time initStability) [member function]
cls.add_method('SetInitStability',
'void',
[param('ns3::Time', 'initStability')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::SetMaxCacheLen(uint32_t len) [member function]
cls.add_method('SetMaxCacheLen',
'void',
[param('uint32_t', 'len')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::SetMaxEntriesEachDst(uint32_t entries) [member function]
cls.add_method('SetMaxEntriesEachDst',
'void',
[param('uint32_t', 'entries')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::SetMinLifeTime(ns3::Time minLifeTime) [member function]
cls.add_method('SetMinLifeTime',
'void',
[param('ns3::Time', 'minLifeTime')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::SetStabilityDecrFactor(uint64_t decrFactor) [member function]
cls.add_method('SetStabilityDecrFactor',
'void',
[param('uint64_t', 'decrFactor')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::SetStabilityIncrFactor(uint64_t incrFactor) [member function]
cls.add_method('SetStabilityIncrFactor',
'void',
[param('uint64_t', 'incrFactor')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::SetSubRoute(bool subRoute) [member function]
cls.add_method('SetSubRoute',
'void',
[param('bool', 'subRoute')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::SetUseExtends(ns3::Time useExtends) [member function]
cls.add_method('SetUseExtends',
'void',
[param('ns3::Time', 'useExtends')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::UpdateNeighbor(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > nodeList, ns3::Time expire) [member function]
cls.add_method('UpdateNeighbor',
'void',
[param('std::vector< ns3::Ipv4Address >', 'nodeList'), param('ns3::Time', 'expire')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::UpdateNetGraph() [member function]
cls.add_method('UpdateNetGraph',
'void',
[])
## dsr-rcache.h (module 'dsr'): bool ns3::dsr::RouteCache::UpdateRouteEntry(ns3::Ipv4Address dst) [member function]
cls.add_method('UpdateRouteEntry',
'bool',
[param('ns3::Ipv4Address', 'dst')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCache::UseExtends(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > rt) [member function]
cls.add_method('UseExtends',
'void',
[param('std::vector< ns3::Ipv4Address >', 'rt')])
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCache::m_arp [variable]
cls.add_instance_attribute('m_arp', 'std::vector< ns3::Ptr< ns3::ArpCache > >', is_const=False)
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCache::m_delay [variable]
cls.add_instance_attribute('m_delay', 'ns3::Time', is_const=False)
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCache::m_handleLinkFailure [variable]
cls.add_instance_attribute('m_handleLinkFailure', 'ns3::Callback< void, ns3::Ipv4Address, unsigned char, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', is_const=False)
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCache::m_nb [variable]
cls.add_instance_attribute('m_nb', 'std::vector< ns3::dsr::RouteCache::Neighbor >', is_const=False)
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCache::m_ntimer [variable]
cls.add_instance_attribute('m_ntimer', 'ns3::Timer', is_const=False)
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCache::m_txErrorCallback [variable]
cls.add_instance_attribute('m_txErrorCallback', 'ns3::Callback< void, ns3::WifiMacHeader const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', is_const=False)
return
def register_Ns3DsrRouteCacheNeighbor_methods(root_module, cls):
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCache::Neighbor::Neighbor(ns3::dsr::RouteCache::Neighbor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::RouteCache::Neighbor const &', 'arg0')])
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCache::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')])
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCache::Neighbor::Neighbor() [constructor]
cls.add_constructor([])
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCache::Neighbor::close [variable]
cls.add_instance_attribute('close', 'bool', is_const=False)
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCache::Neighbor::m_expireTime [variable]
cls.add_instance_attribute('m_expireTime', 'ns3::Time', is_const=False)
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCache::Neighbor::m_hardwareAddress [variable]
cls.add_instance_attribute('m_hardwareAddress', 'ns3::Mac48Address', is_const=False)
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCache::Neighbor::m_neighborAddress [variable]
cls.add_instance_attribute('m_neighborAddress', 'ns3::Ipv4Address', is_const=False)
return
def register_Ns3DsrRouteCacheEntry_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCacheEntry::RouteCacheEntry(ns3::dsr::RouteCacheEntry const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::RouteCacheEntry const &', 'arg0')])
## dsr-rcache.h (module 'dsr'): ns3::dsr::RouteCacheEntry::RouteCacheEntry(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > const & ip=std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> >(), ns3::Ipv4Address dst=ns3::Ipv4Address(), ns3::Time exp=ns3::Simulator::Now( )) [constructor]
cls.add_constructor([param('std::vector< ns3::Ipv4Address > const &', 'ip', default_value='std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> >()'), param('ns3::Ipv4Address', 'dst', default_value='ns3::Ipv4Address()'), param('ns3::Time', 'exp', default_value='ns3::Simulator::Now( )')])
## dsr-rcache.h (module 'dsr'): ns3::Time ns3::dsr::RouteCacheEntry::GetBlacklistTimeout() const [member function]
cls.add_method('GetBlacklistTimeout',
'ns3::Time',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::RouteCacheEntry::GetDestination() const [member function]
cls.add_method('GetDestination',
'ns3::Ipv4Address',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): ns3::Time ns3::dsr::RouteCacheEntry::GetExpireTime() const [member function]
cls.add_method('GetExpireTime',
'ns3::Time',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > ns3::dsr::RouteCacheEntry::GetVector() const [member function]
cls.add_method('GetVector',
'std::vector< ns3::Ipv4Address >',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCacheEntry::Invalidate(ns3::Time badLinkLifetime) [member function]
cls.add_method('Invalidate',
'void',
[param('ns3::Time', 'badLinkLifetime')])
## dsr-rcache.h (module 'dsr'): bool ns3::dsr::RouteCacheEntry::IsUnidirectional() const [member function]
cls.add_method('IsUnidirectional',
'bool',
[],
is_const=True)
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCacheEntry::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCacheEntry::SetBlacklistTimeout(ns3::Time t) [member function]
cls.add_method('SetBlacklistTimeout',
'void',
[param('ns3::Time', 't')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCacheEntry::SetDestination(ns3::Ipv4Address d) [member function]
cls.add_method('SetDestination',
'void',
[param('ns3::Ipv4Address', 'd')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCacheEntry::SetExpireTime(ns3::Time exp) [member function]
cls.add_method('SetExpireTime',
'void',
[param('ns3::Time', 'exp')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCacheEntry::SetUnidirectional(bool u) [member function]
cls.add_method('SetUnidirectional',
'void',
[param('bool', 'u')])
## dsr-rcache.h (module 'dsr'): void ns3::dsr::RouteCacheEntry::SetVector(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > v) [member function]
cls.add_method('SetVector',
'void',
[param('std::vector< ns3::Ipv4Address >', 'v')])
return
def register_Ns3DsrRreqTable_methods(root_module, cls):
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::RreqTable::RreqTable(ns3::dsr::RreqTable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::RreqTable const &', 'arg0')])
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::RreqTable::RreqTable() [constructor]
cls.add_constructor([])
## dsr-rreq-table.h (module 'dsr'): uint32_t ns3::dsr::RreqTable::CheckUniqueRreqId(ns3::Ipv4Address dst) [member function]
cls.add_method('CheckUniqueRreqId',
'uint32_t',
[param('ns3::Ipv4Address', 'dst')])
## dsr-rreq-table.h (module 'dsr'): void ns3::dsr::RreqTable::FindAndUpdate(ns3::Ipv4Address dst) [member function]
cls.add_method('FindAndUpdate',
'void',
[param('ns3::Ipv4Address', 'dst')])
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::BlackList * ns3::dsr::RreqTable::FindUnidirectional(ns3::Ipv4Address neighbor) [member function]
cls.add_method('FindUnidirectional',
'ns3::dsr::BlackList *',
[param('ns3::Ipv4Address', 'neighbor')])
## dsr-rreq-table.h (module 'dsr'): uint32_t ns3::dsr::RreqTable::GetInitHopLimit() const [member function]
cls.add_method('GetInitHopLimit',
'uint32_t',
[],
is_const=True)
## dsr-rreq-table.h (module 'dsr'): uint32_t ns3::dsr::RreqTable::GetRreqCnt(ns3::Ipv4Address dst) [member function]
cls.add_method('GetRreqCnt',
'uint32_t',
[param('ns3::Ipv4Address', 'dst')])
## dsr-rreq-table.h (module 'dsr'): uint32_t ns3::dsr::RreqTable::GetRreqIdSize() const [member function]
cls.add_method('GetRreqIdSize',
'uint32_t',
[],
is_const=True)
## dsr-rreq-table.h (module 'dsr'): uint32_t ns3::dsr::RreqTable::GetRreqSize() [member function]
cls.add_method('GetRreqSize',
'uint32_t',
[])
## dsr-rreq-table.h (module 'dsr'): uint32_t ns3::dsr::RreqTable::GetRreqTableSize() const [member function]
cls.add_method('GetRreqTableSize',
'uint32_t',
[],
is_const=True)
## dsr-rreq-table.h (module 'dsr'): static ns3::TypeId ns3::dsr::RreqTable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-rreq-table.h (module 'dsr'): uint32_t ns3::dsr::RreqTable::GetUniqueRreqIdSize() const [member function]
cls.add_method('GetUniqueRreqIdSize',
'uint32_t',
[],
is_const=True)
## dsr-rreq-table.h (module 'dsr'): void ns3::dsr::RreqTable::Invalidate() [member function]
cls.add_method('Invalidate',
'void',
[])
## dsr-rreq-table.h (module 'dsr'): bool ns3::dsr::RreqTable::MarkLinkAsUnidirectional(ns3::Ipv4Address neighbor, ns3::Time blacklistTimeout) [member function]
cls.add_method('MarkLinkAsUnidirectional',
'bool',
[param('ns3::Ipv4Address', 'neighbor'), param('ns3::Time', 'blacklistTimeout')])
## dsr-rreq-table.h (module 'dsr'): void ns3::dsr::RreqTable::PurgeNeighbor() [member function]
cls.add_method('PurgeNeighbor',
'void',
[])
## dsr-rreq-table.h (module 'dsr'): void ns3::dsr::RreqTable::RemoveLeastExpire(std::map<ns3::Ipv4Address, ns3::dsr::RreqTableEntry, std::less<ns3::Ipv4Address>, std::allocator<std::pair<ns3::Ipv4Address const, ns3::dsr::RreqTableEntry> > > & rreqDstMap) [member function]
cls.add_method('RemoveLeastExpire',
'void',
[param('std::map< ns3::Ipv4Address, ns3::dsr::RreqTableEntry > &', 'rreqDstMap')])
## dsr-rreq-table.h (module 'dsr'): void ns3::dsr::RreqTable::RemoveRreqEntry(ns3::Ipv4Address dst) [member function]
cls.add_method('RemoveRreqEntry',
'void',
[param('ns3::Ipv4Address', 'dst')])
## dsr-rreq-table.h (module 'dsr'): void ns3::dsr::RreqTable::SetInitHopLimit(uint32_t hl) [member function]
cls.add_method('SetInitHopLimit',
'void',
[param('uint32_t', 'hl')])
## dsr-rreq-table.h (module 'dsr'): void ns3::dsr::RreqTable::SetRreqIdSize(uint32_t id) [member function]
cls.add_method('SetRreqIdSize',
'void',
[param('uint32_t', 'id')])
## dsr-rreq-table.h (module 'dsr'): void ns3::dsr::RreqTable::SetRreqTableSize(uint32_t rt) [member function]
cls.add_method('SetRreqTableSize',
'void',
[param('uint32_t', 'rt')])
## dsr-rreq-table.h (module 'dsr'): void ns3::dsr::RreqTable::SetUniqueRreqIdSize(uint32_t uid) [member function]
cls.add_method('SetUniqueRreqIdSize',
'void',
[param('uint32_t', 'uid')])
return
def register_Ns3DsrRreqTableEntry_methods(root_module, cls):
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::RreqTableEntry::RreqTableEntry() [constructor]
cls.add_constructor([])
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::RreqTableEntry::RreqTableEntry(ns3::dsr::RreqTableEntry const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::RreqTableEntry const &', 'arg0')])
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::RreqTableEntry::m_expire [variable]
cls.add_instance_attribute('m_expire', 'ns3::Time', is_const=False)
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::RreqTableEntry::m_reqNo [variable]
cls.add_instance_attribute('m_reqNo', 'uint32_t', is_const=False)
return
def register_Ns3DsrSendBuffEntry_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
## dsr-rsendbuff.h (module 'dsr'): ns3::dsr::SendBuffEntry::SendBuffEntry(ns3::dsr::SendBuffEntry const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::SendBuffEntry const &', 'arg0')])
## dsr-rsendbuff.h (module 'dsr'): ns3::dsr::SendBuffEntry::SendBuffEntry(ns3::Ptr<ns3::Packet const> pa=0, ns3::Ipv4Address d=ns3::Ipv4Address(), ns3::Time exp=ns3::Simulator::Now( ), uint8_t p=0) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Packet const >', 'pa', default_value='0'), param('ns3::Ipv4Address', 'd', default_value='ns3::Ipv4Address()'), param('ns3::Time', 'exp', default_value='ns3::Simulator::Now( )'), param('uint8_t', 'p', default_value='0')])
## dsr-rsendbuff.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::SendBuffEntry::GetDestination() const [member function]
cls.add_method('GetDestination',
'ns3::Ipv4Address',
[],
is_const=True)
## dsr-rsendbuff.h (module 'dsr'): ns3::Time ns3::dsr::SendBuffEntry::GetExpireTime() const [member function]
cls.add_method('GetExpireTime',
'ns3::Time',
[],
is_const=True)
## dsr-rsendbuff.h (module 'dsr'): ns3::Ptr<ns3::Packet const> ns3::dsr::SendBuffEntry::GetPacket() const [member function]
cls.add_method('GetPacket',
'ns3::Ptr< ns3::Packet const >',
[],
is_const=True)
## dsr-rsendbuff.h (module 'dsr'): uint8_t ns3::dsr::SendBuffEntry::GetProtocol() const [member function]
cls.add_method('GetProtocol',
'uint8_t',
[],
is_const=True)
## dsr-rsendbuff.h (module 'dsr'): void ns3::dsr::SendBuffEntry::SetDestination(ns3::Ipv4Address d) [member function]
cls.add_method('SetDestination',
'void',
[param('ns3::Ipv4Address', 'd')])
## dsr-rsendbuff.h (module 'dsr'): void ns3::dsr::SendBuffEntry::SetExpireTime(ns3::Time exp) [member function]
cls.add_method('SetExpireTime',
'void',
[param('ns3::Time', 'exp')])
## dsr-rsendbuff.h (module 'dsr'): void ns3::dsr::SendBuffEntry::SetPacket(ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('SetPacket',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'p')])
## dsr-rsendbuff.h (module 'dsr'): void ns3::dsr::SendBuffEntry::SetProtocol(uint8_t p) [member function]
cls.add_method('SetProtocol',
'void',
[param('uint8_t', 'p')])
return
def register_Ns3DsrSendBuffer_methods(root_module, cls):
## dsr-rsendbuff.h (module 'dsr'): ns3::dsr::SendBuffer::SendBuffer(ns3::dsr::SendBuffer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::SendBuffer const &', 'arg0')])
## dsr-rsendbuff.h (module 'dsr'): ns3::dsr::SendBuffer::SendBuffer() [constructor]
cls.add_constructor([])
## dsr-rsendbuff.h (module 'dsr'): bool ns3::dsr::SendBuffer::Dequeue(ns3::Ipv4Address dst, ns3::dsr::SendBuffEntry & entry) [member function]
cls.add_method('Dequeue',
'bool',
[param('ns3::Ipv4Address', 'dst'), param('ns3::dsr::SendBuffEntry &', 'entry')])
## dsr-rsendbuff.h (module 'dsr'): void ns3::dsr::SendBuffer::DropPacketWithDst(ns3::Ipv4Address dst) [member function]
cls.add_method('DropPacketWithDst',
'void',
[param('ns3::Ipv4Address', 'dst')])
## dsr-rsendbuff.h (module 'dsr'): bool ns3::dsr::SendBuffer::Enqueue(ns3::dsr::SendBuffEntry & entry) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::dsr::SendBuffEntry &', 'entry')])
## dsr-rsendbuff.h (module 'dsr'): bool ns3::dsr::SendBuffer::Find(ns3::Ipv4Address dst) [member function]
cls.add_method('Find',
'bool',
[param('ns3::Ipv4Address', 'dst')])
## dsr-rsendbuff.h (module 'dsr'): std::vector<ns3::dsr::SendBuffEntry, std::allocator<ns3::dsr::SendBuffEntry> > & ns3::dsr::SendBuffer::GetBuffer() [member function]
cls.add_method('GetBuffer',
'std::vector< ns3::dsr::SendBuffEntry > &',
[])
## dsr-rsendbuff.h (module 'dsr'): uint32_t ns3::dsr::SendBuffer::GetMaxQueueLen() const [member function]
cls.add_method('GetMaxQueueLen',
'uint32_t',
[],
is_const=True)
## dsr-rsendbuff.h (module 'dsr'): ns3::Time ns3::dsr::SendBuffer::GetSendBufferTimeout() const [member function]
cls.add_method('GetSendBufferTimeout',
'ns3::Time',
[],
is_const=True)
## dsr-rsendbuff.h (module 'dsr'): uint32_t ns3::dsr::SendBuffer::GetSize() [member function]
cls.add_method('GetSize',
'uint32_t',
[])
## dsr-rsendbuff.h (module 'dsr'): void ns3::dsr::SendBuffer::SetMaxQueueLen(uint32_t len) [member function]
cls.add_method('SetMaxQueueLen',
'void',
[param('uint32_t', 'len')])
## dsr-rsendbuff.h (module 'dsr'): void ns3::dsr::SendBuffer::SetSendBufferTimeout(ns3::Time t) [member function]
cls.add_method('SetSendBufferTimeout',
'void',
[param('ns3::Time', 't')])
return
def register_Ns3DsrSourceRreqEntry_methods(root_module, cls):
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::SourceRreqEntry::SourceRreqEntry() [constructor]
cls.add_constructor([])
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::SourceRreqEntry::SourceRreqEntry(ns3::dsr::SourceRreqEntry const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::SourceRreqEntry const &', 'arg0')])
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::SourceRreqEntry::m_dst [variable]
cls.add_instance_attribute('m_dst', 'ns3::Ipv4Address', is_const=False)
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::SourceRreqEntry::m_expire [variable]
cls.add_instance_attribute('m_expire', 'ns3::Time', is_const=False)
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::SourceRreqEntry::m_identification [variable]
cls.add_instance_attribute('m_identification', 'uint32_t', is_const=False)
## dsr-rreq-table.h (module 'dsr'): ns3::dsr::SourceRreqEntry::m_isError [variable]
cls.add_instance_attribute('m_isError', 'bool', is_const=False)
return
def register_Ns3DsrDsrOptionAck_methods(root_module, cls):
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionAck::DsrOptionAck(ns3::dsr::DsrOptionAck const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionAck const &', 'arg0')])
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionAck::DsrOptionAck() [constructor]
cls.add_constructor([])
## dsr-options.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrOptionAck::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionAck::GetOptionNumber() const [member function]
cls.add_method('GetOptionNumber',
'uint8_t',
[],
is_const=True, is_virtual=True)
## dsr-options.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionAck::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionAck::Process(ns3::Ptr<ns3::Packet> packet, ns3::Ptr<ns3::Packet> dsrP, ns3::Ipv4Address ipv4Address, ns3::Ipv4Address source, ns3::Ipv4Header const & ipv4Header, uint8_t protocol, bool & isPromisc) [member function]
cls.add_method('Process',
'uint8_t',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ptr< ns3::Packet >', 'dsrP'), param('ns3::Ipv4Address', 'ipv4Address'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Header const &', 'ipv4Header'), param('uint8_t', 'protocol'), param('bool &', 'isPromisc')],
is_virtual=True)
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionAck::OPT_NUMBER [variable]
cls.add_static_attribute('OPT_NUMBER', 'uint8_t const', is_const=True)
return
def register_Ns3DsrDsrOptionAckHeader_methods(root_module, cls):
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionAckHeader::DsrOptionAckHeader(ns3::dsr::DsrOptionAckHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionAckHeader const &', 'arg0')])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionAckHeader::DsrOptionAckHeader() [constructor]
cls.add_constructor([])
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionAckHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): uint16_t ns3::dsr::DsrOptionAckHeader::GetAckId() const [member function]
cls.add_method('GetAckId',
'uint16_t',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionHeader::Alignment ns3::dsr::DsrOptionAckHeader::GetAlignment() const [member function]
cls.add_method('GetAlignment',
'ns3::dsr::DsrOptionHeader::Alignment',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrOptionAckHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrOptionAckHeader::GetRealDst() const [member function]
cls.add_method('GetRealDst',
'ns3::Ipv4Address',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): ns3::Ipv4Address ns3::dsr::DsrOptionAckHeader::GetRealSrc() const [member function]
cls.add_method('GetRealSrc',
'ns3::Ipv4Address',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionAckHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionAckHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionAckHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionAckHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionAckHeader::SetAckId(uint16_t identification) [member function]
cls.add_method('SetAckId',
'void',
[param('uint16_t', 'identification')])
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionAckHeader::SetRealDst(ns3::Ipv4Address realDstAddress) [member function]
cls.add_method('SetRealDst',
'void',
[param('ns3::Ipv4Address', 'realDstAddress')])
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionAckHeader::SetRealSrc(ns3::Ipv4Address realSrcAddress) [member function]
cls.add_method('SetRealSrc',
'void',
[param('ns3::Ipv4Address', 'realSrcAddress')])
return
def register_Ns3DsrDsrOptionAckReq_methods(root_module, cls):
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionAckReq::DsrOptionAckReq(ns3::dsr::DsrOptionAckReq const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionAckReq const &', 'arg0')])
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionAckReq::DsrOptionAckReq() [constructor]
cls.add_constructor([])
## dsr-options.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrOptionAckReq::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionAckReq::GetOptionNumber() const [member function]
cls.add_method('GetOptionNumber',
'uint8_t',
[],
is_const=True, is_virtual=True)
## dsr-options.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionAckReq::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionAckReq::Process(ns3::Ptr<ns3::Packet> packet, ns3::Ptr<ns3::Packet> dsrP, ns3::Ipv4Address ipv4Address, ns3::Ipv4Address source, ns3::Ipv4Header const & ipv4Header, uint8_t protocol, bool & isPromisc) [member function]
cls.add_method('Process',
'uint8_t',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ptr< ns3::Packet >', 'dsrP'), param('ns3::Ipv4Address', 'ipv4Address'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Header const &', 'ipv4Header'), param('uint8_t', 'protocol'), param('bool &', 'isPromisc')],
is_virtual=True)
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionAckReq::OPT_NUMBER [variable]
cls.add_static_attribute('OPT_NUMBER', 'uint8_t const', is_const=True)
return
def register_Ns3DsrDsrOptionAckReqHeader_methods(root_module, cls):
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionAckReqHeader::DsrOptionAckReqHeader(ns3::dsr::DsrOptionAckReqHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionAckReqHeader const &', 'arg0')])
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionAckReqHeader::DsrOptionAckReqHeader() [constructor]
cls.add_constructor([])
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionAckReqHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## dsr-option-header.h (module 'dsr'): uint16_t ns3::dsr::DsrOptionAckReqHeader::GetAckId() const [member function]
cls.add_method('GetAckId',
'uint16_t',
[],
is_const=True)
## dsr-option-header.h (module 'dsr'): ns3::dsr::DsrOptionHeader::Alignment ns3::dsr::DsrOptionAckReqHeader::GetAlignment() const [member function]
cls.add_method('GetAlignment',
'ns3::dsr::DsrOptionHeader::Alignment',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrOptionAckReqHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): uint32_t ns3::dsr::DsrOptionAckReqHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionAckReqHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionAckReqHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionAckReqHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## dsr-option-header.h (module 'dsr'): void ns3::dsr::DsrOptionAckReqHeader::SetAckId(uint16_t identification) [member function]
cls.add_method('SetAckId',
'void',
[param('uint16_t', 'identification')])
return
def register_Ns3DsrDsrOptionPad1_methods(root_module, cls):
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionPad1::DsrOptionPad1(ns3::dsr::DsrOptionPad1 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionPad1 const &', 'arg0')])
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionPad1::DsrOptionPad1() [constructor]
cls.add_constructor([])
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionPad1::GetOptionNumber() const [member function]
cls.add_method('GetOptionNumber',
'uint8_t',
[],
is_const=True, is_virtual=True)
## dsr-options.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionPad1::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionPad1::Process(ns3::Ptr<ns3::Packet> packet, ns3::Ptr<ns3::Packet> dsrP, ns3::Ipv4Address ipv4Address, ns3::Ipv4Address source, ns3::Ipv4Header const & ipv4Header, uint8_t protocol, bool & isPromisc) [member function]
cls.add_method('Process',
'uint8_t',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ptr< ns3::Packet >', 'dsrP'), param('ns3::Ipv4Address', 'ipv4Address'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Header const &', 'ipv4Header'), param('uint8_t', 'protocol'), param('bool &', 'isPromisc')],
is_virtual=True)
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionPad1::OPT_NUMBER [variable]
cls.add_static_attribute('OPT_NUMBER', 'uint8_t const', is_const=True)
return
def register_Ns3DsrDsrOptionPadn_methods(root_module, cls):
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionPadn::DsrOptionPadn(ns3::dsr::DsrOptionPadn const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionPadn const &', 'arg0')])
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionPadn::DsrOptionPadn() [constructor]
cls.add_constructor([])
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionPadn::GetOptionNumber() const [member function]
cls.add_method('GetOptionNumber',
'uint8_t',
[],
is_const=True, is_virtual=True)
## dsr-options.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionPadn::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionPadn::Process(ns3::Ptr<ns3::Packet> packet, ns3::Ptr<ns3::Packet> dsrP, ns3::Ipv4Address ipv4Address, ns3::Ipv4Address source, ns3::Ipv4Header const & ipv4Header, uint8_t protocol, bool & isPromisc) [member function]
cls.add_method('Process',
'uint8_t',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ptr< ns3::Packet >', 'dsrP'), param('ns3::Ipv4Address', 'ipv4Address'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Header const &', 'ipv4Header'), param('uint8_t', 'protocol'), param('bool &', 'isPromisc')],
is_virtual=True)
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionPadn::OPT_NUMBER [variable]
cls.add_static_attribute('OPT_NUMBER', 'uint8_t const', is_const=True)
return
def register_Ns3DsrDsrOptionRerr_methods(root_module, cls):
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionRerr::DsrOptionRerr(ns3::dsr::DsrOptionRerr const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionRerr const &', 'arg0')])
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionRerr::DsrOptionRerr() [constructor]
cls.add_constructor([])
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionRerr::DoSendError(ns3::Ptr<ns3::Packet> p, ns3::dsr::DsrOptionRerrUnreachHeader & rerr, uint32_t rerrSize, ns3::Ipv4Address ipv4Address, uint8_t protocol) [member function]
cls.add_method('DoSendError',
'uint8_t',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::dsr::DsrOptionRerrUnreachHeader &', 'rerr'), param('uint32_t', 'rerrSize'), param('ns3::Ipv4Address', 'ipv4Address'), param('uint8_t', 'protocol')])
## dsr-options.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrOptionRerr::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionRerr::GetOptionNumber() const [member function]
cls.add_method('GetOptionNumber',
'uint8_t',
[],
is_const=True, is_virtual=True)
## dsr-options.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionRerr::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionRerr::Process(ns3::Ptr<ns3::Packet> packet, ns3::Ptr<ns3::Packet> dsrP, ns3::Ipv4Address ipv4Address, ns3::Ipv4Address source, ns3::Ipv4Header const & ipv4Header, uint8_t protocol, bool & isPromisc) [member function]
cls.add_method('Process',
'uint8_t',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ptr< ns3::Packet >', 'dsrP'), param('ns3::Ipv4Address', 'ipv4Address'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Header const &', 'ipv4Header'), param('uint8_t', 'protocol'), param('bool &', 'isPromisc')],
is_virtual=True)
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionRerr::OPT_NUMBER [variable]
cls.add_static_attribute('OPT_NUMBER', 'uint8_t const', is_const=True)
return
def register_Ns3DsrDsrOptionRrep_methods(root_module, cls):
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionRrep::DsrOptionRrep(ns3::dsr::DsrOptionRrep const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionRrep const &', 'arg0')])
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionRrep::DsrOptionRrep() [constructor]
cls.add_constructor([])
## dsr-options.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrOptionRrep::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionRrep::GetOptionNumber() const [member function]
cls.add_method('GetOptionNumber',
'uint8_t',
[],
is_const=True, is_virtual=True)
## dsr-options.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionRrep::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionRrep::Process(ns3::Ptr<ns3::Packet> packet, ns3::Ptr<ns3::Packet> dsrP, ns3::Ipv4Address ipv4Address, ns3::Ipv4Address source, ns3::Ipv4Header const & ipv4Header, uint8_t protocol, bool & isPromisc) [member function]
cls.add_method('Process',
'uint8_t',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ptr< ns3::Packet >', 'dsrP'), param('ns3::Ipv4Address', 'ipv4Address'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Header const &', 'ipv4Header'), param('uint8_t', 'protocol'), param('bool &', 'isPromisc')],
is_virtual=True)
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionRrep::OPT_NUMBER [variable]
cls.add_static_attribute('OPT_NUMBER', 'uint8_t const', is_const=True)
return
def register_Ns3DsrDsrOptionRreq_methods(root_module, cls):
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionRreq::DsrOptionRreq(ns3::dsr::DsrOptionRreq const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionRreq const &', 'arg0')])
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionRreq::DsrOptionRreq() [constructor]
cls.add_constructor([])
## dsr-options.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrOptionRreq::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionRreq::GetOptionNumber() const [member function]
cls.add_method('GetOptionNumber',
'uint8_t',
[],
is_const=True, is_virtual=True)
## dsr-options.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionRreq::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionRreq::Process(ns3::Ptr<ns3::Packet> packet, ns3::Ptr<ns3::Packet> dsrP, ns3::Ipv4Address ipv4Address, ns3::Ipv4Address source, ns3::Ipv4Header const & ipv4Header, uint8_t protocol, bool & isPromisc) [member function]
cls.add_method('Process',
'uint8_t',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ptr< ns3::Packet >', 'dsrP'), param('ns3::Ipv4Address', 'ipv4Address'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Header const &', 'ipv4Header'), param('uint8_t', 'protocol'), param('bool &', 'isPromisc')],
is_virtual=True)
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionRreq::OPT_NUMBER [variable]
cls.add_static_attribute('OPT_NUMBER', 'uint8_t const', is_const=True)
return
def register_Ns3DsrDsrOptionSR_methods(root_module, cls):
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionSR::DsrOptionSR(ns3::dsr::DsrOptionSR const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsr::DsrOptionSR const &', 'arg0')])
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionSR::DsrOptionSR() [constructor]
cls.add_constructor([])
## dsr-options.h (module 'dsr'): ns3::TypeId ns3::dsr::DsrOptionSR::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionSR::GetOptionNumber() const [member function]
cls.add_method('GetOptionNumber',
'uint8_t',
[],
is_const=True, is_virtual=True)
## dsr-options.h (module 'dsr'): static ns3::TypeId ns3::dsr::DsrOptionSR::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsr-options.h (module 'dsr'): uint8_t ns3::dsr::DsrOptionSR::Process(ns3::Ptr<ns3::Packet> packet, ns3::Ptr<ns3::Packet> dsrP, ns3::Ipv4Address ipv4Address, ns3::Ipv4Address source, ns3::Ipv4Header const & ipv4Header, uint8_t protocol, bool & isPromisc) [member function]
cls.add_method('Process',
'uint8_t',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ptr< ns3::Packet >', 'dsrP'), param('ns3::Ipv4Address', 'ipv4Address'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Header const &', 'ipv4Header'), param('uint8_t', 'protocol'), param('bool &', 'isPromisc')],
is_virtual=True)
## dsr-options.h (module 'dsr'): ns3::dsr::DsrOptionSR::OPT_NUMBER [variable]
cls.add_static_attribute('OPT_NUMBER', 'uint8_t const', is_const=True)
return
def register_functions(root_module):
module = root_module
register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module)
register_functions_ns3_dsr(module.get_submodule('dsr'), root_module)
register_functions_ns3_internal(module.get_submodule('internal'), root_module)
return
def register_functions_ns3_FatalImpl(module, root_module):
return
def register_functions_ns3_dsr(module, root_module):
return
def register_functions_ns3_internal(module, root_module):
return
def main():
out = FileCodeSink(sys.stdout)
root_module = module_init()
register_types(root_module)
register_methods(root_module)
register_functions(root_module)
root_module.generate(out)
if __name__ == '__main__':
main()
| gpl-2.0 | -228,024,999,261,269,300 | 63.701702 | 998 | 0.602285 | false |
swayf/pyLoad | module/plugins/hoster/YoupornCom.py | 2 | 1680 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
from module.plugins.Hoster import Hoster
class YoupornCom(Hoster):
__name__ = "YoupornCom"
__type__ = "hoster"
__pattern__ = r"http://(www\.)?youporn\.com/watch/.+"
__version__ = "0.2"
__description__ = """Youporn.com Video Download Hoster"""
__author_name__ = ("willnix")
__author_mail__ = ("[email protected]")
def setup(self):
self.html = None
def process(self, pyfile):
self.pyfile = pyfile
if not self.file_exists():
self.offline()
self.pyfile.name = self.get_file_name()
self.download(self.get_file_url())
def download_html(self):
url = self.pyfile.url
self.html = self.load(url, post={"user_choice":"Enter"}, cookies=False)
def get_file_url(self):
""" returns the absolute downloadable filepath
"""
if self.html is None:
self.download_html()
file_url = re.search(r'(http://download\.youporn\.com/download/\d+\?save=1)">', self.html).group(1)
return file_url
def get_file_name(self):
if self.html is None:
self.download_html()
file_name_pattern = r"<title>(.*) - Free Porn Videos - YouPorn</title>"
return re.search(file_name_pattern, self.html).group(1).replace("&", "&").replace("/","") + '.flv'
def file_exists(self):
""" returns True or False
"""
if self.html is None:
self.download_html()
if re.search(r"(.*invalid video_id.*)", self.html) is not None:
return False
else:
return True
| agpl-3.0 | 2,752,229,234,266,981,000 | 29 | 110 | 0.550595 | false |
18padx08/PPTex | PPTexEnv_x86_64/lib/python2.7/site-packages/sympy/core/tests/test_args.py | 7 | 109968 | """Test whether all elements of cls.args are instances of Basic. """
# NOTE: keep tests sorted by (module, class name) key. If a class can't
# be instantiated, add it here anyway with @SKIP("abstract class) (see
# e.g. Function).
import os
import re
import warnings
import io
from sympy import Basic, S, symbols, sqrt, sin, oo, Interval, exp
from sympy.utilities.pytest import XFAIL, SKIP
from sympy.utilities.exceptions import SymPyDeprecationWarning
x, y, z = symbols('x,y,z')
def test_all_classes_are_tested():
this = os.path.split(__file__)[0]
path = os.path.join(this, os.pardir, os.pardir)
sympy_path = os.path.abspath(path)
prefix = os.path.split(sympy_path)[0] + os.sep
re_cls = re.compile("^class ([A-Za-z][A-Za-z0-9_]*)\s*\(", re.MULTILINE)
modules = {}
for root, dirs, files in os.walk(sympy_path):
module = root.replace(prefix, "").replace(os.sep, ".")
for file in files:
if file.startswith(("_", "test_", "bench_")):
continue
if not file.endswith(".py"):
continue
with io.open(os.path.join(root, file), "r", encoding='utf-8') as f:
text = f.read()
submodule = module + '.' + file[:-3]
names = re_cls.findall(text)
if not names:
continue
try:
mod = __import__(submodule, fromlist=names)
except ImportError:
continue
def is_Basic(name):
cls = getattr(mod, name)
return issubclass(cls, Basic)
names = list(filter(is_Basic, names))
if names:
modules[submodule] = names
ns = globals()
failed = []
for module, names in modules.items():
mod = module.replace('.', '__')
for name in names:
test = 'test_' + mod + '__' + name
if test not in ns:
failed.append(module + '.' + name)
# reset all SymPyDeprecationWarning into errors
warnings.simplefilter("error", category=SymPyDeprecationWarning)
assert not failed, "Missing classes: %s. Please add tests for these to sympy/core/tests/test_args.py." % ", ".join(failed)
def _test_args(obj):
return all(isinstance(arg, Basic) for arg in obj.args)
def test_sympy__assumptions__assume__AppliedPredicate():
from sympy.assumptions.assume import AppliedPredicate, Predicate
assert _test_args(AppliedPredicate(Predicate("test"), 2))
def test_sympy__assumptions__assume__Predicate():
from sympy.assumptions.assume import Predicate
assert _test_args(Predicate("test"))
@XFAIL
def test_sympy__combinatorics__graycode__GrayCode():
from sympy.combinatorics.graycode import GrayCode
# an integer is given and returned from GrayCode as the arg
assert _test_args(GrayCode(3, start='100'))
assert _test_args(GrayCode(3, rank=1))
def test_sympy__combinatorics__subsets__Subset():
from sympy.combinatorics.subsets import Subset
assert _test_args(Subset([0, 1], [0, 1, 2, 3]))
assert _test_args(Subset(['c', 'd'], ['a', 'b', 'c', 'd']))
@XFAIL
def test_sympy__combinatorics__permutations__Permutation():
from sympy.combinatorics.permutations import Permutation
assert _test_args(Permutation([0, 1, 2, 3]))
def test_sympy__combinatorics__perm_groups__PermutationGroup():
from sympy.combinatorics.permutations import Permutation
from sympy.combinatorics.perm_groups import PermutationGroup
assert _test_args(PermutationGroup([Permutation([0, 1])]))
def test_sympy__combinatorics__polyhedron__Polyhedron():
from sympy.combinatorics.permutations import Permutation
from sympy.combinatorics.polyhedron import Polyhedron
from sympy.abc import w, x, y, z
pgroup = [Permutation([[0, 1, 2], [3]]),
Permutation([[0, 1, 3], [2]]),
Permutation([[0, 2, 3], [1]]),
Permutation([[1, 2, 3], [0]]),
Permutation([[0, 1], [2, 3]]),
Permutation([[0, 2], [1, 3]]),
Permutation([[0, 3], [1, 2]]),
Permutation([[0, 1, 2, 3]])]
corners = [w, x, y, z]
faces = [(w, x, y), (w, y, z), (w, z, x), (x, y, z)]
assert _test_args(Polyhedron(corners, faces, pgroup))
@XFAIL
def test_sympy__combinatorics__prufer__Prufer():
from sympy.combinatorics.prufer import Prufer
assert _test_args(Prufer([[0, 1], [0, 2], [0, 3]], 4))
def test_sympy__combinatorics__partitions__Partition():
from sympy.combinatorics.partitions import Partition
assert _test_args(Partition([1]))
@XFAIL
def test_sympy__combinatorics__partitions__IntegerPartition():
from sympy.combinatorics.partitions import IntegerPartition
assert _test_args(IntegerPartition([1]))
def test_sympy__concrete__products__Product():
from sympy.concrete.products import Product
assert _test_args(Product(x, (x, 0, 10)))
assert _test_args(Product(x, (x, 0, y), (y, 0, 10)))
@SKIP("abstract Class")
def test_sympy__concrete__expr_with_limits__ExprWithLimits():
from sympy.concrete.expr_with_limits import ExprWithLimits
assert _test_args(ExprWithLimits(x, (x, 0, 10)))
assert _test_args(ExprWithLimits(x*y, (x, 0, 10.),(y,1.,3)))
@SKIP("abstract Class")
def test_sympy__concrete__expr_with_limits__AddWithLimits():
from sympy.concrete.expr_with_limits import AddWithLimits
assert _test_args(AddWithLimits(x, (x, 0, 10)))
assert _test_args(AddWithLimits(x*y, (x, 0, 10),(y,1,3)))
@SKIP("abstract Class")
def test_sympy__concrete__expr_with_intlimits__ExprWithIntLimits():
from sympy.concrete.expr_with_intlimits import ExprWithIntLimits
assert _test_args(ExprWithIntLimits(x, (x, 0, 10)))
assert _test_args(ExprWithIntLimits(x*y, (x, 0, 10),(y,1,3)))
def test_sympy__concrete__summations__Sum():
from sympy.concrete.summations import Sum
assert _test_args(Sum(x, (x, 0, 10)))
assert _test_args(Sum(x, (x, 0, y), (y, 0, 10)))
def test_sympy__core__add__Add():
from sympy.core.add import Add
assert _test_args(Add(x, y, z, 2))
def test_sympy__core__basic__Atom():
from sympy.core.basic import Atom
assert _test_args(Atom())
def test_sympy__core__basic__Basic():
from sympy.core.basic import Basic
assert _test_args(Basic())
def test_sympy__core__containers__Dict():
from sympy.core.containers import Dict
assert _test_args(Dict({x: y, y: z}))
def test_sympy__core__containers__Tuple():
from sympy.core.containers import Tuple
assert _test_args(Tuple(x, y, z, 2))
def test_sympy__core__expr__AtomicExpr():
from sympy.core.expr import AtomicExpr
assert _test_args(AtomicExpr())
def test_sympy__core__expr__Expr():
from sympy.core.expr import Expr
assert _test_args(Expr())
def test_sympy__core__function__Application():
from sympy.core.function import Application
assert _test_args(Application(1, 2, 3))
def test_sympy__core__function__AppliedUndef():
from sympy.core.function import AppliedUndef
assert _test_args(AppliedUndef(1, 2, 3))
def test_sympy__core__function__Derivative():
from sympy.core.function import Derivative
assert _test_args(Derivative(2, x, y, 3))
@SKIP("abstract class")
def test_sympy__core__function__Function():
pass
def test_sympy__core__function__Lambda():
from sympy.core.function import Lambda
assert _test_args(Lambda((x, y), x + y + z))
def test_sympy__core__function__Subs():
from sympy.core.function import Subs
assert _test_args(Subs(x + y, x, 2))
def test_sympy__core__function__WildFunction():
from sympy.core.function import WildFunction
assert _test_args(WildFunction('f'))
def test_sympy__core__mod__Mod():
from sympy.core.mod import Mod
assert _test_args(Mod(x, 2))
def test_sympy__core__mul__Mul():
from sympy.core.mul import Mul
assert _test_args(Mul(2, x, y, z))
def test_sympy__core__numbers__Catalan():
from sympy.core.numbers import Catalan
assert _test_args(Catalan())
def test_sympy__core__numbers__ComplexInfinity():
from sympy.core.numbers import ComplexInfinity
assert _test_args(ComplexInfinity())
def test_sympy__core__numbers__EulerGamma():
from sympy.core.numbers import EulerGamma
assert _test_args(EulerGamma())
def test_sympy__core__numbers__Exp1():
from sympy.core.numbers import Exp1
assert _test_args(Exp1())
def test_sympy__core__numbers__Float():
from sympy.core.numbers import Float
assert _test_args(Float(1.23))
def test_sympy__core__numbers__GoldenRatio():
from sympy.core.numbers import GoldenRatio
assert _test_args(GoldenRatio())
def test_sympy__core__numbers__Half():
from sympy.core.numbers import Half
assert _test_args(Half())
def test_sympy__core__numbers__ImaginaryUnit():
from sympy.core.numbers import ImaginaryUnit
assert _test_args(ImaginaryUnit())
def test_sympy__core__numbers__Infinity():
from sympy.core.numbers import Infinity
assert _test_args(Infinity())
def test_sympy__core__numbers__Integer():
from sympy.core.numbers import Integer
assert _test_args(Integer(7))
@SKIP("abstract class")
def test_sympy__core__numbers__IntegerConstant():
pass
def test_sympy__core__numbers__NaN():
from sympy.core.numbers import NaN
assert _test_args(NaN())
def test_sympy__core__numbers__NegativeInfinity():
from sympy.core.numbers import NegativeInfinity
assert _test_args(NegativeInfinity())
def test_sympy__core__numbers__NegativeOne():
from sympy.core.numbers import NegativeOne
assert _test_args(NegativeOne())
def test_sympy__core__numbers__Number():
from sympy.core.numbers import Number
assert _test_args(Number(1, 7))
def test_sympy__core__numbers__NumberSymbol():
from sympy.core.numbers import NumberSymbol
assert _test_args(NumberSymbol())
def test_sympy__core__numbers__One():
from sympy.core.numbers import One
assert _test_args(One())
def test_sympy__core__numbers__Pi():
from sympy.core.numbers import Pi
assert _test_args(Pi())
def test_sympy__core__numbers__Rational():
from sympy.core.numbers import Rational
assert _test_args(Rational(1, 7))
@SKIP("abstract class")
def test_sympy__core__numbers__RationalConstant():
pass
def test_sympy__core__numbers__Zero():
from sympy.core.numbers import Zero
assert _test_args(Zero())
@SKIP("abstract class")
def test_sympy__core__operations__AssocOp():
pass
@SKIP("abstract class")
def test_sympy__core__operations__LatticeOp():
pass
def test_sympy__core__power__Pow():
from sympy.core.power import Pow
assert _test_args(Pow(x, 2))
def test_sympy__core__relational__Equality():
from sympy.core.relational import Equality
assert _test_args(Equality(x, 2))
def test_sympy__core__relational__GreaterThan():
from sympy.core.relational import GreaterThan
assert _test_args(GreaterThan(x, 2))
def test_sympy__core__relational__LessThan():
from sympy.core.relational import LessThan
assert _test_args(LessThan(x, 2))
@SKIP("abstract class")
def test_sympy__core__relational__Relational():
pass
def test_sympy__core__relational__StrictGreaterThan():
from sympy.core.relational import StrictGreaterThan
assert _test_args(StrictGreaterThan(x, 2))
def test_sympy__core__relational__StrictLessThan():
from sympy.core.relational import StrictLessThan
assert _test_args(StrictLessThan(x, 2))
def test_sympy__core__relational__Unequality():
from sympy.core.relational import Unequality
assert _test_args(Unequality(x, 2))
def test_sympy__sets__sets__EmptySet():
from sympy.sets.sets import EmptySet
assert _test_args(EmptySet())
def test_sympy__sets__sets__UniversalSet():
from sympy.sets.sets import UniversalSet
assert _test_args(UniversalSet())
def test_sympy__sets__sets__FiniteSet():
from sympy.sets.sets import FiniteSet
assert _test_args(FiniteSet(x, y, z))
def test_sympy__sets__sets__Interval():
from sympy.sets.sets import Interval
assert _test_args(Interval(0, 1))
def test_sympy__sets__sets__ProductSet():
from sympy.sets.sets import ProductSet, Interval
assert _test_args(ProductSet(Interval(0, 1), Interval(0, 1)))
@SKIP("does it make sense to test this?")
def test_sympy__sets__sets__Set():
from sympy.sets.sets import Set
assert _test_args(Set())
def test_sympy__sets__sets__Intersection():
from sympy.sets.sets import Intersection, Interval
assert _test_args(Intersection(Interval(0, 3), Interval(2, 4),
evaluate=False))
def test_sympy__sets__sets__Union():
from sympy.sets.sets import Union, Interval
assert _test_args(Union(Interval(0, 1), Interval(2, 3)))
def test_sympy__sets__sets__Complement():
from sympy.sets.sets import Complement
assert _test_args(Complement(Interval(0, 2), Interval(0, 1)))
def test_sympy__core__trace__Tr():
from sympy.core.trace import Tr
a, b = symbols('a b')
assert _test_args(Tr(a + b))
def test_sympy__sets__fancysets__Naturals():
from sympy.sets.fancysets import Naturals
assert _test_args(Naturals())
def test_sympy__sets__fancysets__Naturals0():
from sympy.sets.fancysets import Naturals0
assert _test_args(Naturals0())
def test_sympy__sets__fancysets__Integers():
from sympy.sets.fancysets import Integers
assert _test_args(Integers())
def test_sympy__sets__fancysets__Reals():
from sympy.sets.fancysets import Reals
assert _test_args(Reals())
def test_sympy__sets__fancysets__ImageSet():
from sympy.sets.fancysets import ImageSet
from sympy import S, Lambda, Symbol
x = Symbol('x')
assert _test_args(ImageSet(Lambda(x, x**2), S.Naturals))
def test_sympy__sets__fancysets__Range():
from sympy.sets.fancysets import Range
assert _test_args(Range(1, 5, 1))
def test_sympy__sets__contains__Contains():
from sympy.sets.fancysets import Range
from sympy.sets.contains import Contains
assert _test_args(Contains(x, Range(0, 10, 2)))
# STATS
from sympy.stats.crv_types import NormalDistribution
nd = NormalDistribution(0, 1)
from sympy.stats.frv_types import DieDistribution
die = DieDistribution(6)
def test_sympy__stats__crv__ContinuousDomain():
from sympy.stats.crv import ContinuousDomain
assert _test_args(ContinuousDomain(set([x]), Interval(-oo, oo)))
def test_sympy__stats__crv__SingleContinuousDomain():
from sympy.stats.crv import SingleContinuousDomain
assert _test_args(SingleContinuousDomain(x, Interval(-oo, oo)))
def test_sympy__stats__crv__ProductContinuousDomain():
from sympy.stats.crv import SingleContinuousDomain, ProductContinuousDomain
D = SingleContinuousDomain(x, Interval(-oo, oo))
E = SingleContinuousDomain(y, Interval(0, oo))
assert _test_args(ProductContinuousDomain(D, E))
def test_sympy__stats__crv__ConditionalContinuousDomain():
from sympy.stats.crv import (SingleContinuousDomain,
ConditionalContinuousDomain)
D = SingleContinuousDomain(x, Interval(-oo, oo))
assert _test_args(ConditionalContinuousDomain(D, x > 0))
def test_sympy__stats__crv__ContinuousPSpace():
from sympy.stats.crv import ContinuousPSpace, SingleContinuousDomain
D = SingleContinuousDomain(x, Interval(-oo, oo))
assert _test_args(ContinuousPSpace(D, nd))
def test_sympy__stats__crv__SingleContinuousPSpace():
from sympy.stats.crv import SingleContinuousPSpace
assert _test_args(SingleContinuousPSpace(x, nd))
def test_sympy__stats__crv__ProductContinuousPSpace():
from sympy.stats.crv import ProductContinuousPSpace, SingleContinuousPSpace
A = SingleContinuousPSpace(x, nd)
B = SingleContinuousPSpace(y, nd)
assert _test_args(ProductContinuousPSpace(A, B))
@SKIP("abstract class")
def test_sympy__stats__crv__SingleContinuousDistribution():
pass
def test_sympy__stats__drv__SingleDiscreteDomain():
from sympy.stats.drv import SingleDiscreteDomain
assert _test_args(SingleDiscreteDomain(x, S.Naturals))
def test_sympy__stats__drv__SingleDiscretePSpace():
from sympy.stats.drv import SingleDiscretePSpace
from sympy.stats.drv_types import PoissonDistribution
assert _test_args(SingleDiscretePSpace(x, PoissonDistribution(1)))
@SKIP("abstract class")
def test_sympy__stats__drv__SingleDiscreteDistribution():
pass
def test_sympy__stats__rv__RandomDomain():
from sympy.stats.rv import RandomDomain
from sympy.sets.sets import FiniteSet
assert _test_args(RandomDomain(FiniteSet(x), FiniteSet(1, 2, 3)))
def test_sympy__stats__rv__SingleDomain():
from sympy.stats.rv import SingleDomain
from sympy.sets.sets import FiniteSet
assert _test_args(SingleDomain(x, FiniteSet(1, 2, 3)))
def test_sympy__stats__rv__ConditionalDomain():
from sympy.stats.rv import ConditionalDomain, RandomDomain
from sympy.sets.sets import FiniteSet
D = RandomDomain(FiniteSet(x), FiniteSet(1, 2))
assert _test_args(ConditionalDomain(D, x > 1))
def test_sympy__stats__rv__PSpace():
from sympy.stats.rv import PSpace, RandomDomain
from sympy import Dict, FiniteSet
D = RandomDomain(FiniteSet(x), FiniteSet(1, 2, 3, 4, 5, 6))
assert _test_args(PSpace(D, die))
@SKIP("abstract Class")
def test_sympy__stats__rv__SinglePSpace():
pass
def test_sympy__stats__rv__RandomSymbol():
from sympy.stats.rv import RandomSymbol
from sympy.stats.crv import SingleContinuousPSpace
A = SingleContinuousPSpace(x, nd)
assert _test_args(RandomSymbol(A, x))
def test_sympy__stats__rv__ProductPSpace():
from sympy.stats.rv import ProductPSpace
from sympy.stats.crv import SingleContinuousPSpace
A = SingleContinuousPSpace(x, nd)
B = SingleContinuousPSpace(y, nd)
assert _test_args(ProductPSpace(A, B))
def test_sympy__stats__rv__ProductDomain():
from sympy.stats.rv import ProductDomain, SingleDomain
D = SingleDomain(x, Interval(-oo, oo))
E = SingleDomain(y, Interval(0, oo))
assert _test_args(ProductDomain(D, E))
def test_sympy__stats__frv_types__DiscreteUniformDistribution():
from sympy.stats.frv_types import DiscreteUniformDistribution
from sympy.core.containers import Tuple
assert _test_args(DiscreteUniformDistribution(Tuple(*list(range(6)))))
def test_sympy__stats__frv_types__DieDistribution():
from sympy.stats.frv_types import DieDistribution
assert _test_args(DieDistribution(6))
def test_sympy__stats__frv_types__BernoulliDistribution():
from sympy.stats.frv_types import BernoulliDistribution
assert _test_args(BernoulliDistribution(S.Half, 0, 1))
def test_sympy__stats__frv_types__BinomialDistribution():
from sympy.stats.frv_types import BinomialDistribution
assert _test_args(BinomialDistribution(5, S.Half, 1, 0))
def test_sympy__stats__frv_types__HypergeometricDistribution():
from sympy.stats.frv_types import HypergeometricDistribution
assert _test_args(HypergeometricDistribution(10, 5, 3))
def test_sympy__stats__frv_types__RademacherDistribution():
from sympy.stats.frv_types import RademacherDistribution
assert _test_args(RademacherDistribution())
def test_sympy__stats__frv__FiniteDomain():
from sympy.stats.frv import FiniteDomain
assert _test_args(FiniteDomain(set([(x, 1), (x, 2)]))) # x can be 1 or 2
def test_sympy__stats__frv__SingleFiniteDomain():
from sympy.stats.frv import SingleFiniteDomain
assert _test_args(SingleFiniteDomain(x, set([1, 2]))) # x can be 1 or 2
def test_sympy__stats__frv__ProductFiniteDomain():
from sympy.stats.frv import SingleFiniteDomain, ProductFiniteDomain
xd = SingleFiniteDomain(x, set([1, 2]))
yd = SingleFiniteDomain(y, set([1, 2]))
assert _test_args(ProductFiniteDomain(xd, yd))
def test_sympy__stats__frv__ConditionalFiniteDomain():
from sympy.stats.frv import SingleFiniteDomain, ConditionalFiniteDomain
xd = SingleFiniteDomain(x, set([1, 2]))
assert _test_args(ConditionalFiniteDomain(xd, x > 1))
def test_sympy__stats__frv__FinitePSpace():
from sympy.stats.frv import FinitePSpace, SingleFiniteDomain
xd = SingleFiniteDomain(x, set([1, 2, 3, 4, 5, 6]))
p = 1.0/6
xd = SingleFiniteDomain(x, set([1, 2]))
assert _test_args(FinitePSpace(xd, {(x, 1): S.Half, (x, 2): S.Half}))
def test_sympy__stats__frv__SingleFinitePSpace():
from sympy.stats.frv import SingleFinitePSpace, SingleFiniteDomain
from sympy import Symbol
assert _test_args(SingleFinitePSpace(Symbol('x'), die))
def test_sympy__stats__frv__ProductFinitePSpace():
from sympy.stats.frv import (SingleFiniteDomain, SingleFinitePSpace,
ProductFinitePSpace)
from sympy import Symbol
xp = SingleFinitePSpace(Symbol('x'), die)
yp = SingleFinitePSpace(Symbol('y'), die)
assert _test_args(ProductFinitePSpace(xp, yp))
@SKIP("abstract class")
def test_sympy__stats__frv__SingleFiniteDistribution():
pass
@SKIP("abstract class")
def test_sympy__stats__crv__ContinuousDistribution():
pass
def test_sympy__stats__frv_types__FiniteDistributionHandmade():
from sympy.stats.frv_types import FiniteDistributionHandmade
assert _test_args(FiniteDistributionHandmade({1: 1}))
def test_sympy__stats__crv__ContinuousDistributionHandmade():
from sympy.stats.crv import ContinuousDistributionHandmade
from sympy import Symbol, Interval
assert _test_args(ContinuousDistributionHandmade(Symbol('x'),
Interval(0, 2)))
def test_sympy__stats__rv__Density():
from sympy.stats.rv import Density
from sympy.stats.crv_types import Normal
assert _test_args(Density(Normal('x', 0, 1)))
def test_sympy__stats__crv_types__ArcsinDistribution():
from sympy.stats.crv_types import ArcsinDistribution
assert _test_args(ArcsinDistribution(0, 1))
def test_sympy__stats__crv_types__BeniniDistribution():
from sympy.stats.crv_types import BeniniDistribution
assert _test_args(BeniniDistribution(1, 1, 1))
def test_sympy__stats__crv_types__BetaDistribution():
from sympy.stats.crv_types import BetaDistribution
assert _test_args(BetaDistribution(1, 1))
def test_sympy__stats__crv_types__BetaPrimeDistribution():
from sympy.stats.crv_types import BetaPrimeDistribution
assert _test_args(BetaPrimeDistribution(1, 1))
def test_sympy__stats__crv_types__CauchyDistribution():
from sympy.stats.crv_types import CauchyDistribution
assert _test_args(CauchyDistribution(0, 1))
def test_sympy__stats__crv_types__ChiDistribution():
from sympy.stats.crv_types import ChiDistribution
assert _test_args(ChiDistribution(1))
def test_sympy__stats__crv_types__ChiNoncentralDistribution():
from sympy.stats.crv_types import ChiNoncentralDistribution
assert _test_args(ChiNoncentralDistribution(1,1))
def test_sympy__stats__crv_types__ChiSquaredDistribution():
from sympy.stats.crv_types import ChiSquaredDistribution
assert _test_args(ChiSquaredDistribution(1))
def test_sympy__stats__crv_types__DagumDistribution():
from sympy.stats.crv_types import DagumDistribution
assert _test_args(DagumDistribution(1, 1, 1))
def test_sympy__stats__crv_types__ExponentialDistribution():
from sympy.stats.crv_types import ExponentialDistribution
assert _test_args(ExponentialDistribution(1))
def test_sympy__stats__crv_types__FDistributionDistribution():
from sympy.stats.crv_types import FDistributionDistribution
assert _test_args(FDistributionDistribution(1, 1))
def test_sympy__stats__crv_types__FisherZDistribution():
from sympy.stats.crv_types import FisherZDistribution
assert _test_args(FisherZDistribution(1, 1))
def test_sympy__stats__crv_types__FrechetDistribution():
from sympy.stats.crv_types import FrechetDistribution
assert _test_args(FrechetDistribution(1, 1, 1))
def test_sympy__stats__crv_types__GammaInverseDistribution():
from sympy.stats.crv_types import GammaInverseDistribution
assert _test_args(GammaInverseDistribution(1, 1))
def test_sympy__stats__crv_types__GammaDistribution():
from sympy.stats.crv_types import GammaDistribution
assert _test_args(GammaDistribution(1, 1))
def test_sympy__stats__crv_types__KumaraswamyDistribution():
from sympy.stats.crv_types import KumaraswamyDistribution
assert _test_args(KumaraswamyDistribution(1, 1))
def test_sympy__stats__crv_types__LaplaceDistribution():
from sympy.stats.crv_types import LaplaceDistribution
assert _test_args(LaplaceDistribution(0, 1))
def test_sympy__stats__crv_types__LogisticDistribution():
from sympy.stats.crv_types import LogisticDistribution
assert _test_args(LogisticDistribution(0, 1))
def test_sympy__stats__crv_types__LogNormalDistribution():
from sympy.stats.crv_types import LogNormalDistribution
assert _test_args(LogNormalDistribution(0, 1))
def test_sympy__stats__crv_types__MaxwellDistribution():
from sympy.stats.crv_types import MaxwellDistribution
assert _test_args(MaxwellDistribution(1))
def test_sympy__stats__crv_types__NakagamiDistribution():
from sympy.stats.crv_types import NakagamiDistribution
assert _test_args(NakagamiDistribution(1, 1))
def test_sympy__stats__crv_types__NormalDistribution():
from sympy.stats.crv_types import NormalDistribution
assert _test_args(NormalDistribution(0, 1))
def test_sympy__stats__crv_types__ParetoDistribution():
from sympy.stats.crv_types import ParetoDistribution
assert _test_args(ParetoDistribution(1, 1))
def test_sympy__stats__crv_types__QuadraticUDistribution():
from sympy.stats.crv_types import QuadraticUDistribution
assert _test_args(QuadraticUDistribution(1, 2))
def test_sympy__stats__crv_types__RaisedCosineDistribution():
from sympy.stats.crv_types import RaisedCosineDistribution
assert _test_args(RaisedCosineDistribution(1, 1))
def test_sympy__stats__crv_types__RayleighDistribution():
from sympy.stats.crv_types import RayleighDistribution
assert _test_args(RayleighDistribution(1))
def test_sympy__stats__crv_types__StudentTDistribution():
from sympy.stats.crv_types import StudentTDistribution
assert _test_args(StudentTDistribution(1))
def test_sympy__stats__crv_types__TriangularDistribution():
from sympy.stats.crv_types import TriangularDistribution
assert _test_args(TriangularDistribution(-1, 0, 1))
def test_sympy__stats__crv_types__UniformDistribution():
from sympy.stats.crv_types import UniformDistribution
assert _test_args(UniformDistribution(0, 1))
def test_sympy__stats__crv_types__UniformSumDistribution():
from sympy.stats.crv_types import UniformSumDistribution
assert _test_args(UniformSumDistribution(1))
def test_sympy__stats__crv_types__VonMisesDistribution():
from sympy.stats.crv_types import VonMisesDistribution
assert _test_args(VonMisesDistribution(1, 1))
def test_sympy__stats__crv_types__WeibullDistribution():
from sympy.stats.crv_types import WeibullDistribution
assert _test_args(WeibullDistribution(1, 1))
def test_sympy__stats__crv_types__WignerSemicircleDistribution():
from sympy.stats.crv_types import WignerSemicircleDistribution
assert _test_args(WignerSemicircleDistribution(1))
def test_sympy__stats__drv_types__PoissonDistribution():
from sympy.stats.drv_types import PoissonDistribution
assert _test_args(PoissonDistribution(1))
def test_sympy__stats__drv_types__GeometricDistribution():
from sympy.stats.drv_types import GeometricDistribution
assert _test_args(GeometricDistribution(.5))
def test_sympy__core__symbol__Dummy():
from sympy.core.symbol import Dummy
assert _test_args(Dummy('t'))
def test_sympy__core__symbol__Symbol():
from sympy.core.symbol import Symbol
assert _test_args(Symbol('t'))
def test_sympy__core__symbol__Wild():
from sympy.core.symbol import Wild
assert _test_args(Wild('x', exclude=[x]))
@SKIP("abstract class")
def test_sympy__functions__combinatorial__factorials__CombinatorialFunction():
pass
def test_sympy__functions__combinatorial__factorials__FallingFactorial():
from sympy.functions.combinatorial.factorials import FallingFactorial
assert _test_args(FallingFactorial(2, x))
def test_sympy__functions__combinatorial__factorials__MultiFactorial():
from sympy.functions.combinatorial.factorials import MultiFactorial
assert _test_args(MultiFactorial(x))
def test_sympy__functions__combinatorial__factorials__RisingFactorial():
from sympy.functions.combinatorial.factorials import RisingFactorial
assert _test_args(RisingFactorial(2, x))
def test_sympy__functions__combinatorial__factorials__binomial():
from sympy.functions.combinatorial.factorials import binomial
assert _test_args(binomial(2, x))
def test_sympy__functions__combinatorial__factorials__subfactorial():
from sympy.functions.combinatorial.factorials import subfactorial
assert _test_args(subfactorial(1))
def test_sympy__functions__combinatorial__factorials__factorial():
from sympy.functions.combinatorial.factorials import factorial
assert _test_args(factorial(x))
def test_sympy__functions__combinatorial__factorials__factorial2():
from sympy.functions.combinatorial.factorials import factorial2
assert _test_args(factorial2(x))
def test_sympy__functions__combinatorial__numbers__bell():
from sympy.functions.combinatorial.numbers import bell
assert _test_args(bell(x, y))
def test_sympy__functions__combinatorial__numbers__bernoulli():
from sympy.functions.combinatorial.numbers import bernoulli
assert _test_args(bernoulli(x))
def test_sympy__functions__combinatorial__numbers__catalan():
from sympy.functions.combinatorial.numbers import catalan
assert _test_args(catalan(x))
def test_sympy__functions__combinatorial__numbers__euler():
from sympy.functions.combinatorial.numbers import euler
assert _test_args(euler(x))
def test_sympy__functions__combinatorial__numbers__fibonacci():
from sympy.functions.combinatorial.numbers import fibonacci
assert _test_args(fibonacci(x))
def test_sympy__functions__combinatorial__numbers__harmonic():
from sympy.functions.combinatorial.numbers import harmonic
assert _test_args(harmonic(x, 2))
def test_sympy__functions__combinatorial__numbers__lucas():
from sympy.functions.combinatorial.numbers import lucas
assert _test_args(lucas(x))
def test_sympy__functions__elementary__complexes__Abs():
from sympy.functions.elementary.complexes import Abs
assert _test_args(Abs(x))
def test_sympy__functions__elementary__complexes__adjoint():
from sympy.functions.elementary.complexes import adjoint
assert _test_args(adjoint(x))
def test_sympy__functions__elementary__complexes__arg():
from sympy.functions.elementary.complexes import arg
assert _test_args(arg(x))
def test_sympy__functions__elementary__complexes__conjugate():
from sympy.functions.elementary.complexes import conjugate
assert _test_args(conjugate(x))
def test_sympy__functions__elementary__complexes__im():
from sympy.functions.elementary.complexes import im
assert _test_args(im(x))
def test_sympy__functions__elementary__complexes__re():
from sympy.functions.elementary.complexes import re
assert _test_args(re(x))
def test_sympy__functions__elementary__complexes__sign():
from sympy.functions.elementary.complexes import sign
assert _test_args(sign(x))
def test_sympy__functions__elementary__complexes__polar_lift():
from sympy.functions.elementary.complexes import polar_lift
assert _test_args(polar_lift(x))
def test_sympy__functions__elementary__complexes__periodic_argument():
from sympy.functions.elementary.complexes import periodic_argument
assert _test_args(periodic_argument(x, y))
def test_sympy__functions__elementary__complexes__principal_branch():
from sympy.functions.elementary.complexes import principal_branch
assert _test_args(principal_branch(x, y))
def test_sympy__functions__elementary__complexes__transpose():
from sympy.functions.elementary.complexes import transpose
assert _test_args(transpose(x))
def test_sympy__functions__elementary__exponential__LambertW():
from sympy.functions.elementary.exponential import LambertW
assert _test_args(LambertW(2))
@SKIP("abstract class")
def test_sympy__functions__elementary__exponential__ExpBase():
pass
def test_sympy__functions__elementary__exponential__exp():
from sympy.functions.elementary.exponential import exp
assert _test_args(exp(2))
def test_sympy__functions__elementary__exponential__exp_polar():
from sympy.functions.elementary.exponential import exp_polar
assert _test_args(exp_polar(2))
def test_sympy__functions__elementary__exponential__log():
from sympy.functions.elementary.exponential import log
assert _test_args(log(2))
@SKIP("abstract class")
def test_sympy__functions__elementary__hyperbolic__HyperbolicFunction():
pass
def test_sympy__functions__elementary__hyperbolic__acosh():
from sympy.functions.elementary.hyperbolic import acosh
assert _test_args(acosh(2))
def test_sympy__functions__elementary__hyperbolic__acoth():
from sympy.functions.elementary.hyperbolic import acoth
assert _test_args(acoth(2))
def test_sympy__functions__elementary__hyperbolic__asinh():
from sympy.functions.elementary.hyperbolic import asinh
assert _test_args(asinh(2))
def test_sympy__functions__elementary__hyperbolic__atanh():
from sympy.functions.elementary.hyperbolic import atanh
assert _test_args(atanh(2))
def test_sympy__functions__elementary__hyperbolic__cosh():
from sympy.functions.elementary.hyperbolic import cosh
assert _test_args(cosh(2))
def test_sympy__functions__elementary__hyperbolic__coth():
from sympy.functions.elementary.hyperbolic import coth
assert _test_args(coth(2))
def test_sympy__functions__elementary__hyperbolic__sinh():
from sympy.functions.elementary.hyperbolic import sinh
assert _test_args(sinh(2))
def test_sympy__functions__elementary__hyperbolic__tanh():
from sympy.functions.elementary.hyperbolic import tanh
assert _test_args(tanh(2))
@SKIP("does this work at all?")
def test_sympy__functions__elementary__integers__RoundFunction():
from sympy.functions.elementary.integers import RoundFunction
assert _test_args(RoundFunction())
def test_sympy__functions__elementary__integers__ceiling():
from sympy.functions.elementary.integers import ceiling
assert _test_args(ceiling(x))
def test_sympy__functions__elementary__integers__floor():
from sympy.functions.elementary.integers import floor
assert _test_args(floor(x))
def test_sympy__functions__elementary__miscellaneous__IdentityFunction():
from sympy.functions.elementary.miscellaneous import IdentityFunction
assert _test_args(IdentityFunction())
def test_sympy__functions__elementary__miscellaneous__Max():
from sympy.functions.elementary.miscellaneous import Max
assert _test_args(Max(x, 2))
def test_sympy__functions__elementary__miscellaneous__Min():
from sympy.functions.elementary.miscellaneous import Min
assert _test_args(Min(x, 2))
@SKIP("abstract class")
def test_sympy__functions__elementary__miscellaneous__MinMaxBase():
pass
def test_sympy__functions__elementary__piecewise__ExprCondPair():
from sympy.functions.elementary.piecewise import ExprCondPair
assert _test_args(ExprCondPair(1, True))
def test_sympy__functions__elementary__piecewise__Piecewise():
from sympy.functions.elementary.piecewise import Piecewise
assert _test_args(Piecewise((1, x >= 0), (0, True)))
@SKIP("abstract class")
def test_sympy__functions__elementary__trigonometric__TrigonometricFunction():
pass
@SKIP("abstract class")
def test_sympy__functions__elementary__trigonometric__ReciprocalTrigonometricFunction():
pass
@SKIP("abstract class")
def test_sympy__functions__elementary__trigonometric__InverseTrigonometricFunction():
pass
def test_sympy__functions__elementary__trigonometric__acos():
from sympy.functions.elementary.trigonometric import acos
assert _test_args(acos(2))
def test_sympy__functions__elementary__trigonometric__acot():
from sympy.functions.elementary.trigonometric import acot
assert _test_args(acot(2))
def test_sympy__functions__elementary__trigonometric__asin():
from sympy.functions.elementary.trigonometric import asin
assert _test_args(asin(2))
def test_sympy__functions__elementary__trigonometric__asec():
from sympy.functions.elementary.trigonometric import asec
assert _test_args(asec(2))
def test_sympy__functions__elementary__trigonometric__acsc():
from sympy.functions.elementary.trigonometric import acsc
assert _test_args(acsc(2))
def test_sympy__functions__elementary__trigonometric__atan():
from sympy.functions.elementary.trigonometric import atan
assert _test_args(atan(2))
def test_sympy__functions__elementary__trigonometric__atan2():
from sympy.functions.elementary.trigonometric import atan2
assert _test_args(atan2(2, 3))
def test_sympy__functions__elementary__trigonometric__cos():
from sympy.functions.elementary.trigonometric import cos
assert _test_args(cos(2))
def test_sympy__functions__elementary__trigonometric__csc():
from sympy.functions.elementary.trigonometric import csc
assert _test_args(csc(2))
def test_sympy__functions__elementary__trigonometric__cot():
from sympy.functions.elementary.trigonometric import cot
assert _test_args(cot(2))
def test_sympy__functions__elementary__trigonometric__sin():
assert _test_args(sin(2))
def test_sympy__functions__elementary__trigonometric__sec():
from sympy.functions.elementary.trigonometric import sec
assert _test_args(sec(2))
def test_sympy__functions__elementary__trigonometric__tan():
from sympy.functions.elementary.trigonometric import tan
assert _test_args(tan(2))
@SKIP("abstract class")
def test_sympy__functions__special__bessel__BesselBase():
pass
@SKIP("abstract class")
def test_sympy__functions__special__bessel__SphericalBesselBase():
pass
def test_sympy__functions__special__bessel__besseli():
from sympy.functions.special.bessel import besseli
assert _test_args(besseli(x, 1))
def test_sympy__functions__special__bessel__besselj():
from sympy.functions.special.bessel import besselj
assert _test_args(besselj(x, 1))
def test_sympy__functions__special__bessel__besselk():
from sympy.functions.special.bessel import besselk
assert _test_args(besselk(x, 1))
def test_sympy__functions__special__bessel__bessely():
from sympy.functions.special.bessel import bessely
assert _test_args(bessely(x, 1))
def test_sympy__functions__special__bessel__hankel1():
from sympy.functions.special.bessel import hankel1
assert _test_args(hankel1(x, 1))
def test_sympy__functions__special__bessel__hankel2():
from sympy.functions.special.bessel import hankel2
assert _test_args(hankel2(x, 1))
def test_sympy__functions__special__bessel__jn():
from sympy.functions.special.bessel import jn
assert _test_args(jn(0, x))
def test_sympy__functions__special__bessel__yn():
from sympy.functions.special.bessel import yn
assert _test_args(yn(0, x))
def test_sympy__functions__special__bessel__AiryBase():
pass
def test_sympy__functions__special__bessel__airyai():
from sympy.functions.special.bessel import airyai
assert _test_args(airyai(2))
def test_sympy__functions__special__bessel__airybi():
from sympy.functions.special.bessel import airybi
assert _test_args(airybi(2))
def test_sympy__functions__special__bessel__airyaiprime():
from sympy.functions.special.bessel import airyaiprime
assert _test_args(airyaiprime(2))
def test_sympy__functions__special__bessel__airybiprime():
from sympy.functions.special.bessel import airybiprime
assert _test_args(airybiprime(2))
def test_sympy__functions__special__elliptic_integrals__elliptic_k():
from sympy.functions.special.elliptic_integrals import elliptic_k as K
assert _test_args(K(x))
def test_sympy__functions__special__elliptic_integrals__elliptic_f():
from sympy.functions.special.elliptic_integrals import elliptic_f as F
assert _test_args(F(x, y))
def test_sympy__functions__special__elliptic_integrals__elliptic_e():
from sympy.functions.special.elliptic_integrals import elliptic_e as E
assert _test_args(E(x))
assert _test_args(E(x, y))
def test_sympy__functions__special__elliptic_integrals__elliptic_pi():
from sympy.functions.special.elliptic_integrals import elliptic_pi as P
assert _test_args(P(x, y))
assert _test_args(P(x, y, z))
def test_sympy__functions__special__delta_functions__DiracDelta():
from sympy.functions.special.delta_functions import DiracDelta
assert _test_args(DiracDelta(x, 1))
def test_sympy__functions__special__delta_functions__Heaviside():
from sympy.functions.special.delta_functions import Heaviside
assert _test_args(Heaviside(x))
def test_sympy__functions__special__error_functions__erf():
from sympy.functions.special.error_functions import erf
assert _test_args(erf(2))
def test_sympy__functions__special__error_functions__erfc():
from sympy.functions.special.error_functions import erfc
assert _test_args(erfc(2))
def test_sympy__functions__special__error_functions__erfi():
from sympy.functions.special.error_functions import erfi
assert _test_args(erfi(2))
def test_sympy__functions__special__error_functions__erf2():
from sympy.functions.special.error_functions import erf2
assert _test_args(erf2(2, 3))
def test_sympy__functions__special__error_functions__erfinv():
from sympy.functions.special.error_functions import erfinv
assert _test_args(erfinv(2))
def test_sympy__functions__special__error_functions__erfcinv():
from sympy.functions.special.error_functions import erfcinv
assert _test_args(erfcinv(2))
def test_sympy__functions__special__error_functions__erf2inv():
from sympy.functions.special.error_functions import erf2inv
assert _test_args(erf2inv(2, 3))
@SKIP("abstract class")
def test_sympy__functions__special__error_functions__FresnelIntegral():
pass
def test_sympy__functions__special__error_functions__fresnels():
from sympy.functions.special.error_functions import fresnels
assert _test_args(fresnels(2))
def test_sympy__functions__special__error_functions__fresnelc():
from sympy.functions.special.error_functions import fresnelc
assert _test_args(fresnelc(2))
def test_sympy__functions__special__error_functions__erfs():
from sympy.functions.special.error_functions import _erfs
assert _test_args(_erfs(2))
def test_sympy__functions__special__error_functions__Ei():
from sympy.functions.special.error_functions import Ei
assert _test_args(Ei(2))
def test_sympy__functions__special__error_functions__li():
from sympy.functions.special.error_functions import li
assert _test_args(li(2))
def test_sympy__functions__special__error_functions__Li():
from sympy.functions.special.error_functions import Li
assert _test_args(Li(2))
@SKIP("abstract class")
def test_sympy__functions__special__error_functions__TrigonometricIntegral():
pass
def test_sympy__functions__special__error_functions__Si():
from sympy.functions.special.error_functions import Si
assert _test_args(Si(2))
def test_sympy__functions__special__error_functions__Ci():
from sympy.functions.special.error_functions import Ci
assert _test_args(Ci(2))
def test_sympy__functions__special__error_functions__Shi():
from sympy.functions.special.error_functions import Shi
assert _test_args(Shi(2))
def test_sympy__functions__special__error_functions__Chi():
from sympy.functions.special.error_functions import Chi
assert _test_args(Chi(2))
def test_sympy__functions__special__error_functions__expint():
from sympy.functions.special.error_functions import expint
assert _test_args(expint(y, x))
def test_sympy__functions__special__gamma_functions__gamma():
from sympy.functions.special.gamma_functions import gamma
assert _test_args(gamma(x))
def test_sympy__functions__special__gamma_functions__loggamma():
from sympy.functions.special.gamma_functions import loggamma
assert _test_args(loggamma(2))
def test_sympy__functions__special__gamma_functions__lowergamma():
from sympy.functions.special.gamma_functions import lowergamma
assert _test_args(lowergamma(x, 2))
def test_sympy__functions__special__gamma_functions__polygamma():
from sympy.functions.special.gamma_functions import polygamma
assert _test_args(polygamma(x, 2))
def test_sympy__functions__special__gamma_functions__uppergamma():
from sympy.functions.special.gamma_functions import uppergamma
assert _test_args(uppergamma(x, 2))
def test_sympy__functions__special__beta_functions__beta():
from sympy.functions.special.beta_functions import beta
assert _test_args(beta(x, x))
@SKIP("abstract class")
def test_sympy__functions__special__hyper__TupleParametersBase():
pass
@SKIP("abstract class")
def test_sympy__functions__special__hyper__TupleArg():
pass
def test_sympy__functions__special__hyper__hyper():
from sympy.functions.special.hyper import hyper
assert _test_args(hyper([1, 2, 3], [4, 5], x))
def test_sympy__functions__special__hyper__meijerg():
from sympy.functions.special.hyper import meijerg
assert _test_args(meijerg([1, 2, 3], [4, 5], [6], [], x))
@SKIP("abstract class")
def test_sympy__functions__special__hyper__HyperRep():
pass
def test_sympy__functions__special__hyper__HyperRep_power1():
from sympy.functions.special.hyper import HyperRep_power1
assert _test_args(HyperRep_power1(x, y))
def test_sympy__functions__special__hyper__HyperRep_power2():
from sympy.functions.special.hyper import HyperRep_power2
assert _test_args(HyperRep_power2(x, y))
def test_sympy__functions__special__hyper__HyperRep_log1():
from sympy.functions.special.hyper import HyperRep_log1
assert _test_args(HyperRep_log1(x))
def test_sympy__functions__special__hyper__HyperRep_atanh():
from sympy.functions.special.hyper import HyperRep_atanh
assert _test_args(HyperRep_atanh(x))
def test_sympy__functions__special__hyper__HyperRep_asin1():
from sympy.functions.special.hyper import HyperRep_asin1
assert _test_args(HyperRep_asin1(x))
def test_sympy__functions__special__hyper__HyperRep_asin2():
from sympy.functions.special.hyper import HyperRep_asin2
assert _test_args(HyperRep_asin2(x))
def test_sympy__functions__special__hyper__HyperRep_sqrts1():
from sympy.functions.special.hyper import HyperRep_sqrts1
assert _test_args(HyperRep_sqrts1(x, y))
def test_sympy__functions__special__hyper__HyperRep_sqrts2():
from sympy.functions.special.hyper import HyperRep_sqrts2
assert _test_args(HyperRep_sqrts2(x, y))
def test_sympy__functions__special__hyper__HyperRep_log2():
from sympy.functions.special.hyper import HyperRep_log2
assert _test_args(HyperRep_log2(x))
def test_sympy__functions__special__hyper__HyperRep_cosasin():
from sympy.functions.special.hyper import HyperRep_cosasin
assert _test_args(HyperRep_cosasin(x, y))
def test_sympy__functions__special__hyper__HyperRep_sinasin():
from sympy.functions.special.hyper import HyperRep_sinasin
assert _test_args(HyperRep_sinasin(x, y))
@SKIP("abstract class")
def test_sympy__functions__special__polynomials__OrthogonalPolynomial():
pass
def test_sympy__functions__special__polynomials__jacobi():
from sympy.functions.special.polynomials import jacobi
assert _test_args(jacobi(x, 2, 2, 2))
def test_sympy__functions__special__polynomials__gegenbauer():
from sympy.functions.special.polynomials import gegenbauer
assert _test_args(gegenbauer(x, 2, 2))
def test_sympy__functions__special__polynomials__chebyshevt():
from sympy.functions.special.polynomials import chebyshevt
assert _test_args(chebyshevt(x, 2))
def test_sympy__functions__special__polynomials__chebyshevt_root():
from sympy.functions.special.polynomials import chebyshevt_root
assert _test_args(chebyshevt_root(3, 2))
def test_sympy__functions__special__polynomials__chebyshevu():
from sympy.functions.special.polynomials import chebyshevu
assert _test_args(chebyshevu(x, 2))
def test_sympy__functions__special__polynomials__chebyshevu_root():
from sympy.functions.special.polynomials import chebyshevu_root
assert _test_args(chebyshevu_root(3, 2))
def test_sympy__functions__special__polynomials__hermite():
from sympy.functions.special.polynomials import hermite
assert _test_args(hermite(x, 2))
def test_sympy__functions__special__polynomials__legendre():
from sympy.functions.special.polynomials import legendre
assert _test_args(legendre(x, 2))
def test_sympy__functions__special__polynomials__assoc_legendre():
from sympy.functions.special.polynomials import assoc_legendre
assert _test_args(assoc_legendre(x, 0, y))
def test_sympy__functions__special__polynomials__laguerre():
from sympy.functions.special.polynomials import laguerre
assert _test_args(laguerre(x, 2))
def test_sympy__functions__special__polynomials__assoc_laguerre():
from sympy.functions.special.polynomials import assoc_laguerre
assert _test_args(assoc_laguerre(x, 0, y))
def test_sympy__functions__special__spherical_harmonics__Ynm():
from sympy.functions.special.spherical_harmonics import Ynm
assert _test_args(Ynm(1, 1, x, y))
def test_sympy__functions__special__spherical_harmonics__Znm():
from sympy.functions.special.spherical_harmonics import Znm
assert _test_args(Znm(1, 1, x, y))
def test_sympy__functions__special__tensor_functions__LeviCivita():
from sympy.functions.special.tensor_functions import LeviCivita
assert _test_args(LeviCivita(x, y, 2))
def test_sympy__functions__special__tensor_functions__KroneckerDelta():
from sympy.functions.special.tensor_functions import KroneckerDelta
assert _test_args(KroneckerDelta(x, y))
def test_sympy__functions__special__zeta_functions__dirichlet_eta():
from sympy.functions.special.zeta_functions import dirichlet_eta
assert _test_args(dirichlet_eta(x))
def test_sympy__functions__special__zeta_functions__zeta():
from sympy.functions.special.zeta_functions import zeta
assert _test_args(zeta(101))
def test_sympy__functions__special__zeta_functions__lerchphi():
from sympy.functions.special.zeta_functions import lerchphi
assert _test_args(lerchphi(x, y, z))
def test_sympy__functions__special__zeta_functions__polylog():
from sympy.functions.special.zeta_functions import polylog
assert _test_args(polylog(x, y))
def test_sympy__integrals__integrals__Integral():
from sympy.integrals.integrals import Integral
assert _test_args(Integral(2, (x, 0, 1)))
def test_sympy__integrals__risch__NonElementaryIntegral():
from sympy.integrals.risch import NonElementaryIntegral
assert _test_args(NonElementaryIntegral(exp(-x**2), x))
@SKIP("abstract class")
def test_sympy__integrals__transforms__IntegralTransform():
pass
def test_sympy__integrals__transforms__MellinTransform():
from sympy.integrals.transforms import MellinTransform
assert _test_args(MellinTransform(2, x, y))
def test_sympy__integrals__transforms__InverseMellinTransform():
from sympy.integrals.transforms import InverseMellinTransform
assert _test_args(InverseMellinTransform(2, x, y, 0, 1))
def test_sympy__integrals__transforms__LaplaceTransform():
from sympy.integrals.transforms import LaplaceTransform
assert _test_args(LaplaceTransform(2, x, y))
def test_sympy__integrals__transforms__InverseLaplaceTransform():
from sympy.integrals.transforms import InverseLaplaceTransform
assert _test_args(InverseLaplaceTransform(2, x, y, 0))
@SKIP("abstract class")
def test_sympy__integrals__transforms__FourierTypeTransform():
pass
def test_sympy__integrals__transforms__InverseFourierTransform():
from sympy.integrals.transforms import InverseFourierTransform
assert _test_args(InverseFourierTransform(2, x, y))
def test_sympy__integrals__transforms__FourierTransform():
from sympy.integrals.transforms import FourierTransform
assert _test_args(FourierTransform(2, x, y))
@SKIP("abstract class")
def test_sympy__integrals__transforms__SineCosineTypeTransform():
pass
def test_sympy__integrals__transforms__InverseSineTransform():
from sympy.integrals.transforms import InverseSineTransform
assert _test_args(InverseSineTransform(2, x, y))
def test_sympy__integrals__transforms__SineTransform():
from sympy.integrals.transforms import SineTransform
assert _test_args(SineTransform(2, x, y))
def test_sympy__integrals__transforms__InverseCosineTransform():
from sympy.integrals.transforms import InverseCosineTransform
assert _test_args(InverseCosineTransform(2, x, y))
def test_sympy__integrals__transforms__CosineTransform():
from sympy.integrals.transforms import CosineTransform
assert _test_args(CosineTransform(2, x, y))
@SKIP("abstract class")
def test_sympy__integrals__transforms__HankelTypeTransform():
pass
def test_sympy__integrals__transforms__InverseHankelTransform():
from sympy.integrals.transforms import InverseHankelTransform
assert _test_args(InverseHankelTransform(2, x, y, 0))
def test_sympy__integrals__transforms__HankelTransform():
from sympy.integrals.transforms import HankelTransform
assert _test_args(HankelTransform(2, x, y, 0))
@XFAIL
def test_sympy__liealgebras__cartan_type__CartanType_generator():
from sympy.liealgebras.cartan_type import CartanType_generator
assert _test_args(CartanType_generator("A2"))
@XFAIL
def test_sympy__liealgebras__cartan_type__Standard_Cartan():
from sympy.liealgebras.cartan_type import Standard_Cartan
assert _test_args(Standard_Cartan("A", 2))
@XFAIL
def test_sympy__liealgebras__weyl_group__WeylGroup():
from sympy.liealgebras.weyl_group import WeylGroup
assert _test_args(WeylGroup("B4"))
@XFAIL
def test_sympy__liealgebras__root_system__RootSystem():
from sympy.liealgebras.root_system import RootSyStem
assert _test_args(RootSystem("A2"))
@XFAIL
def test_sympy__liealgebras__type_a__TypeA():
from sympy.liealgebras.type_a import TypeA
assert _test_args(TypeA(2))
@XFAIL
def test_sympy__liealgebras__type_b__TypeB():
from sympy.liealgebras.type_b import TypeB
assert _test_args(TypeB(4))
@XFAIL
def test_sympy__liealgebras__type_c__TypeC():
from sympy.liealgebras.type_c import TypeC
assert _test_args(TypeC(4))
@XFAIL
def test_sympy__liealgebras__type_d__TypeD():
from sympy.liealgebras.type_d import TypeD
assert _test_args(TypeD(4))
@XFAIL
def test_sympy__liealgebras__type_e__TypeE():
from sympy.liealgebras.type_e import TypeE
assert _test_args(TypeE(6))
@XFAIL
def test_sympy__liealgebras__type_f__TypeF():
from sympy.liealgebras.type_f import TypeF
assert _test_args(TypeF(4))
@XFAIL
def test_sympy__liealgebras__type_g__TypeG():
from sympy.liealgebras.type_g import TypeG
assert _test_args(TypeG(2))
def test_sympy__logic__boolalg__And():
from sympy.logic.boolalg import And
assert _test_args(And(x, y, 2))
@SKIP("abstract class")
def test_sympy__logic__boolalg__Boolean():
pass
def test_sympy__logic__boolalg__BooleanFunction():
from sympy.logic.boolalg import BooleanFunction
assert _test_args(BooleanFunction(1, 2, 3))
@SKIP("abstract class")
def test_sympy__logic__boolalg__BooleanAtom():
pass
def test_sympy__logic__boolalg__BooleanTrue():
from sympy.logic.boolalg import true
assert _test_args(true)
def test_sympy__logic__boolalg__BooleanFalse():
from sympy.logic.boolalg import false
assert _test_args(false)
def test_sympy__logic__boolalg__Equivalent():
from sympy.logic.boolalg import Equivalent
assert _test_args(Equivalent(x, 2))
def test_sympy__logic__boolalg__ITE():
from sympy.logic.boolalg import ITE
assert _test_args(ITE(x, y, 2))
def test_sympy__logic__boolalg__Implies():
from sympy.logic.boolalg import Implies
assert _test_args(Implies(x, y))
def test_sympy__logic__boolalg__Nand():
from sympy.logic.boolalg import Nand
assert _test_args(Nand(x, y, 2))
def test_sympy__logic__boolalg__Nor():
from sympy.logic.boolalg import Nor
assert _test_args(Nor(x, y))
def test_sympy__logic__boolalg__Not():
from sympy.logic.boolalg import Not
assert _test_args(Not(x))
def test_sympy__logic__boolalg__Or():
from sympy.logic.boolalg import Or
assert _test_args(Or(x, y))
def test_sympy__logic__boolalg__Xor():
from sympy.logic.boolalg import Xor
assert _test_args(Xor(x, y, 2))
def test_sympy__matrices__matrices__DeferredVector():
from sympy.matrices.matrices import DeferredVector
assert _test_args(DeferredVector("X"))
@SKIP("abstract class")
def test_sympy__matrices__expressions__matexpr__MatrixBase():
pass
def test_sympy__matrices__immutable__ImmutableMatrix():
from sympy.matrices.immutable import ImmutableMatrix
assert _test_args(ImmutableMatrix([[1, 2], [3, 4]]))
def test_sympy__matrices__immutable__ImmutableSparseMatrix():
from sympy.matrices.immutable import ImmutableSparseMatrix
assert _test_args(ImmutableSparseMatrix([[1, 2], [3, 4]]))
def test_sympy__matrices__expressions__slice__MatrixSlice():
from sympy.matrices.expressions.slice import MatrixSlice
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', 4, 4)
assert _test_args(MatrixSlice(X, (0, 2), (0, 2)))
def test_sympy__matrices__expressions__blockmatrix__BlockDiagMatrix():
from sympy.matrices.expressions.blockmatrix import BlockDiagMatrix
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, x)
Y = MatrixSymbol('Y', y, y)
assert _test_args(BlockDiagMatrix(X, Y))
def test_sympy__matrices__expressions__blockmatrix__BlockMatrix():
from sympy.matrices.expressions.blockmatrix import BlockMatrix
from sympy.matrices.expressions import MatrixSymbol, ZeroMatrix
X = MatrixSymbol('X', x, x)
Y = MatrixSymbol('Y', y, y)
Z = MatrixSymbol('Z', x, y)
O = ZeroMatrix(y, x)
assert _test_args(BlockMatrix([[X, Z], [O, Y]]))
def test_sympy__matrices__expressions__inverse__Inverse():
from sympy.matrices.expressions.inverse import Inverse
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Inverse(MatrixSymbol('A', 3, 3)))
def test_sympy__matrices__expressions__matadd__MatAdd():
from sympy.matrices.expressions.matadd import MatAdd
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, y)
Y = MatrixSymbol('Y', x, y)
assert _test_args(MatAdd(X, Y))
def test_sympy__matrices__expressions__matexpr__Identity():
from sympy.matrices.expressions.matexpr import Identity
assert _test_args(Identity(3))
@SKIP("abstract class")
def test_sympy__matrices__expressions__matexpr__MatrixExpr():
pass
def test_sympy__matrices__expressions__matexpr__MatrixElement():
from sympy.matrices.expressions.matexpr import MatrixSymbol, MatrixElement
from sympy import S
assert _test_args(MatrixElement(MatrixSymbol('A', 3, 5), S(2), S(3)))
@XFAIL
def test_sympy__matrices__expressions__matexpr__MatrixSymbol():
from sympy.matrices.expressions.matexpr import MatrixSymbol
assert _test_args(MatrixSymbol('A', 3, 5))
def test_sympy__matrices__expressions__matexpr__ZeroMatrix():
from sympy.matrices.expressions.matexpr import ZeroMatrix
assert _test_args(ZeroMatrix(3, 5))
def test_sympy__matrices__expressions__matmul__MatMul():
from sympy.matrices.expressions.matmul import MatMul
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, y)
Y = MatrixSymbol('Y', y, x)
assert _test_args(MatMul(X, Y))
def test_sympy__matrices__expressions__diagonal__DiagonalMatrix():
from sympy.matrices.expressions.diagonal import DiagonalMatrix
from sympy.matrices.expressions import MatrixSymbol
x = MatrixSymbol('x', 10, 1)
assert _test_args(DiagonalMatrix(x))
def test_sympy__matrices__expressions__diagonal__DiagonalOf():
from sympy.matrices.expressions.diagonal import DiagonalOf
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('x', 10, 10)
assert _test_args(DiagonalOf(X))
def test_sympy__matrices__expressions__hadamard__HadamardProduct():
from sympy.matrices.expressions.hadamard import HadamardProduct
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, y)
Y = MatrixSymbol('Y', x, y)
assert _test_args(HadamardProduct(X, Y))
def test_sympy__matrices__expressions__matpow__MatPow():
from sympy.matrices.expressions.matpow import MatPow
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, x)
assert _test_args(MatPow(X, 2))
def test_sympy__matrices__expressions__transpose__Transpose():
from sympy.matrices.expressions.transpose import Transpose
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Transpose(MatrixSymbol('A', 3, 5)))
def test_sympy__matrices__expressions__adjoint__Adjoint():
from sympy.matrices.expressions.adjoint import Adjoint
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Adjoint(MatrixSymbol('A', 3, 5)))
def test_sympy__matrices__expressions__trace__Trace():
from sympy.matrices.expressions.trace import Trace
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Trace(MatrixSymbol('A', 3, 3)))
def test_sympy__matrices__expressions__determinant__Determinant():
from sympy.matrices.expressions.determinant import Determinant
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Determinant(MatrixSymbol('A', 3, 3)))
def test_sympy__matrices__expressions__funcmatrix__FunctionMatrix():
from sympy.matrices.expressions.funcmatrix import FunctionMatrix
from sympy import Lambda, symbols
i, j = symbols('i,j')
assert _test_args(FunctionMatrix(3, 3, Lambda((i, j), i - j) ))
def test_sympy__matrices__expressions__fourier__DFT():
from sympy.matrices.expressions.fourier import DFT
from sympy import S
assert _test_args(DFT(S(2)))
def test_sympy__matrices__expressions__fourier__IDFT():
from sympy.matrices.expressions.fourier import IDFT
from sympy import S
assert _test_args(IDFT(S(2)))
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', 10, 10)
def test_sympy__matrices__expressions__factorizations__LofLU():
from sympy.matrices.expressions.factorizations import LofLU
assert _test_args(LofLU(X))
def test_sympy__matrices__expressions__factorizations__UofLU():
from sympy.matrices.expressions.factorizations import UofLU
assert _test_args(UofLU(X))
def test_sympy__matrices__expressions__factorizations__QofQR():
from sympy.matrices.expressions.factorizations import QofQR
assert _test_args(QofQR(X))
def test_sympy__matrices__expressions__factorizations__RofQR():
from sympy.matrices.expressions.factorizations import RofQR
assert _test_args(RofQR(X))
def test_sympy__matrices__expressions__factorizations__LofCholesky():
from sympy.matrices.expressions.factorizations import LofCholesky
assert _test_args(LofCholesky(X))
def test_sympy__matrices__expressions__factorizations__UofCholesky():
from sympy.matrices.expressions.factorizations import UofCholesky
assert _test_args(UofCholesky(X))
def test_sympy__matrices__expressions__factorizations__EigenVectors():
from sympy.matrices.expressions.factorizations import EigenVectors
assert _test_args(EigenVectors(X))
def test_sympy__matrices__expressions__factorizations__EigenValues():
from sympy.matrices.expressions.factorizations import EigenValues
assert _test_args(EigenValues(X))
def test_sympy__matrices__expressions__factorizations__UofSVD():
from sympy.matrices.expressions.factorizations import UofSVD
assert _test_args(UofSVD(X))
def test_sympy__matrices__expressions__factorizations__VofSVD():
from sympy.matrices.expressions.factorizations import VofSVD
assert _test_args(VofSVD(X))
def test_sympy__matrices__expressions__factorizations__SofSVD():
from sympy.matrices.expressions.factorizations import SofSVD
assert _test_args(SofSVD(X))
@SKIP("abstract class")
def test_sympy__matrices__expressions__factorizations__Factorization():
pass
def test_sympy__physics__vector__frame__CoordinateSym():
from sympy.physics.vector import CoordinateSym
from sympy.physics.vector import ReferenceFrame
assert _test_args(CoordinateSym('R_x', ReferenceFrame('R'), 0))
def test_sympy__physics__paulialgebra__Pauli():
from sympy.physics.paulialgebra import Pauli
assert _test_args(Pauli(1))
def test_sympy__physics__quantum__anticommutator__AntiCommutator():
from sympy.physics.quantum.anticommutator import AntiCommutator
assert _test_args(AntiCommutator(x, y))
def test_sympy__physics__quantum__cartesian__PositionBra3D():
from sympy.physics.quantum.cartesian import PositionBra3D
assert _test_args(PositionBra3D(x, y, z))
def test_sympy__physics__quantum__cartesian__PositionKet3D():
from sympy.physics.quantum.cartesian import PositionKet3D
assert _test_args(PositionKet3D(x, y, z))
def test_sympy__physics__quantum__cartesian__PositionState3D():
from sympy.physics.quantum.cartesian import PositionState3D
assert _test_args(PositionState3D(x, y, z))
def test_sympy__physics__quantum__cartesian__PxBra():
from sympy.physics.quantum.cartesian import PxBra
assert _test_args(PxBra(x, y, z))
def test_sympy__physics__quantum__cartesian__PxKet():
from sympy.physics.quantum.cartesian import PxKet
assert _test_args(PxKet(x, y, z))
def test_sympy__physics__quantum__cartesian__PxOp():
from sympy.physics.quantum.cartesian import PxOp
assert _test_args(PxOp(x, y, z))
def test_sympy__physics__quantum__cartesian__XBra():
from sympy.physics.quantum.cartesian import XBra
assert _test_args(XBra(x))
def test_sympy__physics__quantum__cartesian__XKet():
from sympy.physics.quantum.cartesian import XKet
assert _test_args(XKet(x))
def test_sympy__physics__quantum__cartesian__XOp():
from sympy.physics.quantum.cartesian import XOp
assert _test_args(XOp(x))
def test_sympy__physics__quantum__cartesian__YOp():
from sympy.physics.quantum.cartesian import YOp
assert _test_args(YOp(x))
def test_sympy__physics__quantum__cartesian__ZOp():
from sympy.physics.quantum.cartesian import ZOp
assert _test_args(ZOp(x))
def test_sympy__physics__quantum__cg__CG():
from sympy.physics.quantum.cg import CG
from sympy import S
assert _test_args(CG(S(3)/2, S(3)/2, S(1)/2, -S(1)/2, 1, 1))
def test_sympy__physics__quantum__cg__Wigner3j():
from sympy.physics.quantum.cg import Wigner3j
assert _test_args(Wigner3j(6, 0, 4, 0, 2, 0))
def test_sympy__physics__quantum__cg__Wigner6j():
from sympy.physics.quantum.cg import Wigner6j
assert _test_args(Wigner6j(1, 2, 3, 2, 1, 2))
def test_sympy__physics__quantum__cg__Wigner9j():
from sympy.physics.quantum.cg import Wigner9j
assert _test_args(Wigner9j(2, 1, 1, S(3)/2, S(1)/2, 1, S(1)/2, S(1)/2, 0))
def test_sympy__physics__quantum__circuitplot__Mz():
from sympy.physics.quantum.circuitplot import Mz
assert _test_args(Mz(0))
def test_sympy__physics__quantum__circuitplot__Mx():
from sympy.physics.quantum.circuitplot import Mx
assert _test_args(Mx(0))
def test_sympy__physics__quantum__commutator__Commutator():
from sympy.physics.quantum.commutator import Commutator
A, B = symbols('A,B', commutative=False)
assert _test_args(Commutator(A, B))
def test_sympy__physics__quantum__constants__HBar():
from sympy.physics.quantum.constants import HBar
assert _test_args(HBar())
def test_sympy__physics__quantum__dagger__Dagger():
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.state import Ket
assert _test_args(Dagger(Dagger(Ket('psi'))))
def test_sympy__physics__quantum__gate__CGate():
from sympy.physics.quantum.gate import CGate, Gate
assert _test_args(CGate((0, 1), Gate(2)))
def test_sympy__physics__quantum__gate__CGateS():
from sympy.physics.quantum.gate import CGateS, Gate
assert _test_args(CGateS((0, 1), Gate(2)))
def test_sympy__physics__quantum__gate__CNotGate():
from sympy.physics.quantum.gate import CNotGate
assert _test_args(CNotGate(0, 1))
def test_sympy__physics__quantum__gate__Gate():
from sympy.physics.quantum.gate import Gate
assert _test_args(Gate(0))
def test_sympy__physics__quantum__gate__HadamardGate():
from sympy.physics.quantum.gate import HadamardGate
assert _test_args(HadamardGate(0))
def test_sympy__physics__quantum__gate__IdentityGate():
from sympy.physics.quantum.gate import IdentityGate
assert _test_args(IdentityGate(0))
def test_sympy__physics__quantum__gate__OneQubitGate():
from sympy.physics.quantum.gate import OneQubitGate
assert _test_args(OneQubitGate(0))
def test_sympy__physics__quantum__gate__PhaseGate():
from sympy.physics.quantum.gate import PhaseGate
assert _test_args(PhaseGate(0))
def test_sympy__physics__quantum__gate__SwapGate():
from sympy.physics.quantum.gate import SwapGate
assert _test_args(SwapGate(0, 1))
def test_sympy__physics__quantum__gate__TGate():
from sympy.physics.quantum.gate import TGate
assert _test_args(TGate(0))
def test_sympy__physics__quantum__gate__TwoQubitGate():
from sympy.physics.quantum.gate import TwoQubitGate
assert _test_args(TwoQubitGate(0))
def test_sympy__physics__quantum__gate__UGate():
from sympy.physics.quantum.gate import UGate
from sympy.matrices.immutable import ImmutableMatrix
from sympy import Integer, Tuple
assert _test_args(
UGate(Tuple(Integer(1)), ImmutableMatrix([[1, 0], [0, 2]])))
def test_sympy__physics__quantum__gate__XGate():
from sympy.physics.quantum.gate import XGate
assert _test_args(XGate(0))
def test_sympy__physics__quantum__gate__YGate():
from sympy.physics.quantum.gate import YGate
assert _test_args(YGate(0))
def test_sympy__physics__quantum__gate__ZGate():
from sympy.physics.quantum.gate import ZGate
assert _test_args(ZGate(0))
@SKIP("TODO: sympy.physics")
def test_sympy__physics__quantum__grover__OracleGate():
from sympy.physics.quantum.grover import OracleGate
assert _test_args(OracleGate())
def test_sympy__physics__quantum__grover__WGate():
from sympy.physics.quantum.grover import WGate
assert _test_args(WGate(1))
def test_sympy__physics__quantum__hilbert__ComplexSpace():
from sympy.physics.quantum.hilbert import ComplexSpace
assert _test_args(ComplexSpace(x))
def test_sympy__physics__quantum__hilbert__DirectSumHilbertSpace():
from sympy.physics.quantum.hilbert import DirectSumHilbertSpace, ComplexSpace, FockSpace
c = ComplexSpace(2)
f = FockSpace()
assert _test_args(DirectSumHilbertSpace(c, f))
def test_sympy__physics__quantum__hilbert__FockSpace():
from sympy.physics.quantum.hilbert import FockSpace
assert _test_args(FockSpace())
def test_sympy__physics__quantum__hilbert__HilbertSpace():
from sympy.physics.quantum.hilbert import HilbertSpace
assert _test_args(HilbertSpace())
def test_sympy__physics__quantum__hilbert__L2():
from sympy.physics.quantum.hilbert import L2
from sympy import oo, Interval
assert _test_args(L2(Interval(0, oo)))
def test_sympy__physics__quantum__hilbert__TensorPowerHilbertSpace():
from sympy.physics.quantum.hilbert import TensorPowerHilbertSpace, FockSpace
f = FockSpace()
assert _test_args(TensorPowerHilbertSpace(f, 2))
def test_sympy__physics__quantum__hilbert__TensorProductHilbertSpace():
from sympy.physics.quantum.hilbert import TensorProductHilbertSpace, FockSpace, ComplexSpace
c = ComplexSpace(2)
f = FockSpace()
assert _test_args(TensorProductHilbertSpace(f, c))
def test_sympy__physics__quantum__innerproduct__InnerProduct():
from sympy.physics.quantum import Bra, Ket, InnerProduct
b = Bra('b')
k = Ket('k')
assert _test_args(InnerProduct(b, k))
def test_sympy__physics__quantum__operator__DifferentialOperator():
from sympy.physics.quantum.operator import DifferentialOperator
from sympy import Derivative, Function
f = Function('f')
assert _test_args(DifferentialOperator(1/x*Derivative(f(x), x), f(x)))
def test_sympy__physics__quantum__operator__HermitianOperator():
from sympy.physics.quantum.operator import HermitianOperator
assert _test_args(HermitianOperator('H'))
def test_sympy__physics__quantum__operator__IdentityOperator():
from sympy.physics.quantum.operator import IdentityOperator
assert _test_args(IdentityOperator(5))
def test_sympy__physics__quantum__operator__Operator():
from sympy.physics.quantum.operator import Operator
assert _test_args(Operator('A'))
def test_sympy__physics__quantum__operator__OuterProduct():
from sympy.physics.quantum.operator import OuterProduct
from sympy.physics.quantum import Ket, Bra
b = Bra('b')
k = Ket('k')
assert _test_args(OuterProduct(k, b))
def test_sympy__physics__quantum__operator__UnitaryOperator():
from sympy.physics.quantum.operator import UnitaryOperator
assert _test_args(UnitaryOperator('U'))
def test_sympy__physics__quantum__piab__PIABBra():
from sympy.physics.quantum.piab import PIABBra
assert _test_args(PIABBra('B'))
def test_sympy__physics__quantum__boson__BosonOp():
from sympy.physics.quantum.boson import BosonOp
assert _test_args(BosonOp('a'))
assert _test_args(BosonOp('a', False))
def test_sympy__physics__quantum__boson__BosonFockKet():
from sympy.physics.quantum.boson import BosonFockKet
assert _test_args(BosonFockKet(1))
def test_sympy__physics__quantum__boson__BosonFockBra():
from sympy.physics.quantum.boson import BosonFockBra
assert _test_args(BosonFockBra(1))
def test_sympy__physics__quantum__boson__BosonCoherentKet():
from sympy.physics.quantum.boson import BosonCoherentKet
assert _test_args(BosonCoherentKet(1))
def test_sympy__physics__quantum__boson__BosonCoherentBra():
from sympy.physics.quantum.boson import BosonCoherentBra
assert _test_args(BosonCoherentBra(1))
def test_sympy__physics__quantum__fermion__FermionOp():
from sympy.physics.quantum.fermion import FermionOp
assert _test_args(FermionOp('c'))
assert _test_args(FermionOp('c', False))
def test_sympy__physics__quantum__fermion__FermionFockKet():
from sympy.physics.quantum.fermion import FermionFockKet
assert _test_args(FermionFockKet(1))
def test_sympy__physics__quantum__fermion__FermionFockBra():
from sympy.physics.quantum.fermion import FermionFockBra
assert _test_args(FermionFockBra(1))
def test_sympy__physics__quantum__pauli__SigmaOpBase():
from sympy.physics.quantum.pauli import SigmaOpBase
assert _test_args(SigmaOpBase())
def test_sympy__physics__quantum__pauli__SigmaX():
from sympy.physics.quantum.pauli import SigmaX
assert _test_args(SigmaX())
def test_sympy__physics__quantum__pauli__SigmaY():
from sympy.physics.quantum.pauli import SigmaY
assert _test_args(SigmaY())
def test_sympy__physics__quantum__pauli__SigmaZ():
from sympy.physics.quantum.pauli import SigmaZ
assert _test_args(SigmaZ())
def test_sympy__physics__quantum__pauli__SigmaMinus():
from sympy.physics.quantum.pauli import SigmaMinus
assert _test_args(SigmaMinus())
def test_sympy__physics__quantum__pauli__SigmaPlus():
from sympy.physics.quantum.pauli import SigmaPlus
assert _test_args(SigmaPlus())
def test_sympy__physics__quantum__pauli__SigmaZKet():
from sympy.physics.quantum.pauli import SigmaZKet
assert _test_args(SigmaZKet(0))
def test_sympy__physics__quantum__pauli__SigmaZBra():
from sympy.physics.quantum.pauli import SigmaZBra
assert _test_args(SigmaZBra(0))
def test_sympy__physics__quantum__piab__PIABHamiltonian():
from sympy.physics.quantum.piab import PIABHamiltonian
assert _test_args(PIABHamiltonian('P'))
def test_sympy__physics__quantum__piab__PIABKet():
from sympy.physics.quantum.piab import PIABKet
assert _test_args(PIABKet('K'))
def test_sympy__physics__quantum__qexpr__QExpr():
from sympy.physics.quantum.qexpr import QExpr
assert _test_args(QExpr(0))
def test_sympy__physics__quantum__qft__Fourier():
from sympy.physics.quantum.qft import Fourier
assert _test_args(Fourier(0, 1))
def test_sympy__physics__quantum__qft__IQFT():
from sympy.physics.quantum.qft import IQFT
assert _test_args(IQFT(0, 1))
def test_sympy__physics__quantum__qft__QFT():
from sympy.physics.quantum.qft import QFT
assert _test_args(QFT(0, 1))
def test_sympy__physics__quantum__qft__RkGate():
from sympy.physics.quantum.qft import RkGate
assert _test_args(RkGate(0, 1))
def test_sympy__physics__quantum__qubit__IntQubit():
from sympy.physics.quantum.qubit import IntQubit
assert _test_args(IntQubit(0))
def test_sympy__physics__quantum__qubit__IntQubitBra():
from sympy.physics.quantum.qubit import IntQubitBra
assert _test_args(IntQubitBra(0))
def test_sympy__physics__quantum__qubit__IntQubitState():
from sympy.physics.quantum.qubit import IntQubitState, QubitState
assert _test_args(IntQubitState(QubitState(0, 1)))
def test_sympy__physics__quantum__qubit__Qubit():
from sympy.physics.quantum.qubit import Qubit
assert _test_args(Qubit(0, 0, 0))
def test_sympy__physics__quantum__qubit__QubitBra():
from sympy.physics.quantum.qubit import QubitBra
assert _test_args(QubitBra('1', 0))
def test_sympy__physics__quantum__qubit__QubitState():
from sympy.physics.quantum.qubit import QubitState
assert _test_args(QubitState(0, 1))
def test_sympy__physics__quantum__density__Density():
from sympy.physics.quantum.density import Density
from sympy.physics.quantum.state import Ket
assert _test_args(Density([Ket(0), 0.5], [Ket(1), 0.5]))
@SKIP("TODO: sympy.physics.quantum.shor: Cmod Not Implemented")
def test_sympy__physics__quantum__shor__CMod():
from sympy.physics.quantum.shor import CMod
assert _test_args(CMod())
def test_sympy__physics__quantum__spin__CoupledSpinState():
from sympy.physics.quantum.spin import CoupledSpinState
assert _test_args(CoupledSpinState(1, 0, (1, 1)))
assert _test_args(CoupledSpinState(1, 0, (1, S(1)/2, S(1)/2)))
assert _test_args(CoupledSpinState(
1, 0, (1, S(1)/2, S(1)/2), ((2, 3, S(1)/2), (1, 2, 1)) ))
j, m, j1, j2, j3, j12, x = symbols('j m j1:4 j12 x')
assert CoupledSpinState(
j, m, (j1, j2, j3)).subs(j2, x) == CoupledSpinState(j, m, (j1, x, j3))
assert CoupledSpinState(j, m, (j1, j2, j3), ((1, 3, j12), (1, 2, j)) ).subs(j12, x) == \
CoupledSpinState(j, m, (j1, j2, j3), ((1, 3, x), (1, 2, j)) )
def test_sympy__physics__quantum__spin__J2Op():
from sympy.physics.quantum.spin import J2Op
assert _test_args(J2Op('J'))
def test_sympy__physics__quantum__spin__JminusOp():
from sympy.physics.quantum.spin import JminusOp
assert _test_args(JminusOp('J'))
def test_sympy__physics__quantum__spin__JplusOp():
from sympy.physics.quantum.spin import JplusOp
assert _test_args(JplusOp('J'))
def test_sympy__physics__quantum__spin__JxBra():
from sympy.physics.quantum.spin import JxBra
assert _test_args(JxBra(1, 0))
def test_sympy__physics__quantum__spin__JxBraCoupled():
from sympy.physics.quantum.spin import JxBraCoupled
assert _test_args(JxBraCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JxKet():
from sympy.physics.quantum.spin import JxKet
assert _test_args(JxKet(1, 0))
def test_sympy__physics__quantum__spin__JxKetCoupled():
from sympy.physics.quantum.spin import JxKetCoupled
assert _test_args(JxKetCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JxOp():
from sympy.physics.quantum.spin import JxOp
assert _test_args(JxOp('J'))
def test_sympy__physics__quantum__spin__JyBra():
from sympy.physics.quantum.spin import JyBra
assert _test_args(JyBra(1, 0))
def test_sympy__physics__quantum__spin__JyBraCoupled():
from sympy.physics.quantum.spin import JyBraCoupled
assert _test_args(JyBraCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JyKet():
from sympy.physics.quantum.spin import JyKet
assert _test_args(JyKet(1, 0))
def test_sympy__physics__quantum__spin__JyKetCoupled():
from sympy.physics.quantum.spin import JyKetCoupled
assert _test_args(JyKetCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JyOp():
from sympy.physics.quantum.spin import JyOp
assert _test_args(JyOp('J'))
def test_sympy__physics__quantum__spin__JzBra():
from sympy.physics.quantum.spin import JzBra
assert _test_args(JzBra(1, 0))
def test_sympy__physics__quantum__spin__JzBraCoupled():
from sympy.physics.quantum.spin import JzBraCoupled
assert _test_args(JzBraCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JzKet():
from sympy.physics.quantum.spin import JzKet
assert _test_args(JzKet(1, 0))
def test_sympy__physics__quantum__spin__JzKetCoupled():
from sympy.physics.quantum.spin import JzKetCoupled
assert _test_args(JzKetCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JzOp():
from sympy.physics.quantum.spin import JzOp
assert _test_args(JzOp('J'))
def test_sympy__physics__quantum__spin__Rotation():
from sympy.physics.quantum.spin import Rotation
from sympy import pi
assert _test_args(Rotation(pi, 0, pi/2))
def test_sympy__physics__quantum__spin__SpinState():
from sympy.physics.quantum.spin import SpinState
assert _test_args(SpinState(1, 0))
def test_sympy__physics__quantum__spin__WignerD():
from sympy.physics.quantum.spin import WignerD
assert _test_args(WignerD(0, 1, 2, 3, 4, 5))
def test_sympy__physics__quantum__state__Bra():
from sympy.physics.quantum.state import Bra
assert _test_args(Bra(0))
def test_sympy__physics__quantum__state__BraBase():
from sympy.physics.quantum.state import BraBase
assert _test_args(BraBase(0))
def test_sympy__physics__quantum__state__Ket():
from sympy.physics.quantum.state import Ket
assert _test_args(Ket(0))
def test_sympy__physics__quantum__state__KetBase():
from sympy.physics.quantum.state import KetBase
assert _test_args(KetBase(0))
def test_sympy__physics__quantum__state__State():
from sympy.physics.quantum.state import State
assert _test_args(State(0))
def test_sympy__physics__quantum__state__StateBase():
from sympy.physics.quantum.state import StateBase
assert _test_args(StateBase(0))
def test_sympy__physics__quantum__state__TimeDepBra():
from sympy.physics.quantum.state import TimeDepBra
assert _test_args(TimeDepBra('psi', 't'))
def test_sympy__physics__quantum__state__TimeDepKet():
from sympy.physics.quantum.state import TimeDepKet
assert _test_args(TimeDepKet('psi', 't'))
def test_sympy__physics__quantum__state__TimeDepState():
from sympy.physics.quantum.state import TimeDepState
assert _test_args(TimeDepState('psi', 't'))
def test_sympy__physics__quantum__state__Wavefunction():
from sympy.physics.quantum.state import Wavefunction
from sympy.functions import sin
from sympy import Piecewise, pi
n = 1
L = 1
g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True))
assert _test_args(Wavefunction(g, x))
def test_sympy__physics__quantum__tensorproduct__TensorProduct():
from sympy.physics.quantum.tensorproduct import TensorProduct
assert _test_args(TensorProduct(x, y))
def test_sympy__physics__quantum__identitysearch__GateIdentity():
from sympy.physics.quantum.gate import X
from sympy.physics.quantum.identitysearch import GateIdentity
assert _test_args(GateIdentity(X(0), X(0)))
def test_sympy__physics__quantum__sho1d__SHOOp():
from sympy.physics.quantum.sho1d import SHOOp
assert _test_args(SHOOp('a'))
def test_sympy__physics__quantum__sho1d__RaisingOp():
from sympy.physics.quantum.sho1d import RaisingOp
assert _test_args(RaisingOp('a'))
def test_sympy__physics__quantum__sho1d__LoweringOp():
from sympy.physics.quantum.sho1d import LoweringOp
assert _test_args(LoweringOp('a'))
def test_sympy__physics__quantum__sho1d__NumberOp():
from sympy.physics.quantum.sho1d import NumberOp
assert _test_args(NumberOp('N'))
def test_sympy__physics__quantum__sho1d__Hamiltonian():
from sympy.physics.quantum.sho1d import Hamiltonian
assert _test_args(Hamiltonian('H'))
def test_sympy__physics__quantum__sho1d__SHOState():
from sympy.physics.quantum.sho1d import SHOState
assert _test_args(SHOState(0))
def test_sympy__physics__quantum__sho1d__SHOKet():
from sympy.physics.quantum.sho1d import SHOKet
assert _test_args(SHOKet(0))
def test_sympy__physics__quantum__sho1d__SHOBra():
from sympy.physics.quantum.sho1d import SHOBra
assert _test_args(SHOBra(0))
def test_sympy__physics__secondquant__AnnihilateBoson():
from sympy.physics.secondquant import AnnihilateBoson
assert _test_args(AnnihilateBoson(0))
def test_sympy__physics__secondquant__AnnihilateFermion():
from sympy.physics.secondquant import AnnihilateFermion
assert _test_args(AnnihilateFermion(0))
@SKIP("abstract class")
def test_sympy__physics__secondquant__Annihilator():
pass
def test_sympy__physics__secondquant__AntiSymmetricTensor():
from sympy.physics.secondquant import AntiSymmetricTensor
i, j = symbols('i j', below_fermi=True)
a, b = symbols('a b', above_fermi=True)
assert _test_args(AntiSymmetricTensor('v', (a, i), (b, j)))
def test_sympy__physics__secondquant__BosonState():
from sympy.physics.secondquant import BosonState
assert _test_args(BosonState((0, 1)))
@SKIP("abstract class")
def test_sympy__physics__secondquant__BosonicOperator():
pass
def test_sympy__physics__secondquant__Commutator():
from sympy.physics.secondquant import Commutator
assert _test_args(Commutator(x, y))
def test_sympy__physics__secondquant__CreateBoson():
from sympy.physics.secondquant import CreateBoson
assert _test_args(CreateBoson(0))
def test_sympy__physics__secondquant__CreateFermion():
from sympy.physics.secondquant import CreateFermion
assert _test_args(CreateFermion(0))
@SKIP("abstract class")
def test_sympy__physics__secondquant__Creator():
pass
def test_sympy__physics__secondquant__Dagger():
from sympy.physics.secondquant import Dagger
from sympy import I
assert _test_args(Dagger(2*I))
def test_sympy__physics__secondquant__FermionState():
from sympy.physics.secondquant import FermionState
assert _test_args(FermionState((0, 1)))
def test_sympy__physics__secondquant__FermionicOperator():
from sympy.physics.secondquant import FermionicOperator
assert _test_args(FermionicOperator(0))
def test_sympy__physics__secondquant__FockState():
from sympy.physics.secondquant import FockState
assert _test_args(FockState((0, 1)))
def test_sympy__physics__secondquant__FockStateBosonBra():
from sympy.physics.secondquant import FockStateBosonBra
assert _test_args(FockStateBosonBra((0, 1)))
def test_sympy__physics__secondquant__FockStateBosonKet():
from sympy.physics.secondquant import FockStateBosonKet
assert _test_args(FockStateBosonKet((0, 1)))
def test_sympy__physics__secondquant__FockStateBra():
from sympy.physics.secondquant import FockStateBra
assert _test_args(FockStateBra((0, 1)))
def test_sympy__physics__secondquant__FockStateFermionBra():
from sympy.physics.secondquant import FockStateFermionBra
assert _test_args(FockStateFermionBra((0, 1)))
def test_sympy__physics__secondquant__FockStateFermionKet():
from sympy.physics.secondquant import FockStateFermionKet
assert _test_args(FockStateFermionKet((0, 1)))
def test_sympy__physics__secondquant__FockStateKet():
from sympy.physics.secondquant import FockStateKet
assert _test_args(FockStateKet((0, 1)))
def test_sympy__physics__secondquant__InnerProduct():
from sympy.physics.secondquant import InnerProduct
from sympy.physics.secondquant import FockStateKet, FockStateBra
assert _test_args(InnerProduct(FockStateBra((0, 1)), FockStateKet((0, 1))))
def test_sympy__physics__secondquant__NO():
from sympy.physics.secondquant import NO, F, Fd
assert _test_args(NO(Fd(x)*F(y)))
def test_sympy__physics__secondquant__PermutationOperator():
from sympy.physics.secondquant import PermutationOperator
assert _test_args(PermutationOperator(0, 1))
def test_sympy__physics__secondquant__SqOperator():
from sympy.physics.secondquant import SqOperator
assert _test_args(SqOperator(0))
def test_sympy__physics__secondquant__TensorSymbol():
from sympy.physics.secondquant import TensorSymbol
assert _test_args(TensorSymbol(x))
def test_sympy__physics__units__Unit():
from sympy.physics.units import Unit
assert _test_args(Unit("meter", "m"))
def test_sympy__physics__unitsystems__dimensions__Dimension():
from sympy.physics.unitsystems.dimensions import Dimension
assert _test_args(Dimension(name="length", symbol="L", length=1))
def test_sympy__physics__unitsystems__quantities__Quantity():
from sympy.physics.unitsystems.quantities import Quantity
from sympy.physics.unitsystems.systems import mks
assert _test_args(Quantity(10, mks["m"]))
def test_sympy__physics__unitsystems__units__Constant():
from sympy.physics.unitsystems.units import Constant
from sympy.physics.unitsystems.dimensions import Dimension
length = Dimension(length=1)
assert _test_args(Constant(length, abbrev="u", factor=10))
def test_sympy__physics__unitsystems__units__Unit():
from sympy.physics.unitsystems.units import Unit
from sympy.physics.unitsystems.dimensions import Dimension
length = Dimension(length=1)
assert _test_args(Unit(length, abbrev="u", factor=10))
def test_sympy__core__numbers__AlgebraicNumber():
from sympy.core.numbers import AlgebraicNumber
assert _test_args(AlgebraicNumber(sqrt(2), [1, 2, 3]))
def test_sympy__polys__polytools__GroebnerBasis():
from sympy.polys.polytools import GroebnerBasis
assert _test_args(GroebnerBasis([x, y, z], x, y, z))
def test_sympy__polys__polytools__Poly():
from sympy.polys.polytools import Poly
assert _test_args(Poly(2, x, y))
def test_sympy__polys__polytools__PurePoly():
from sympy.polys.polytools import PurePoly
assert _test_args(PurePoly(2, x, y))
def test_sympy__polys__rootoftools__RootOf():
from sympy.polys.rootoftools import RootOf
assert _test_args(RootOf(x**3 + x + 1, 0))
def test_sympy__polys__rootoftools__RootSum():
from sympy.polys.rootoftools import RootSum
assert _test_args(RootSum(x**3 + x + 1, sin))
def test_sympy__series__limits__Limit():
from sympy.series.limits import Limit
assert _test_args(Limit(x, x, 0, dir='-'))
def test_sympy__series__order__Order():
from sympy.series.order import Order
assert _test_args(Order(1, x, y))
def test_sympy__simplify__hyperexpand__Hyper_Function():
from sympy.simplify.hyperexpand import Hyper_Function
assert _test_args(Hyper_Function([2], [1]))
def test_sympy__simplify__hyperexpand__G_Function():
from sympy.simplify.hyperexpand import G_Function
assert _test_args(G_Function([2], [1], [], []))
def test_sympy__tensor__indexed__Idx():
from sympy.tensor.indexed import Idx
assert _test_args(Idx('test'))
assert _test_args(Idx(1, (0, 10)))
def test_sympy__tensor__indexed__Indexed():
from sympy.tensor.indexed import Indexed, Idx
assert _test_args(Indexed('A', Idx('i'), Idx('j')))
def test_sympy__tensor__indexed__IndexedBase():
from sympy.tensor.indexed import IndexedBase
assert _test_args(IndexedBase('A', shape=(x, y)))
assert _test_args(IndexedBase('A', 1))
assert _test_args(IndexedBase('A')[0, 1])
@XFAIL
def test_sympy__physics__hep__gamma_matrices__GammaMatrixHead():
# This test fails, this class can be reconstructed from the *args
# of an instance using `TensorHead(*args)`
from sympy.physics.hep.gamma_matrices import GammaMatrixHead, Lorentz
from sympy.tensor.tensor import tensor_indices
i = tensor_indices('i', Lorentz)
assert _test_args(GammaMatrixHead())
def test_sympy__tensor__tensor__TensorIndexType():
from sympy.tensor.tensor import TensorIndexType
from sympy import Symbol
assert _test_args(TensorIndexType('Lorentz', metric=False))
def test_sympy__tensor__tensor__TensorSymmetry():
from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorSymmetry, TensorType, get_symmetric_group_sgs
assert _test_args(TensorSymmetry(get_symmetric_group_sgs(2)))
def test_sympy__tensor__tensor__TensorType():
from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, TensorType
Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')
sym = TensorSymmetry(get_symmetric_group_sgs(1))
assert _test_args(TensorType([Lorentz], sym))
def test_sympy__tensor__tensor__TensorHead():
from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, TensorType, get_symmetric_group_sgs, TensorHead
Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')
sym = TensorSymmetry(get_symmetric_group_sgs(1))
S1 = TensorType([Lorentz], sym)
assert _test_args(TensorHead('p', S1, 0))
def test_sympy__tensor__tensor__TensorIndex():
from sympy.tensor.tensor import TensorIndexType, TensorIndex, TensorSymmetry, TensorType, get_symmetric_group_sgs
Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')
assert _test_args(TensorIndex('i', Lorentz))
@SKIP("abstract class")
def test_sympy__tensor__tensor__TensExpr():
pass
def test_sympy__tensor__tensor__TensAdd():
from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, TensorType, get_symmetric_group_sgs, tensor_indices, TensAdd
Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')
a, b = tensor_indices('a,b', Lorentz)
sym = TensorSymmetry(get_symmetric_group_sgs(1))
S1 = TensorType([Lorentz], sym)
p, q = S1('p,q')
t1 = p(a)
t2 = q(a)
assert _test_args(TensAdd(t1, t2))
def test_sympy__tensor__tensor__TensMul():
from sympy.core import S
from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, TensorType, get_symmetric_group_sgs, tensor_indices, TensMul, TIDS
Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')
a, b = tensor_indices('a,b', Lorentz)
sym = TensorSymmetry(get_symmetric_group_sgs(1))
S1 = TensorType([Lorentz], sym)
p = S1('p')
free, dum = TIDS.free_dum_from_indices(a)
assert _test_args(TensMul.from_data(S.One, [p], free, dum))
def test_as_coeff_add():
assert (7, (3*x, 4*x**2)) == (7 + 3*x + 4*x**2).as_coeff_add()
def test_sympy__geometry__curve__Curve():
from sympy.geometry.curve import Curve
assert _test_args(Curve((x, 1), (x, 0, 1)))
def test_sympy__geometry__point__Point():
from sympy.geometry.point import Point
assert _test_args(Point(0, 1))
def test_sympy__geometry__point3d__Point3D():
from sympy.geometry.point3d import Point3D
assert _test_args(Point3D(0, 1, 2))
def test_sympy__geometry__ellipse__Ellipse():
from sympy.geometry.ellipse import Ellipse
assert _test_args(Ellipse((0, 1), 2, 3))
def test_sympy__geometry__ellipse__Circle():
from sympy.geometry.ellipse import Circle
assert _test_args(Circle((0, 1), 2))
@SKIP("abstract class")
def test_sympy__geometry__line__LinearEntity():
pass
def test_sympy__geometry__line__Line():
from sympy.geometry.line import Line
assert _test_args(Line((0, 1), (2, 3)))
def test_sympy__geometry__line__Ray():
from sympy.geometry.line import Ray
assert _test_args(Ray((0, 1), (2, 3)))
def test_sympy__geometry__line__Segment():
from sympy.geometry.line import Segment
assert _test_args(Segment((0, 1), (2, 3)))
@SKIP("abstract class")
def test_sympy__geometry__line3d__LinearEntity3D():
pass
def test_sympy__geometry__line3d__Line3D():
from sympy.geometry.line3d import Line3D
assert _test_args(Line3D((0, 1, 1), (2, 3, 4)))
def test_sympy__geometry__line3d__Segment3D():
from sympy.geometry.line3d import Segment3D
assert _test_args(Segment3D((0, 1, 1), (2, 3, 4)))
def test_sympy__geometry__line3d__Ray3D():
from sympy.geometry.line3d import Ray3D
assert _test_args(Ray3D((0, 1, 1), (2, 3, 4)))
def test_sympy__geometry__plane__Plane():
from sympy.geometry.plane import Plane
assert _test_args(Plane((1, 1, 1), (-3, 4, -2), (1, 2, 3)))
def test_sympy__geometry__polygon__Polygon():
from sympy.geometry.polygon import Polygon
assert _test_args(Polygon((0, 1), (2, 3), (4, 5), (6, 7)))
def test_sympy__geometry__polygon__RegularPolygon():
from sympy.geometry.polygon import RegularPolygon
assert _test_args(RegularPolygon((0, 1), 2, 3, 4))
def test_sympy__geometry__polygon__Triangle():
from sympy.geometry.polygon import Triangle
assert _test_args(Triangle((0, 1), (2, 3), (4, 5)))
def test_sympy__geometry__entity__GeometryEntity():
from sympy.geometry.entity import GeometryEntity
from sympy.geometry.point import Point
assert _test_args(GeometryEntity(Point(1, 0), 1))
@XFAIL
def test_sympy__diffgeom__diffgeom__Manifold():
from sympy.diffgeom import Manifold
assert _test_args(Manifold('name', 3))
@XFAIL
def test_sympy__diffgeom__diffgeom__Patch():
from sympy.diffgeom import Manifold, Patch
assert _test_args(Patch('name', Manifold('name', 3)))
@XFAIL
def test_sympy__diffgeom__diffgeom__CoordSystem():
from sympy.diffgeom import Manifold, Patch, CoordSystem
assert _test_args(CoordSystem('name', Patch('name', Manifold('name', 3))))
@XFAIL
def test_sympy__diffgeom__diffgeom__Point():
from sympy.diffgeom import Manifold, Patch, CoordSystem, Point
assert _test_args(Point(
CoordSystem('name', Patch('name', Manifold('name', 3))), [x, y]))
@XFAIL
def test_sympy__diffgeom__diffgeom__BaseScalarField():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField
cs = CoordSystem('name', Patch('name', Manifold('name', 3)))
assert _test_args(BaseScalarField(cs, 0))
@XFAIL
def test_sympy__diffgeom__diffgeom__BaseVectorField():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField
cs = CoordSystem('name', Patch('name', Manifold('name', 3)))
assert _test_args(BaseVectorField(cs, 0))
def test_sympy__diffgeom__diffgeom__Differential():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential
cs = CoordSystem('name', Patch('name', Manifold('name', 3)))
assert _test_args(Differential(BaseScalarField(cs, 0)))
def test_sympy__diffgeom__diffgeom__Commutator():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, BaseVectorField, Commutator
cs = CoordSystem('name', Patch('name', Manifold('name', 3)))
cs1 = CoordSystem('name1', Patch('name', Manifold('name', 3)))
v = BaseVectorField(cs, 0)
v1 = BaseVectorField(cs1, 0)
assert _test_args(Commutator(v, v1))
def test_sympy__diffgeom__diffgeom__TensorProduct():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, TensorProduct
cs = CoordSystem('name', Patch('name', Manifold('name', 3)))
d = Differential(BaseScalarField(cs, 0))
assert _test_args(TensorProduct(d, d))
def test_sympy__diffgeom__diffgeom__WedgeProduct():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, WedgeProduct
cs = CoordSystem('name', Patch('name', Manifold('name', 3)))
d = Differential(BaseScalarField(cs, 0))
d1 = Differential(BaseScalarField(cs, 1))
assert _test_args(WedgeProduct(d, d1))
def test_sympy__diffgeom__diffgeom__LieDerivative():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, BaseVectorField, LieDerivative
cs = CoordSystem('name', Patch('name', Manifold('name', 3)))
d = Differential(BaseScalarField(cs, 0))
v = BaseVectorField(cs, 0)
assert _test_args(LieDerivative(v, d))
@XFAIL
def test_sympy__diffgeom__diffgeom__BaseCovarDerivativeOp():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseCovarDerivativeOp
cs = CoordSystem('name', Patch('name', Manifold('name', 3)))
assert _test_args(BaseCovarDerivativeOp(cs, 0, [[[0, ]*3, ]*3, ]*3))
def test_sympy__diffgeom__diffgeom__CovarDerivativeOp():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField, CovarDerivativeOp
cs = CoordSystem('name', Patch('name', Manifold('name', 3)))
v = BaseVectorField(cs, 0)
_test_args(CovarDerivativeOp(v, [[[0, ]*3, ]*3, ]*3))
def test_sympy__categories__baseclasses__Class():
from sympy.categories.baseclasses import Class
assert _test_args(Class())
def test_sympy__categories__baseclasses__Object():
from sympy.categories import Object
assert _test_args(Object("A"))
@XFAIL
def test_sympy__categories__baseclasses__Morphism():
from sympy.categories import Object, Morphism
assert _test_args(Morphism(Object("A"), Object("B")))
def test_sympy__categories__baseclasses__IdentityMorphism():
from sympy.categories import Object, IdentityMorphism
assert _test_args(IdentityMorphism(Object("A")))
def test_sympy__categories__baseclasses__NamedMorphism():
from sympy.categories import Object, NamedMorphism
assert _test_args(NamedMorphism(Object("A"), Object("B"), "f"))
def test_sympy__categories__baseclasses__CompositeMorphism():
from sympy.categories import Object, NamedMorphism, CompositeMorphism
A = Object("A")
B = Object("B")
C = Object("C")
f = NamedMorphism(A, B, "f")
g = NamedMorphism(B, C, "g")
assert _test_args(CompositeMorphism(f, g))
def test_sympy__categories__baseclasses__Diagram():
from sympy.categories import Object, NamedMorphism, Diagram, Category
A = Object("A")
B = Object("B")
C = Object("C")
f = NamedMorphism(A, B, "f")
d = Diagram([f])
assert _test_args(d)
def test_sympy__categories__baseclasses__Category():
from sympy.categories import Object, NamedMorphism, Diagram, Category
A = Object("A")
B = Object("B")
C = Object("C")
f = NamedMorphism(A, B, "f")
g = NamedMorphism(B, C, "g")
d1 = Diagram([f, g])
d2 = Diagram([f])
K = Category("K", commutative_diagrams=[d1, d2])
assert _test_args(K)
def test_sympy__ntheory__factor___totient():
from sympy.ntheory.factor_ import totient
k = symbols('k', integer=True)
t = totient(k)
assert _test_args(t)
def test_sympy__ntheory__factor___divisor_sigma():
from sympy.ntheory.factor_ import divisor_sigma
k = symbols('k', integer=True)
n = symbols('n', integer=True)
t = divisor_sigma(n, k)
assert _test_args(t)
def test_sympy__ntheory__residue_ntheory__mobius():
from sympy.ntheory import mobius
assert _test_args(mobius(2))
def test_sympy__physics__optics__waves__TWave():
from sympy.physics.optics import TWave
A, f, phi = symbols('A, f, phi')
assert _test_args(TWave(A, f, phi))
def test_sympy__physics__optics__gaussopt__BeamParameter():
from sympy.physics.optics import BeamParameter
assert _test_args(BeamParameter(530e-9, 1, w=1e-3))
def test_sympy__physics__optics__medium__Medium():
from sympy.physics.optics import Medium
assert _test_args(Medium('m'))
def test_sympy__printing__codeprinter__Assignment():
from sympy.printing.codeprinter import Assignment
assert _test_args(Assignment(x, y))
def test_sympy__vector__coordsysrect__CoordSysCartesian():
from sympy.vector.coordsysrect import CoordSysCartesian
assert _test_args(CoordSysCartesian('C'))
def test_sympy__vector__point__Point():
from sympy.vector.point import Point
assert _test_args(Point('P'))
def test_sympy__vector__basisdependent__BasisDependent():
from sympy.vector.basisdependent import BasisDependent
#These classes have been created to maintain an OOP hierarchy
#for Vectors and Dyadics. Are NOT meant to be initialized
def test_sympy__vector__basisdependent__BasisDependentMul():
from sympy.vector.basisdependent import BasisDependentMul
#These classes have been created to maintain an OOP hierarchy
#for Vectors and Dyadics. Are NOT meant to be initialized
def test_sympy__vector__basisdependent__BasisDependentAdd():
from sympy.vector.basisdependent import BasisDependentAdd
#These classes have been created to maintain an OOP hierarchy
#for Vectors and Dyadics. Are NOT meant to be initialized
def test_sympy__vector__basisdependent__BasisDependentZero():
from sympy.vector.basisdependent import BasisDependentZero
#These classes have been created to maintain an OOP hierarchy
#for Vectors and Dyadics. Are NOT meant to be initialized
def test_sympy__vector__vector__BaseVector():
from sympy.vector.vector import BaseVector
from sympy.vector.coordsysrect import CoordSysCartesian
C = CoordSysCartesian('C')
assert _test_args(BaseVector('Ci', 0, C, ' ', ' '))
def test_sympy__vector__vector__VectorAdd():
from sympy.vector.vector import VectorAdd, VectorMul
from sympy.vector.coordsysrect import CoordSysCartesian
C = CoordSysCartesian('C')
from sympy.abc import a, b, c, x, y, z
v1 = a*C.i + b*C.j + c*C.k
v2 = x*C.i + y*C.j + z*C.k
assert _test_args(VectorAdd(v1, v2))
assert _test_args(VectorMul(x, v1))
def test_sympy__vector__vector__VectorMul():
from sympy.vector.vector import VectorMul
from sympy.vector.coordsysrect import CoordSysCartesian
C = CoordSysCartesian('C')
from sympy.abc import a
assert _test_args(VectorMul(a, C.i))
def test_sympy__vector__vector__VectorZero():
from sympy.vector.vector import VectorZero
assert _test_args(VectorZero())
def test_sympy__vector__vector__Vector():
from sympy.vector.vector import Vector
#Vector is never to be initialized using args
pass
def test_sympy__vector__dyadic__Dyadic():
from sympy.vector.dyadic import Dyadic
#Dyadic is never to be initialized using args
pass
def test_sympy__vector__dyadic__BaseDyadic():
from sympy.vector.dyadic import BaseDyadic
from sympy.vector.coordsysrect import CoordSysCartesian
C = CoordSysCartesian('C')
assert _test_args(BaseDyadic(C.i, C.j))
def test_sympy__vector__dyadic__DyadicMul():
from sympy.vector.dyadic import BaseDyadic, DyadicMul
from sympy.vector.coordsysrect import CoordSysCartesian
C = CoordSysCartesian('C')
assert _test_args(DyadicMul(3, BaseDyadic(C.i, C.j)))
def test_sympy__vector__dyadic__DyadicAdd():
from sympy.vector.dyadic import BaseDyadic, DyadicAdd
from sympy.vector.coordsysrect import CoordSysCartesian
C = CoordSysCartesian('C')
assert _test_args(2 * DyadicAdd(BaseDyadic(C.i, C.i),
BaseDyadic(C.i, C.j)))
def test_sympy__vector__dyadic__DyadicZero():
from sympy.vector.dyadic import DyadicZero
assert _test_args(DyadicZero())
def test_sympy__vector__deloperator__Del():
from sympy.vector.deloperator import Del
from sympy.vector.coordsysrect import CoordSysCartesian
C = CoordSysCartesian('C')
assert _test_args(Del(C))
def test_sympy__vector__orienters__Orienter():
from sympy.vector.orienters import Orienter
#Not to be initialized
def test_sympy__vector__orienters__ThreeAngleOrienter():
from sympy.vector.orienters import ThreeAngleOrienter
#Not to be initialized
def test_sympy__vector__orienters__AxisOrienter():
from sympy.vector.orienters import AxisOrienter
from sympy.vector.coordsysrect import CoordSysCartesian
C = CoordSysCartesian('C')
assert _test_args(AxisOrienter(x, C.i))
def test_sympy__vector__orienters__BodyOrienter():
from sympy.vector.orienters import BodyOrienter
assert _test_args(BodyOrienter(x, y, z, '123'))
def test_sympy__vector__orienters__SpaceOrienter():
from sympy.vector.orienters import SpaceOrienter
assert _test_args(SpaceOrienter(x, y, z, '123'))
def test_sympy__vector__orienters__QuaternionOrienter():
from sympy.vector.orienters import QuaternionOrienter
a, b, c, d = symbols('a b c d')
assert _test_args(QuaternionOrienter(a, b, c, d))
def test_sympy__vector__scalar__BaseScalar():
from sympy.vector.scalar import BaseScalar
from sympy.vector.coordsysrect import CoordSysCartesian
C = CoordSysCartesian('C')
assert _test_args(BaseScalar('Cx', 0, C, ' ', ' '))
| mit | -1,594,203,192,293,846,500 | 30.663691 | 135 | 0.719591 | false |
Bismarrck/tensorflow | tensorflow/contrib/factorization/python/kernel_tests/clustering_ops_test.py | 25 | 7475 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
# ==============================================================================
"""Tests for clustering_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.factorization.python.ops import clustering_ops
from tensorflow.python.platform import test
class KmeansPlusPlusInitializationTest(test.TestCase):
# All but one input point are close to (101, 1). With uniform random sampling,
# it is highly improbable for (-1, -1) to be selected.
def setUp(self):
self._points = np.array([[100., 0.],
[101., 2.],
[102., 0.],
[100., 1.],
[100., 2.],
[101., 0.],
[101., 0.],
[101., 1.],
[102., 0.],
[-1., -1.]]).astype(np.float32)
def runTestWithSeed(self, seed):
with self.cached_session():
sampled_points = clustering_ops.kmeans_plus_plus_initialization(
self._points, 3, seed, (seed % 5) - 1)
self.assertAllClose(
sorted(sampled_points.eval().tolist()), [[-1., -1.],
[101., 1.],
[101., 1.]],
atol=1.0)
def testBasic(self):
for seed in range(100):
self.runTestWithSeed(seed)
class KMC2InitializationTest(test.TestCase):
def runTestWithSeed(self, seed):
with self.cached_session():
distances = np.zeros(1000).astype(np.float32)
distances[6] = 10e7
distances[4] = 10e3
sampled_point = clustering_ops.kmc2_chain_initialization(distances, seed)
self.assertEquals(sampled_point.eval(), 6)
distances[6] = 0.0
sampled_point = clustering_ops.kmc2_chain_initialization(distances, seed)
self.assertEquals(sampled_point.eval(), 4)
def testBasic(self):
for seed in range(100):
self.runTestWithSeed(seed)
class KMC2InitializationLargeTest(test.TestCase):
def setUp(self):
self._distances = np.zeros(1001)
self._distances[500] = 100.0
self._distances[1000] = 50.0
def testBasic(self):
with self.cached_session():
counts = {}
seed = 0
for i in range(50):
sample = clustering_ops.kmc2_chain_initialization(
self._distances, seed + i).eval()
counts[sample] = counts.get(sample, 0) + 1
self.assertEquals(len(counts), 2)
self.assertTrue(500 in counts)
self.assertTrue(1000 in counts)
self.assertGreaterEqual(counts[500], 5)
self.assertGreaterEqual(counts[1000], 5)
class KMC2InitializationCornercaseTest(test.TestCase):
def setUp(self):
self._distances = np.zeros(10)
def runTestWithSeed(self, seed):
with self.cached_session():
sampled_point = clustering_ops.kmc2_chain_initialization(
self._distances, seed)
self.assertEquals(sampled_point.eval(), 0)
def testBasic(self):
for seed in range(100):
self.runTestWithSeed(seed)
# A simple test that can be verified by hand.
class NearestCentersTest(test.TestCase):
def setUp(self):
self._points = np.array([[100., 0.],
[101., 2.],
[99., 2.],
[1., 1.]]).astype(np.float32)
self._centers = np.array([[100., 0.],
[99., 1.],
[50., 50.],
[0., 0.],
[1., 1.]]).astype(np.float32)
def testNearest1(self):
with self.cached_session():
[indices, distances] = clustering_ops.nearest_neighbors(self._points,
self._centers, 1)
self.assertAllClose(indices.eval(), [[0], [0], [1], [4]])
self.assertAllClose(distances.eval(), [[0.], [5.], [1.], [0.]])
def testNearest2(self):
with self.cached_session():
[indices, distances] = clustering_ops.nearest_neighbors(self._points,
self._centers, 2)
self.assertAllClose(indices.eval(), [[0, 1], [0, 1], [1, 0], [4, 3]])
self.assertAllClose(distances.eval(),
[[0., 2.], [5., 5.], [1., 5.], [0., 2.]])
# A test with large inputs.
class NearestCentersLargeTest(test.TestCase):
def setUp(self):
num_points = 1000
num_centers = 2000
num_dim = 100
max_k = 5
# Construct a small number of random points and later tile them.
points_per_tile = 10
assert num_points % points_per_tile == 0
points = np.random.standard_normal(
[points_per_tile, num_dim]).astype(np.float32)
# Construct random centers.
self._centers = np.random.standard_normal(
[num_centers, num_dim]).astype(np.float32)
# Exhaustively compute expected nearest neighbors.
def squared_distance(x, y):
return np.linalg.norm(x - y, ord=2)**2
nearest_neighbors = [
sorted([(squared_distance(point, self._centers[j]), j)
for j in range(num_centers)])[:max_k] for point in points
]
expected_nearest_neighbor_indices = np.array(
[[i for _, i in nn] for nn in nearest_neighbors])
expected_nearest_neighbor_squared_distances = np.array(
[[dist for dist, _ in nn] for nn in nearest_neighbors])
# Tile points and expected results to reach requested size (num_points)
(self._points, self._expected_nearest_neighbor_indices,
self._expected_nearest_neighbor_squared_distances) = (
np.tile(x, (int(num_points / points_per_tile), 1))
for x in (points, expected_nearest_neighbor_indices,
expected_nearest_neighbor_squared_distances))
def testNearest1(self):
with self.cached_session():
[indices, distances] = clustering_ops.nearest_neighbors(self._points,
self._centers, 1)
self.assertAllClose(indices.eval(),
self._expected_nearest_neighbor_indices[:, [0]])
self.assertAllClose(
distances.eval(),
self._expected_nearest_neighbor_squared_distances[:, [0]])
def testNearest5(self):
with self.cached_session():
[indices, distances] = clustering_ops.nearest_neighbors(self._points,
self._centers, 5)
self.assertAllClose(indices.eval(),
self._expected_nearest_neighbor_indices[:, 0:5])
self.assertAllClose(
distances.eval(),
self._expected_nearest_neighbor_squared_distances[:, 0:5])
if __name__ == "__main__":
np.random.seed(0)
test.main()
| apache-2.0 | -4,176,005,034,119,026,700 | 35.463415 | 80 | 0.570569 | false |
robbiet480/python-social-auth | examples/flask_me_example/settings.py | 51 | 2283 | from flask_me_example import app
app.debug = True
SECRET_KEY = 'random-secret-key'
SESSION_COOKIE_NAME = 'psa_session'
DEBUG = False
MONGODB_SETTINGS = {'DB': 'psa_db'}
DEBUG_TB_INTERCEPT_REDIRECTS = False
SESSION_PROTECTION = 'strong'
SOCIAL_AUTH_LOGIN_URL = '/'
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/done/'
SOCIAL_AUTH_USER_MODEL = 'flask_me_example.models.user.User'
SOCIAL_AUTH_AUTHENTICATION_BACKENDS = (
'social.backends.open_id.OpenIdAuth',
'social.backends.google.GoogleOpenId',
'social.backends.google.GoogleOAuth2',
'social.backends.google.GoogleOAuth',
'social.backends.twitter.TwitterOAuth',
'social.backends.yahoo.YahooOpenId',
'social.backends.stripe.StripeOAuth2',
'social.backends.persona.PersonaAuth',
'social.backends.facebook.FacebookOAuth2',
'social.backends.facebook.FacebookAppOAuth2',
'social.backends.yahoo.YahooOAuth',
'social.backends.angel.AngelOAuth2',
'social.backends.behance.BehanceOAuth2',
'social.backends.bitbucket.BitbucketOAuth',
'social.backends.box.BoxOAuth2',
'social.backends.linkedin.LinkedinOAuth',
'social.backends.github.GithubOAuth2',
'social.backends.foursquare.FoursquareOAuth2',
'social.backends.instagram.InstagramOAuth2',
'social.backends.live.LiveOAuth2',
'social.backends.vk.VKOAuth2',
'social.backends.dailymotion.DailymotionOAuth2',
'social.backends.disqus.DisqusOAuth2',
'social.backends.dropbox.DropboxOAuth',
'social.backends.eveonline.EVEOnlineOAuth2',
'social.backends.evernote.EvernoteSandboxOAuth',
'social.backends.fitbit.FitbitOAuth',
'social.backends.flickr.FlickrOAuth',
'social.backends.livejournal.LiveJournalOpenId',
'social.backends.soundcloud.SoundcloudOAuth2',
'social.backends.lastfm.LastFmAuth',
'social.backends.thisismyjam.ThisIsMyJamOAuth1',
'social.backends.stocktwits.StocktwitsOAuth2',
'social.backends.tripit.TripItOAuth',
'social.backends.clef.ClefOAuth2',
'social.backends.twilio.TwilioAuth',
'social.backends.xing.XingOAuth',
'social.backends.yandex.YandexOAuth2',
'social.backends.podio.PodioOAuth2',
'social.backends.reddit.RedditOAuth2',
'social.backends.mineid.MineIDOAuth2',
'social.backends.wunderlist.WunderlistOAuth2',
)
| bsd-3-clause | 6,287,968,014,095,256,000 | 36.42623 | 60 | 0.7477 | false |
futurecolors/suds | tests/jasper.py | 65 | 1659 | # This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# 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 Lesser General Public License for more details at
# ( http://www.gnu.org/licenses/lgpl.html ).
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# written by: Jeff Ortel ( [email protected] )
import sys
sys.path.append('../')
import logging
import traceback as tb
import urllib2
import suds.metrics as metrics
import traceback as tb
from tests import *
from suds import WebFault
from suds.client import Client
errors = 0
setup_logging()
#logging.getLogger('suds.client').setLevel(logging.DEBUG)
def start(url):
print '\n________________________________________________________________\n'
print 'Test @ ( %s )' % url
try:
url = 'http://localhost:9090/jasperserver-pro/services/repository?wsdl'
start(url)
client = Client(url, username='jeff', password='ortel')
print client
print client.service.list('')
except WebFault, f:
errors += 1
print f
print f.fault
except Exception, e:
errors += 1
print e
tb.print_exc()
print '\nFinished: errors = %d' % errors
| lgpl-3.0 | -2,370,564,939,218,539,500 | 29.722222 | 81 | 0.691983 | false |
vaas-krish/openthread | tools/harness-automation/cases/router_9_2_10.py | 16 | 1877 | #!/usr/bin/env python
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
import unittest
from autothreadharness.harness_case import HarnessCase
class Router_9_2_10(HarnessCase):
role = HarnessCase.ROLE_ROUTER
case = '9 2 10'
golden_devices_required = 4
def on_dialog(self, dialog, title):
pass
if __name__ == '__main__':
unittest.main()
| bsd-3-clause | -1,919,293,728,224,491,000 | 42.651163 | 77 | 0.76292 | false |
ActiveState/code | recipes/Python/578272_Topological_Sort/recipe-578272.py | 1 | 1311 | def toposort2(data):
"""Dependencies are expressed as a dictionary whose keys are items
and whose values are a set of dependent items. Output is a list of
sets in topological order. The first set consists of items with no
dependences, each subsequent set consists of items that depend upon
items in the preceeding sets.
>>> print '\\n'.join(repr(sorted(x)) for x in toposort2({
... 2: set([11]),
... 9: set([11,8]),
... 10: set([11,3]),
... 11: set([7,5]),
... 8: set([7,3]),
... }) )
[3, 5, 7]
[8, 11]
[2, 9, 10]
"""
from functools import reduce
# Ignore self dependencies.
for k, v in data.items():
v.discard(k)
# Find all items that don't depend on anything.
extra_items_in_deps = reduce(set.union, data.itervalues()) - set(data.iterkeys())
# Add empty dependences where needed
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item, dep in data.iteritems() if not dep)
if not ordered:
break
yield ordered
data = {item: (dep - ordered)
for item, dep in data.iteritems()
if item not in ordered}
assert not data, "Cyclic dependencies exist among these items:\n%s" % '\n'.join(repr(x) for x in data.iteritems())
| mit | -4,232,482,206,019,321,000 | 33.5 | 118 | 0.613272 | false |
hubert667/AIR | build/kombu/build/lib.linux-i686-2.7/kombu/utils/limits.py | 7 | 1848 | """
kombu.utils.limits
==================
Token bucket implementation for rate limiting.
"""
from __future__ import absolute_import
from kombu.five import monotonic
__all__ = ['TokenBucket']
class TokenBucket(object):
"""Token Bucket Algorithm.
See http://en.wikipedia.org/wiki/Token_Bucket
Most of this code was stolen from an entry in the ASPN Python Cookbook:
http://code.activestate.com/recipes/511490/
.. admonition:: Thread safety
This implementation may not be thread safe.
"""
#: The rate in tokens/second that the bucket will be refilled
fill_rate = None
#: Maximum number of tokensin the bucket.
capacity = 1
#: Timestamp of the last time a token was taken out of the bucket.
timestamp = None
def __init__(self, fill_rate, capacity=1):
self.capacity = float(capacity)
self._tokens = capacity
self.fill_rate = float(fill_rate)
self.timestamp = monotonic()
def can_consume(self, tokens=1):
"""Return :const:`True` if the number of tokens can be consumed
from the bucket."""
if tokens <= self._get_tokens():
self._tokens -= tokens
return True
return False
def expected_time(self, tokens=1):
"""Return the time (in seconds) when a new token is expected
to be available.
This will also consume a token from the bucket.
"""
_tokens = self._get_tokens()
tokens = max(tokens, _tokens)
return (tokens - _tokens) / self.fill_rate
def _get_tokens(self):
if self._tokens < self.capacity:
now = monotonic()
delta = self.fill_rate * (now - self.timestamp)
self._tokens = min(self.capacity, self._tokens + delta)
self.timestamp = now
return self._tokens
| gpl-3.0 | 4,406,822,282,728,687,600 | 26.176471 | 75 | 0.610931 | false |
hamishmb/ddrescue-gui | Tools/DDRescueTools/allversions.py | 1 | 1543 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# DDRescue Tools for all versions in the Tools Package for DDRescue-GUI Version 2.0.0
# This file is part of DDRescue-GUI.
# Copyright (C) 2013-2018 Hamish McIntyre-Bhatty
# DDRescue-GUI is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3 or,
# at your option, any later version.
#
# DDRescue-GUI 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 DDRescue-GUI. If not, see <http://www.gnu.org/licenses/>.
"""
Tools for all versions of ddrescue.
"""
#Do future imports to prepare to support python 3.
#Use unicode strings rather than ASCII strings, as they fix potential problems.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
from . import decorators
#Make unicode an alias for str in Python 3.
if sys.version_info[0] == 3:
unicode = str #pylint: disable=redefined-builtin,invalid-name
@decorators.define_versions
def get_initial_status(split_line):
"""
Function to get ddrescue's initial status.
Works with ddrescue versions: 1.14,1.15,1.16,1.17,1.18,1.19,1.20,1.21,1.22,1.23
"""
return int(split_line[3]), split_line[4]
| gpl-3.0 | -1,624,647,275,907,555,800 | 34.068182 | 85 | 0.736876 | false |
caorong/livestreamer | tests/plugins/testplugin.py | 25 | 1547 | from livestreamer.plugins import Plugin
from livestreamer.options import Options
from livestreamer.stream import *
from livestreamer.plugin.api.support_plugin import testplugin_support
class TestPlugin(Plugin):
options = Options({
"a_option": "default"
})
@classmethod
def can_handle_url(self, url):
return "test.se" in url
def _get_streams(self):
streams = {}
streams["rtmp"] = RTMPStream(self.session, dict(rtmp="rtmp://test.se"))
streams["hls"] = HLSStream(self.session, "http://test.se/playlist.m3u8")
streams["http"] = HTTPStream(self.session, "http://test.se/stream")
streams["akamaihd"] = AkamaiHDStream(self.session, "http://test.se/stream")
streams["240p"] = HTTPStream(self.session, "http://test.se/stream")
streams["360p"] = HTTPStream(self.session, "http://test.se/stream")
streams["1080p"] = HTTPStream(self.session, "http://test.se/stream")
streams["350k"] = HTTPStream(self.session, "http://test.se/stream")
streams["800k"] = HTTPStream(self.session, "http://test.se/stream")
streams["1500k"] = HTTPStream(self.session, "http://test.se/stream")
streams["3000k"] = HTTPStream(self.session, "http://test.se/stream")
streams["480p"] = [HTTPStream(self.session, "http://test.se/stream"),
RTMPStream(self.session, dict(rtmp="rtmp://test.se"))]
streams.update(testplugin_support.get_streams(self.session))
return streams
__plugin__ = TestPlugin
| bsd-2-clause | -3,315,691,411,885,909,500 | 38.666667 | 83 | 0.64318 | false |
dvliman/jaikuengine | .google_appengine/lib/django-1.5/django/utils/encoding.py | 4 | 9165 | from __future__ import unicode_literals
import codecs
import datetime
from decimal import Decimal
import locale
try:
from urllib.parse import quote
except ImportError: # Python 2
from urllib import quote
import warnings
from django.utils.functional import Promise
from django.utils import six
class DjangoUnicodeDecodeError(UnicodeDecodeError):
def __init__(self, obj, *args):
self.obj = obj
UnicodeDecodeError.__init__(self, *args)
def __str__(self):
original = UnicodeDecodeError.__str__(self)
return '%s. You passed in %r (%s)' % (original, self.obj,
type(self.obj))
class StrAndUnicode(object):
"""
A class that derives __str__ from __unicode__.
On Python 2, __str__ returns the output of __unicode__ encoded as a UTF-8
bytestring. On Python 3, __str__ returns the output of __unicode__.
Useful as a mix-in. If you support Python 2 and 3 with a single code base,
you can inherit this mix-in and just define __unicode__.
"""
def __init__(self, *args, **kwargs):
warnings.warn("StrAndUnicode is deprecated. Define a __str__ method "
"and apply the @python_2_unicode_compatible decorator "
"instead.", PendingDeprecationWarning, stacklevel=2)
super(StrAndUnicode, self).__init__(*args, **kwargs)
if six.PY3:
def __str__(self):
return self.__unicode__()
else:
def __str__(self):
return self.__unicode__().encode('utf-8')
def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if not six.PY3:
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass
def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Returns a text object representing 's' -- unicode on Python 2 and str on
Python 3. Treats bytestrings using the 'encoding' codec.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if isinstance(s, Promise):
# The input is the result of a gettext_lazy() call.
return s
return force_text(s, encoding, strings_only, errors)
def is_protected_type(obj):
"""Determine if the object instance is of a protected type.
Objects of protected types are preserved as-is when passed to
force_text(strings_only=True).
"""
return isinstance(obj, six.integer_types + (type(None), float, Decimal,
datetime.datetime, datetime.date, datetime.time))
def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_text, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case first, saves 30-40% when s is an instance of
# six.text_type. This function gets called often in that setting.
if isinstance(s, six.text_type):
return s
if strings_only and is_protected_type(s):
return s
try:
if not isinstance(s, six.string_types):
if hasattr(s, '__unicode__'):
s = s.__unicode__()
else:
if six.PY3:
if isinstance(s, bytes):
s = six.text_type(s, encoding, errors)
else:
s = six.text_type(s)
else:
s = six.text_type(bytes(s), encoding, errors)
else:
# Note: We use .decode() here, instead of six.text_type(s, encoding,
# errors), so that if s is a SafeBytes, it ends up being a
# SafeText at the end.
s = s.decode(encoding, errors)
except UnicodeDecodeError as e:
if not isinstance(s, Exception):
raise DjangoUnicodeDecodeError(s, *e.args)
else:
# If we get to here, the caller has passed in an Exception
# subclass populated with non-ASCII bytestring data without a
# working unicode method. Try to handle this without raising a
# further exception by individually forcing the exception args
# to unicode.
s = ' '.join([force_text(arg, encoding, strings_only,
errors) for arg in s])
return s
def smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if isinstance(s, Promise):
# The input is the result of a gettext_lazy() call.
return s
return force_bytes(s, encoding, strings_only, errors)
def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if isinstance(s, bytes):
if encoding == 'utf-8':
return s
else:
return s.decode('utf-8', errors).encode(encoding, errors)
if strings_only and (s is None or isinstance(s, int)):
return s
if isinstance(s, Promise):
return six.text_type(s).encode(encoding, errors)
if not isinstance(s, six.string_types):
try:
if six.PY3:
return six.text_type(s).encode(encoding)
else:
return bytes(s)
except UnicodeEncodeError:
if isinstance(s, Exception):
# An Exception subclass containing non-ASCII data that doesn't
# know how to print itself properly. We shouldn't raise a
# further exception.
return b' '.join([force_bytes(arg, encoding, strings_only,
errors) for arg in s])
return six.text_type(s).encode(encoding, errors)
else:
return s.encode(encoding, errors)
if six.PY3:
smart_str = smart_text
force_str = force_text
else:
smart_str = smart_bytes
force_str = force_bytes
# backwards compatibility for Python 2
smart_unicode = smart_text
force_unicode = force_text
smart_str.__doc__ = """\
Apply smart_text in Python 3 and smart_bytes in Python 2.
This is suitable for writing to sys.stdout (for instance).
"""
force_str.__doc__ = """\
Apply force_text in Python 3 and force_bytes in Python 2.
"""
def iri_to_uri(iri):
"""
Convert an Internationalized Resource Identifier (IRI) portion to a URI
portion that is suitable for inclusion in a URL.
This is the algorithm from section 3.1 of RFC 3987. However, since we are
assuming input is either UTF-8 or unicode already, we can simplify things a
little from the full method.
Returns an ASCII string containing the encoded result.
"""
# The list of safe characters here is constructed from the "reserved" and
# "unreserved" characters specified in sections 2.2 and 2.3 of RFC 3986:
# reserved = gen-delims / sub-delims
# gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
# sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
# / "*" / "+" / "," / ";" / "="
# unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
# Of the unreserved characters, urllib.quote already considers all but
# the ~ safe.
# The % character is also added to the list of safe characters here, as the
# end of section 3.1 of RFC 3987 specifically mentions that % must not be
# converted.
if iri is None:
return iri
return quote(force_bytes(iri), safe=b"/#%[]=:;$&()+,!?*@'~")
def filepath_to_uri(path):
"""Convert a file system path to a URI portion that is suitable for
inclusion in a URL.
We are assuming input is either UTF-8 or unicode already.
This method will encode certain chars that would normally be recognized as
special chars for URIs. Note that this method does not encode the '
character, as it is a valid character within URIs. See
encodeURIComponent() JavaScript function for more details.
Returns an ASCII string containing the encoded result.
"""
if path is None:
return path
# I know about `os.sep` and `os.altsep` but I want to leave
# some flexibility for hardcoding separators.
return quote(force_bytes(path.replace("\\", "/")), safe=b"/~!*()'")
# The encoding of the default system locale but falls back to the
# given fallback encoding if the encoding is unsupported by python or could
# not be determined. See tickets #10335 and #5846
try:
DEFAULT_LOCALE_ENCODING = locale.getdefaultlocale()[1] or 'ascii'
codecs.lookup(DEFAULT_LOCALE_ENCODING)
except:
DEFAULT_LOCALE_ENCODING = 'ascii'
| apache-2.0 | -1,548,998,234,296,606,500 | 36.561475 | 80 | 0.619313 | false |
TheTimmy/spack | var/spack/repos/builtin/packages/libszip/package.py | 3 | 2068 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# 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 terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Libszip(AutotoolsPackage):
"""Szip is an implementation of the extended-Rice lossless
compression algorithm.
It provides lossless compression of scientific data, and is
provided with HDF software products.
"""
homepage = "https://support.hdfgroup.org/doc_resource/SZIP/"
url = "https://support.hdfgroup.org/ftp/lib-external/szip/2.1.1/src/szip-2.1.1.tar.gz"
list_url = "https://support.hdfgroup.org/ftp/lib-external/szip"
list_depth = 2
provides('szip')
version('2.1.1', 'dd579cf0f26d44afd10a0ad7291fc282')
version('2.1', '902f831bcefb69c6b635374424acbead')
def configure_args(self):
return [
'--enable-production',
'--enable-shared',
'--enable-static',
'--enable-encoding',
]
| lgpl-2.1 | -3,492,386,258,225,179,600 | 38.769231 | 95 | 0.658124 | false |
chickonice/AutonomousFlight | apm_ws/build/catkin_generated/generate_cached_setup.py | 1 | 1486 | # -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import os
import stat
import sys
# find the import for catkin's python package - either from source space or from an installed underlay
if os.path.exists(os.path.join('/opt/ros/indigo/share/catkin/cmake', 'catkinConfig.cmake.in')):
sys.path.insert(0, os.path.join('/opt/ros/indigo/share/catkin/cmake', '..', 'python'))
try:
from catkin.environment_cache import generate_environment_script
except ImportError:
# search for catkin package in all workspaces and prepend to path
for workspace in "/home/odroid/Documents/AutonomousFlight/apm_ws/devel;/home/odroid/Documents/AutonomousFlight/final_ws/devel;/home/odroid/Documents/AutonomousFlight/apriltags_ws/devel;/opt/ros/indigo".split(';'):
python_path = os.path.join(workspace, 'lib/python2.7/dist-packages')
if os.path.isdir(os.path.join(python_path, 'catkin')):
sys.path.insert(0, python_path)
break
from catkin.environment_cache import generate_environment_script
code = generate_environment_script('/home/odroid/Documents/AutonomousFlight/apm_ws/devel/env.sh')
output_filename = '/home/odroid/Documents/AutonomousFlight/apm_ws/build/catkin_generated/setup_cached.sh'
with open(output_filename, 'w') as f:
#print('Generate script for cached setup "%s"' % output_filename)
f.write('\n'.join(code))
mode = os.stat(output_filename).st_mode
os.chmod(output_filename, mode | stat.S_IXUSR)
| gpl-3.0 | 8,973,257,408,228,105,000 | 48.533333 | 217 | 0.734859 | false |
derrowap/DNC-TensorFlow | src/dnc/external_memory.py | 1 | 11075 | """External Memory used in a DNC for read and writes.
This External Memory is implemented as defined in the DNC architecture
in DeepMind's Nature paper:
http://www.nature.com/nature/journal/vaop/ncurrent/full/nature20101.html
Author: Austin Derrow-Pinion
"""
import collections
import tensorflow as tf
import sonnet as snt
# Ensure values are greater than epsilon to avoid numerical instability.
_EPSILON = 1e-6
ExternalMemoryState = collections.namedtuple('ExternalMemoryState', (
'memory'))
class ExternalMemory(snt.RNNCore):
"""External Memory for the DNC to read and write to.
In a content based addressing read mode, a DNC read head compares
a read vector to the contents stored in this External Memory. This
similarity is computed using cosine similarity in the DNC paper.
A write head writes to external memory in a DNC through first an
erase operation and then an adding operation. The erase operation
adds an erase vector across each memory slot and is then followed
by adding the write vector to memory.
"""
def __init__(self,
memory_size=16,
word_size=16,
name='external_memory'):
"""Initialize External Memory used in a DNC.
Args:
memory_size: The number of memory slots (N in the DNC paper).
Default value is 16.
word_size: The width of each memory slot (W in the DNC paper).
Default value is 16.
name: The name of the module (default 'external_memory').
"""
super(ExternalMemory, self).__init__(name=name)
self._memory_size = memory_size
self._word_size = word_size
self._state_size = ExternalMemoryState(
memory=tf.TensorShape([self._memory_size, self._word_size]))
def _build(self,
read_keys,
read_strengths,
write_weightings,
erase_vector,
write_vector,
prev_state):
"""Compute one timestep of computation for the External Memory.
Args:
read_keys: A Tensor of shape `[batch_size, num_reads, word_size]`
containing the read keys from the Read Head originally emitted
by the DNC controller. These are compared to each slot in the
external memory for content based addressing. Represented as
`k_t^{r,i}` in the DNC paper for the read keys at time `t`
and read head `i`.
read_strengths: A Tensor of shape `[batch_size, num_reads]`
containing the key strength at which the `c_t` vector should
be heightened in value. The values are bound to the interval
[1, inf). Represented in the DNC paper as `beta_t^{r,i}` for
time `t` with the ith read head.
write_weightings: A Tensor of shape `[batch_size, memory_size]`
containing the write weightings for external memory write
operation. If `write_weighting[,i]` is high, then that means
the ith slot in external memory should be written to the value
in `write_vector[i]` much more than if the value was low.
Represented as w_t^w in the DNC paper for write weightings
at time `t`.
erase_vector: A Tensor of shape `[batch_size, word_size]` with
the weights to erase from external memory. If
`erase_vector[,i]` is high then the ith word in each slot of
external memory will be erased more than if the value was
smaller. Represented as `e_t` in the DNC paper for the erase
vector at time `t`.
write_vector: A Tensor of shape `[batch_size, word_size]` with
the values to write in memory. This vector was directly
emitted from the DNC controller. Represented as `v_t` in the
DNC paper for the write vector at time `t`.
prev_state: An instance of `ExternalMemoryState` containing the
previous state of this External Memory.
Returns:
A tuple `(output, next_state)`. Where `output` is a Tensor of the
content based addressing weightings. The `next_state` is an
instance of `ExternalMemoryState` representing the next state of
this External Memory after computation finishes.
"""
# content adressing weightings
c_t = self.content_weights(
read_keys, read_strengths, prev_state.memory)
# write to memory
memory = self.write(
write_weightings, erase_vector, write_vector, prev_state.memory)
return (c_t, ExternalMemoryState(memory=memory))
def content_weights(self, read_keys, read_strengths, memory):
"""Calculate content based addressing weights, c_t.
Content based addressing starts with calculating the cosine similarity
between the input read keys and the current state of memory. The
content vector, `c_t`, at time `t` is outputed by taking the softmax of
the product between the cosine similarity and the input read strengths.
Cosine similarity here is defined as in the DNC paper:
D(u, v) = (u * v) / (|u| * |v|)
The resulting similarity ranges from -1 meaning exactly opposite, to
1 meaning exactly the same.
Args:
read_keys: A Tensor of shape `[batch_size, num_reads, word_size]`
containing the read keys from the Read Head originally emitted
by the DNC controller. These are compared to each slot in the
external memory for content based addressing.
read_strengths: A Tensor of shape `[batch_size, num_reads]`
containing the key strength at which the `c_t` vector should
be heightened in value. The values are bound to the interval
[1, inf). Represented in the DNC paper as `beta_t^{r,i}` for
time `t` with the ith read head.
memory: A Tensor of shape `[batch_size, memory_size, word_size]`
containing the data of the external memory.
Returns:
A Tensor of shape `[batch_size, num_reads, memory_size]` with the
content weights for each of the num_reads many read heads.
"""
# Sneaky way of doing batched dot product between read_keys and memory.
# Each read key, k_t^{r,i}, is element-wise multiplied against each row
# of memory and summed together (definition of dot product). This
# outputs a Tensor of size `[batch_size, num_reads, memory_size]`.
dot = tf.matmul(read_keys, memory, transpose_b=True)
# Euclidean norms
read_keys_norm = tf.norm(
read_keys, ord='euclidean', axis=2, keep_dims=True)
memory_norm = tf.norm(memory, ord='euclidean', axis=2, keep_dims=True)
norm = tf.matmul(read_keys_norm, memory_norm, transpose_b=True)
# similarity of each read key vector from each read head in every batch
content_similarity = dot / (norm + tf.constant(_EPSILON))
# Content weighting is a softmax of the content similarity.
# The product of content_similarity and read_strenghts uses
# broadcasting to handle unequal Tensor shapes.
return tf.nn.softmax(tf.multiply(content_similarity,
tf.expand_dims(read_strengths, 2)))
def write(self, write_weightings, erase_vector, write_vector, memory):
"""Write to external memory through en erase then add operation.
The write operation to external memory consists of two parts: erase
operation, add operation.
Let `M_t(i)` be the external memory matrix contents of slot `i` at time
`t`. Let `w_t(i)` be the write weightings vector at time `t` for the
slot `i` in external memory. Let `e_t` be the erase vector at time `t`.
Let `v_t` be the write vector at time `t` that is added to memory.
Erase Operation:
M_t'(i) = M_{t-1}(i) * (1 - w_t(i) * e_t)
Add Operation:
M_t(i) = M_t'(i) + w_t(i) * v_t
Args:
write_weightings: A Tensor of shape `[batch_size, memory_size]`
containing the write weightings for external memory write
operation. If `write_weighting[,i]` is high, then that means
the ith slot in external memory should be written to the value
in `write_vector[i]` much more than if the value was low.
Represented as w_t^w in the DNC paper for write weightings
at time `t`.
erase_vector: A Tensor of shape `[batch_size, word_size]` with
the weights to erase from external memory. If
`erase_vector[,i]` is high then the ith word in each slot of
external memory will be erased more than if the value was
smaller. Represented as `e_t` in the DNC paper for the erase
vector at time `t`.
write_vector: A Tensor of shape `[batch_size, word_size]` with
the values to write in memory. This vector was directly
emitted from the DNC controller. Represented as `v_t` in the
DNC paper for the write vector at time `t`.
memory: A Tensor of shape `[batch_size, memory_size, word_size]`
containing the data of the external memory.
Returns:
A Tensor of shape `[batch_size, memory_size, word_size]` containing
the contents of memory after writing for each batch.
"""
# Tensor of shape `[batch_size, memory_size, 1]`
write_weightings_expanded = tf.expand_dims(write_weightings, 2)
# Tensor of shape `[batch_size, 1, word_size]`
erase_vector_expanded = tf.expand_dims(erase_vector, 1)
# Product is Tensor of shape `[batch_size, memory_size, word_size]`
weighted_erase_vector = tf.matmul(write_weightings_expanded,
erase_vector_expanded)
# Erase memory
erased_memory = tf.multiply(memory, 1 - weighted_erase_vector)
# Tensor of shape `[batch_size, 1, word_size]`
write_vector_expanded = tf.expand_dims(write_vector, 1)
# Product is Tensor of shape `[batch_size, memory_size, word_size]`
weighted_write_vector = tf.matmul(write_weightings_expanded,
write_vector_expanded)
# Write to memory
written_memory = tf.add(erased_memory, weighted_write_vector)
return written_memory
@property
def state_size(self):
"""Return a description of the state size."""
return self._state_size
@property
def output_size(self):
"""Return the output shape."""
return tf.TensorShape([self._memory_size])
| mit | 5,558,887,863,217,535,000 | 46.943723 | 79 | 0.614537 | false |
abpoms/google-api-cpp-client | prepare_dependencies.py | 1 | 42463 | #!/usr/bin/python
# Copyright 2013 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.
"""Prepares dependencies for Google APIs Client Library for C++.
This *might* download, configure, build, and install the libraries we
depend on in whole or part. It is almost always not exactly you really
want, because each of the dependencies releases on their own cycle,
faster than this script will track them. For the most repeatable build
process, developers should manually pull the individual packages from
their respective repositories, inspect their licenses, add them to their
local revision control, and integrate into their build system.
Since this script is only marginally maintained, if it does not work for
you, your best options is to install the required components by hand.
Usage:
By default, with no args, this will run turnkey doing whatever is needed.
The provided options let you fine tune running specific packages. For
example, if you need to upgrade a dependency or build again.
To force a dependency to rebuild, use --force.
[-b] Just build the dependent packages in the --download_dir
[-d] Just download the dependent packages to the --download_dir
[-i] Just install the dependencies to the --install_dir
[--force] Ignore any previous results and force the request from scratch.
[--download_dir=<path>] Specifies the download_dir.
The default path is ./external_dependencies.
[--install_dir=<path>] Specifies the install_dir.
The default path is ./external_dependencies/install.
[cmake|curl|gflags|glog|gmock]* Process just the specific subset.
If you wish to obtain and build a newer (or older) version of
a dependency, simply change the url in this file and run this
script again on that name with the --force flag.
"""
import getopt
import glob
import os
import stat
import platform
import shutil
import subprocess
import sys
import tarfile
import urllib
import ssl
import zipfile
COMPILED_MARKER = '_built'
INSTALLED_MARKER = '_installed'
CONFIGURED_MARKER = '_configured'
CYGWIN_PLATFORM = 'cygwin'
WINDOWS_PLATFORM = 'windows'
OSX_PLATFORM = 'osx'
LINUX_PLATFORM = 'Linux'
VS_COMPILER = 'VisualStudio'
GCC_COMPILER = 'gcc'
AUTO_CONFIG = 'auto'
CONFIGURE_CONFIG = 'configure'
CMAKE_CONFIG = 'cmake'
class ConfigInfo(object):
"""Configuration information for how to build the dependencies."""
def __init__(self, abs_root_dir, unused_argv):
"""Initialize Configuration Information.
Args:
abs_root_dir: (sring) The path tot he build root directory.
unused_argv: (string) The program arguments, including argv[0].
"""
self._abs_root_dir = '%s' % abs_root_dir
self._download_packages = False
self._build_packages = False
self._install_packages = False
self._force = False
self._download_dir = os.path.join(abs_root_dir, 'external_dependencies')
self._abs_install_dir = '%s' % os.path.join(
os.getcwd(), os.path.join('external_dependencies', 'install'))
self._compiler = GCC_COMPILER
if os.name == 'nt':
self._port_name = WINDOWS_PLATFORM
self._compiler = VS_COMPILER
elif platform.system().startswith('CYGWIN'):
self._port_name = CYGWIN_PLATFORM
elif platform.system() == 'Darwin':
self._port_name = OSX_PLATFORM
elif platform.system() == 'Linux':
self._port_name = LINUX_PLATFORM
else:
print 'Unknown system = %s. Assuming it is Linux compatible.' % (
platform.system())
self._port_name = LINUX_PLATFORM
return
def SetOptions(self, options):
"""Sets custom options.
Args:
options: (list[string, string]) name, value pairs of options given
"""
do_all = True
for opt, arg in options:
if opt == '-b':
do_all = False
self._build_packages = True
elif opt == '-d':
do_all = False
self._download_packages = True
elif opt == '-i':
do_all = False
self._install_packages = True
elif opt == '--force':
self._force = True
elif opt == '--download_dir':
self._download_dir = arg
elif opt == '--install_dir':
if arg.startswith('/'):
self._abs_install_dir = '%s' % arg
else:
self._abs_install_dir = os.path.join('%s' % os.getcwd(), arg)
if do_all:
self._build_packages = True
self._download_packages = True
self._install_packages = True
if self._build_packages:
print ' Build packages = True'
if self._download_packages:
print ' Download packages = True'
if self._install_packages:
print ' Installing packages = True'
if self._download_packages:
print ' Downloading files to %s' % self._download_dir
if not os.path.exists(self._download_dir):
os.makedirs(self._download_dir)
if self._install_packages:
print ' Installing packages to %s' % self._abs_install_dir
if not os.path.exists(os.path.join(self._abs_install_dir, 'lib')):
os.makedirs(os.path.join(self._abs_install_dir, 'lib'))
if not os.path.exists(os.path.join(self._abs_install_dir, 'include')):
os.makedirs(os.path.join(self._abs_install_dir, 'include'))
@property
def build_packages(self):
"""Returns whether we wwant to compile the packages."""
return self._build_packages
@property
def download_packages(self):
"""Returns whether we wwant to download the packages."""
return self._download_packages
@property
def install_packages(self):
"""Returns whether we wwant to install the packages."""
return self._install_packages
@property
def compiler(self):
"""Returns the name of the compiler we prefer."""
return self._compiler
@property
def port(self):
"""Returns the name of the platform we are preparing."""
return self._port_name
@property
def make_command(self):
"""A tuple of (make_program_path, make_argument_list) for using Make."""
if os.name == 'nt':
program = 'nmake'
args = '/C'
else:
program = 'make'
args = ''
return (program, args)
@property
def cmake_command(self):
"""A tuple of (cmake_program_path, cmake_argument_list) for using CMake."""
if self._port_name == WINDOWS_PLATFORM:
program = 'cmake'
args = '-G "NMake Makefiles"'
elif self._port_name == CYGWIN_PLATFORM:
program = 'cmake'
args = '-G "Unix Makefiles"'
else:
program = os.path.join(self._abs_install_dir, 'bin', 'cmake')
args = ''
return (program, args)
@property
def force(self):
"""Force all the work to be done again."""
return self._force
@property
def download_dir(self):
"""The directory that we'll download and build external packages in."""
return self._download_dir
@property
def abs_install_dir(self):
"""The root directory for the external dependency installation dir."""
return self._abs_install_dir
@property
def abs_root_dir(self):
"""The root directory for the Google APIs for C++ sources."""
return self._abs_root_dir
def _DownloadStatusHook(a, b, c):
"""Shows progress of download."""
print '% 3.1f%% of %d bytes\r' % (min(100, float(a * b) / c * 100), c)
class PackageInstaller(object):
"""Acquires, builds, and installs an individual package for use in the SDK.
"""
def __init__(self, config, url,
make_target='all',
package_name='',
config_type=AUTO_CONFIG,
extra_configure_flags=''):
"""Initializes for the individual package located at the given URL.
Args:
config: (Installer) The installer contains configuration info.
url: (string) The url to install.
make_target: (string) The make target to use when compiling.
package_name: (string) Explicit package name if different than
indicated by the URL's archive.
config_type: (string) Specifies how this package is configured.
extra_configure_flags: (string) Nonstandard flags for ./configure
"""
self._config = config
self._url = url
self._config_type = config_type
self._extra_configure_flags = extra_configure_flags
self._extra_cppflags = ''
self._extra_ldflags = ''
self._make_target = make_target
self._archive_file = os.path.split(url)[1]
if not package_name:
package_name = PackageInstaller._ArchiveToPackage(self._archive_file)
self._package_name = package_name
self._package_path = os.path.join(config.download_dir,
self._package_name)
self._vc_project_path = ''
self._vc_upgrade_from_project_path = ''
self._msbuild_args = ''
def UpgradeVisualStudio(self, from_project, to_project):
"""Upgrades visual studio project.
Args:
from_project: (string) The path of the project to convert from.
to_project: (string) The path of the project to convert to.
(conversion might be in-place).
"""
if from_project == to_project or not os.path.exists(to_project):
print '>>> Upgrading %s' % from_project
upgrade_cmd = 'devenv "%s" /upgrade' % from_project
PackageInstaller.RunOrDie(
upgrade_cmd, 'Devenv failed to upgrade project.')
def Download(self):
"""Downloads URL to file in configured download_dir."""
config = self._config
url = self._url
filename = self._archive_file
download_dir = config.download_dir
download_path = os.path.join(download_dir, filename)
if os.path.exists(download_path) and not config.force:
print '%s already exists - skipping download from %s' % (filename, url)
return
print 'Downloading %s from %s: ' % (filename, url)
try:
if sys.version_info >= (2, 7, 9):
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
urllib.urlretrieve(url, download_path, _DownloadStatusHook,
context=context)
else:
urllib.urlretrieve(url, download_path, _DownloadStatusHook)
except IOError:
print ('\nERROR:\n'
'Could not download %s.\n' % url
+ ('It could be that this particular version is no longer'
' available.\n'
'Check the site where the url is coming from.\n'
'If there is a more recent version then:\n'
' 1) Edit this script to change the old url to the new one.\n'
' 2) Run the script again.\n'
' It will pick up where it left off, using the new url.'
'\n'))
sys.exit(1)
def MaybeTweakAfterUnpackage(self):
"""Extra stuff to do after unpackaging an archive."""
config = self._config
if config.compiler == VS_COMPILER and self._vc_upgrade_from_project_path:
proj_dir = os.path.split(self._vc_project_path)[0]
marker = os.path.join(proj_dir, '_upgraded_vc')
if os.path.exists(self._vc_project_path) and config.force:
if self._vc_upgrade_from_project_path != self._vc_project_path:
os.unlink(self._vc_project_path)
if os.path.exists(marker):
os.unlink(marker)
if (not os.path.exists(self._vc_project_path)
or self._vc_project_path == self._vc_upgrade_from_project_path):
self.UpgradeVisualStudio(self._vc_upgrade_from_project_path,
self._vc_project_path)
open(marker, 'w').close()
def Unpackage(self):
"""Unpackages the archive into the package if needed."""
config = self._config
download_dir = config.download_dir
archive_filename = self._archive_file
package = self._package_name
os.chdir(download_dir)
if not os.path.exists(archive_filename):
print '%s does not exist in %s' % (
archive_filename, config.download_dir)
sys.exit(1)
if os.path.exists(self._package_name):
if not config.force:
self.MaybeTweakAfterUnpackage()
return
print 'Removing existing %s' % self._package_name
shutil.rmtree(self._package_name)
print '\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'
print '>>> Unpacking %s into %s' % (archive_filename, package)
if archive_filename.endswith('zip'):
z = zipfile.ZipFile(archive_filename)
for elem in z.namelist():
dirname, filename = os.path.split(elem)
if not os.path.exists(dirname):
os.makedirs(dirname)
if filename:
with open(elem, 'w') as f:
f.write(z.read(elem))
z.close()
elif archive_filename.endswith('.bz2'):
try:
subprocess.call('tar -xjf %s' % archive_filename, shell=True)
except OSError:
print 'Failed to unpack %s' % archive_filename
sys.exit(-1)
else:
try:
tar = tarfile.open(archive_filename)
tar.extractall()
tar.close()
except IOError:
try:
subprocess.call('tar -xf %s' % archive_filename, shell=True)
except OSError:
print 'Failed to unpack %s' % archive_filename
sys.exit(-1)
self.MaybeTweakAfterUnpackage()
print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'
def DetermineConfigType(self, path):
"""Detemines how to configure the directory depending on files.
Args:
path: (string) The path to be configured.
Returns:
The method to use for configuring the package.
"""
if self._vc_project_path and self._config.compiler == VS_COMPILER:
return None
if os.path.exists(os.path.join(path, 'CMakeLists.txt')):
return CMAKE_CONFIG
if os.path.exists(os.path.join(path, 'configure')):
return CONFIGURE_CONFIG
if os.path.exists(os.path.join(path, 'Configure')):
return CONFIGURE_CONFIG
print 'Could not determine how to configure %s' % path
sys.exit(1)
def Configure(self):
"""Configure the package."""
config = self._config
os.chdir(self._package_path)
marker_path = CONFIGURED_MARKER
if os.path.exists(marker_path):
if not config.force:
print '%s already configured' % self._package_name
return
# remove built since we are forcing a rebuild
os.unlink(marker_path)
config_type = self._config_type
if config_type == AUTO_CONFIG:
config_type = self.DetermineConfigType('.')
if not config_type:
pass
elif config_type == CMAKE_CONFIG:
configure_cmd = '%s %s' % (
config.cmake_command[0], config.cmake_command[1])
prefix_arg = '-DCMAKE_INSTALL_PREFIX:PATH="%s" .' % (
config.abs_install_dir)
elif config_type == CONFIGURE_CONFIG:
# Normally the automake uses a script called 'configure'
# but for some reason openssl calls it 'Configure'.
configure_cmd = os.path.join('.', 'configure')
if not os.path.exists(configure_cmd):
configure_cmd = os.path.join('.', 'Configure')
configure_cmd = "bash " + configure_cmd
prefix_arg = '--prefix="%s" %s' % (
config.abs_install_dir, self._extra_configure_flags)
if not config_type:
cmd = None
elif config.port == WINDOWS_PLATFORM:
cmd = '%s %s' % (configure_cmd, prefix_arg)
else:
ldflags = '-L%s/lib %s' % (
config.abs_install_dir, self._extra_ldflags)
cppflags = '-I%s/include %s' % (
config.abs_install_dir, self._extra_cppflags)
cmd = 'LDFLAGS="%s" CPPFLAGS="%s" LIBS="-ldl" %s %s' % (
ldflags, cppflags, configure_cmd, prefix_arg)
if cmd:
PackageInstaller.RunOrDie(
cmd, 'Failed to configure %s' % self._package_name)
# touch file so we know we configured it.
open(marker_path, 'w').close()
print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'
print '>>> Finished configuring %s' % self._package_name
print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n'
def Compile(self):
"""Compiles a package but does not install it."""
package_name = self._package_name
config = self._config
os.chdir(self._package_path)
marker_path = COMPILED_MARKER
if os.path.exists(marker_path):
if not config.force:
print '%s already built' % package_name
return
# remove built since we are forcing a rebuild
os.unlink(marker_path)
PackageInstaller._VerifyMakeOrDie(config.make_command[0])
print '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
print '+++ Building %s [%s]' % (package_name, self._make_target)
print '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
if self._vc_project_path and config.compiler == VS_COMPILER:
dirname, filename = os.path.split(self._vc_project_path)
os.chdir(dirname)
make_cmd = 'msbuild "%s" %s' % (filename, self._msbuild_args)
else:
make_cmd = '%s %s %s' % (
config.make_command[0], config.make_command[1], self._make_target)
PackageInstaller.RunOrDie(make_cmd, 'Failed to make %s' % package_name)
# touch file so we know we built it.
open(marker_path, 'w').close()
print '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
print '+++ Finished building %s' % package_name
print '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n'
def Install(self):
"""Installs a pre-built package using a make-rule."""
self.MakeInstall()
def MakeInstall(self):
"""Installs a pre-built package, including ones we built ourself."""
package_name = self._package_name
config = self._config
os.chdir(self._package_path)
marker_path = INSTALLED_MARKER
if os.path.exists(marker_path):
if not config.force:
print '%s already installed' % package_name
return
# remove built since we are forcing an install
os.unlink(marker_path)
PackageInstaller._VerifyMakeOrDie(config.make_command[0])
print '\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
print '+++ Installing %s' % package_name
print '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
cmd = '%s %s install' % config.make_command
PackageInstaller.RunOrDie(cmd, 'Failed to install %s' % package_name)
# touch file so we know we installed it.
open(marker_path, 'w').close()
print '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
print '+++ Finished installing %s' % package_name
print '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
def Process(self):
"""Runs standard workflow to obatin and prepare dependencies."""
config = self._config
if config.download_packages:
self.Download()
if config.build_packages or config.install_packages:
self.Unpackage()
if config.build_packages or config.install_packages:
self.Configure()
if config.build_packages:
self.Compile()
if config.install_packages:
self.Install()
@classmethod
def CopyAllFiles(cls, from_dir, to_dir):
"""Copies one directory tree into another.
Args:
from_dir: (string) The directory to copy from.
to_dir: (string) The directory to copy to.
"""
for elem in glob.glob(os.path.join(from_dir, '*')):
tail = os.path.split(elem)[1]
if os.path.isdir(elem):
targetdir = os.path.join(to_dir, tail)
if not os.path.exists(targetdir):
os.makedirs(targetdir)
PackageInstaller.CopyAllFiles(elem, targetdir)
else:
targetfile = os.path.join(to_dir, tail)
shutil.copyfile(elem, targetfile)
shutil.copystat(elem, targetfile)
@classmethod
def RunOrDie(cls, cmd, error_msg):
"""Runs system command. Dies if the command fails.
Args:
cmd: (string) Command to execute.
error_msg: (string) Optional additional error to print on failure.
"""
try:
print '>>> Executing [%s] in %s' % (cmd, os.getcwd())
ok = os.system(cmd) == 0
except OSError:
ok = False
if not ok:
print 'Failed command: [%s] in %s' % (cmd, os.getcwd())
if error_msg:
print ' %s' % error_msg
sys.exit(1)
@classmethod
def _ArchiveToPackage(cls, archive):
"""Return the package name for a given archive.
Usually this is the archive name stripped of the .tar.gz or .zip suffix.
Args:
archive: (string) A tar or zip file.
Returns:
The package name of the archive strips the .tar.gz or .zip extension.
"""
for suffix in ['.tar.gz', '.zip', '.tgz', '.tar.bz2']:
if archive.endswith(suffix):
return archive[0:len(archive) - len(suffix)]
print 'Unhandled archive=%s' % archive
sys.exit(1)
@classmethod
def _VerifyCMakeOrDie(cls, cmake_program):
"""Verifies that CMake is on the path or exits.
Args:
cmake_program: (string) The cmake program to check for.
"""
if not cls._VerifyProgram(cmake_program, '--version'):
print('Could not find "cmake" on your PATH. '
'Try running this script again with the arguments '
'"-di cmake".\n'
'Then try building and installing again.')
exit(1)
@classmethod
def _VerifyMakeOrDie(cls, make_program):
"""Verifies that the make_program variable is on the path or exits.
Args:
make_program: (string) The make program to check for.
"""
install_instructions = ''
args = '--version'
if os.name == 'nt':
args = '/C /HELP'
install_instructions = (
'If you are using Visual Studio, try running the vcvars.bat script '
' for the version of Visual Studio you wish to use. '
' For 64-bit Visual Studio 11.0 this is something like '
' C:\\"Program Files (x86)"\\"Microsoft Visual Studio 11.0"'
'\\VC\\bin\\x86_amd64\\vcvars64.bat')
if not cls._VerifyProgram(make_program, args):
print('Make sure that "%s" is in your path. %s' % (
make_program, install_instructions))
exit(1)
@classmethod
def _VerifyProgram(cls, prog, args):
"""Verify the program exists on the path.
Args:
prog: (string) The name of the program to check.
args: (string) args to give program when running it.
Returns:
True if program is on PATH, False otherwise.
"""
try:
test = '%s %s' % (prog, args)
subprocess.Popen(test, stdout=subprocess.PIPE, shell=True)
except OSError:
return False
return True
class MongoosePackageInstaller(PackageInstaller):
"""Custom installer for the Mongoose package."""
def __init__(self, config, url):
"""Standard PackageInstaller initializer."""
super(MongoosePackageInstaller, self).__init__(config, url)
self._config_type = CMAKE_CONFIG
self._package_path = os.path.join(self._config.download_dir, 'mongoose')
def MaybeTweakAfterUnpackage(self):
"""Creates a CMakeLists.txt file for building the package."""
config = self._config
cmakelists_path = os.path.join(self._package_path, 'CMakeLists.txt')
if config.force and os.path.exists(cmakelists_path):
os.unlink(cmakelists_path)
if os.path.exists(cmakelists_path):
return
# Mongoose just builds a server, and does so nonstandard.
# We want a library. There's only one file so pretty simple.
print '>>> Creating CMakeLists.txt as %s' % cmakelists_path
with open(cmakelists_path, 'w') as f:
f.write('cmake_minimum_required (VERSION 2.6)\n')
f.write('project (Mongoose)\n')
f.write('add_library(mongoose STATIC mongoose.c)\n')
f.write('add_definitions( -DNO_CGI -U__STDC_FORMAT_MACROS )\n')
def Install(self):
"""Copies headers and libraries to install the package."""
config = self._config
include_dir = os.path.join(config.abs_install_dir, 'include', 'mongoose')
if not os.path.exists(include_dir):
os.makedirs(include_dir)
shutil.copy(os.path.join(self._package_path, 'mongoose.h'), include_dir)
libdir = os.path.join(config.abs_install_dir, 'lib')
if not os.path.exists(libdir):
os.makedirs(libdir)
if config.port != WINDOWS_PLATFORM:
shutil.copy(os.path.join(self._package_path, 'libmongoose.a'), libdir)
else:
for ext in ['lib', 'pdb']:
shutil.copy(os.path.join(self._package_path, 'mongoose.%s' % ext),
libdir)
class JsonCppPackageInstaller(PackageInstaller):
"""Custom installer for the JsonCpp package."""
def __init__(self, config, url):
"""Standard PackageInstaller initializer."""
super(JsonCppPackageInstaller, self).__init__(config, url)
self._config_type = CMAKE_CONFIG
def MaybeTweakAfterUnpackage(self):
"""Creates a CMakeLists.txt to build the package."""
config = self._config
os.chdir(self._package_path)
if config.force and os.path.exists('CMakeLists.txt'):
os.unlink('CMakeLists.txt')
if os.path.exists('CMakeLists.txt'):
return
if config.build_packages:
allfiles = ''
src_path = os.path.join('src', 'lib_json')
for elem in glob.glob('%s/*.cpp' % src_path):
allfiles = '%s "%s"' % (allfiles, elem)
print '>>> Creating CMakeLists.txt'
with open('CMakeLists.txt', 'w') as f:
f.write('cmake_minimum_required (VERSION 2.6)\n')
f.write('project (JsonCpp)\n')
f.write('INCLUDE_DIRECTORIES(./include src/lib_json)\n')
f.write('add_library(jsoncpp STATIC %s)\n' % allfiles)
def Install(self):
"""Copies the libraries nad header files to install the package."""
config = self._config
print '>>> Installing %s' % self._package_name
PackageInstaller.CopyAllFiles(
os.path.join(self._package_path, 'include'),
os.path.join(config.abs_install_dir, 'include'))
libdir = os.path.join(config.abs_install_dir, 'lib')
if not os.path.exists(libdir):
os.makedirs(libdir)
if config.port != WINDOWS_PLATFORM:
shutil.copy('libjsoncpp.a', libdir)
else:
for ext in ['lib', 'pdb']:
shutil.copy('jsoncpp.%s' % ext, libdir)
class CMakeExeInstaller(PackageInstaller):
"""Installs CMake under Windows from initialization executable."""
def __init__(self, config, url):
"""Standard PackageInstaller initializer."""
super(CMakeExeInstaller, self).__init__(config, url, package_name='ignore')
def Unpackage(self):
return
def Configure(self):
return
def Compile(self):
return
def Install(self):
"""Runs installer to install CMake (on the system)."""
config = self._config
if not config.force:
if PackageInstaller._VerifyProgram('cmake', '--version'):
print 'Already have CMake'
return
print 'Installing CMake'
download_dir = config.download_dir
exe_filename = self._archive_file
os.chdir(download_dir)
# This is a self-installing .exe file
PackageInstaller.RunOrDie(
exe_filename, 'Failed to install CMake from %s.' % exe_filename)
class IgnorePackageInstaller(PackageInstaller):
"""This package initializer does nothing."""
def __init__(self, config, url):
"""Standard PackageInstaller initializer."""
super(IgnorePackageInstaller, self).__init__(
config, url, package_name='ignore')
def Download(self):
return
def Unpackage(self):
return
def Configure(self):
return
def Compile(self):
return
def Install(self):
return
class OpenSslPackageInstaller(PackageInstaller):
"""Custom installer for the OpenSsl package."""
def __init__(self, config, url):
"""Standard PackageInstaller initializer."""
super(OpenSslPackageInstaller, self).__init__(config, url)
if config.port == OSX_PLATFORM:
self._extra_configure_flags = 'darwin64-x86_64-cc'
elif platform.system() == 'Linux':
self._extra_configure_flags = 'linux-%s' % platform.machine()
else:
self._extra_configure_flags = 'gcc'
def Configure(self):
# TODO(user): 20130626
# These artifacts are probably not even needed. Investigate for a
# future release.
print 'NOTE for Google APIs Client Library for C++ Installer:'
print ' If this fails it might be because we guessed the wrong platform.'
print ' Edit prepare_dependencies.py and notify us.'
print ' See the README in the release for contact information.'
super(OpenSslPackageInstaller, self).Configure()
class GFlagsPackageInstaller(PackageInstaller):
"""Custom installer for the GFlags package."""
def __init__(self, config, url, package_name=''):
"""Standard PackageInstaller initializer."""
super(GFlagsPackageInstaller, self).__init__(
config, url, package_name=package_name)
self._archive_file = self._archive_file.replace('-no-svn-files', '')
self._package_name = self._package_name.replace('-no-svn-files', '')
self._package_path = self._package_path.replace('-no-svn-files', '')
self._msbuild_args = '/p:Configuration=Release;Platform=x86'
self._vc_upgrade_from_project_path = (
'%s\\vsprojects\\libgflags\\libgflags.vcproj' % self._package_path)
self._vc_project_path = self._vc_upgrade_from_project_path.replace(
'.vcproj', '.vcxproj')
def Install(self):
"""Copis generated libs and headers into the install directory."""
config = self._config
if config.compiler != VS_COMPILER:
super(GFlagsPackageInstaller, self).Install()
return
print '>>> Installing %s' % self._package_name
install_libdir = os.path.join(config.abs_install_dir, 'lib')
install_includedir = os.path.join(config.abs_install_dir,
'include', 'gflags')
if not os.path.exists(install_libdir):
os.makedirs(install_libdir)
if not os.path.exists(install_includedir):
os.makedirs(install_includedir)
release_dir = os.path.join(self._package_path,
'vsprojects', 'libgflags', 'Release')
for ext in ['lib', 'dll', 'pdb']:
print 'renaming %s.%s' % (os.path.join(release_dir, 'libgflags'), ext)
shutil.copyfile(
'%s.%s' % (os.path.join(release_dir, 'libgflags'), ext),
'%s.%s' % (os.path.join(install_libdir, 'libgflags'), ext))
class GMockPackageInstaller(PackageInstaller):
"""Custom installer for the GMock package."""
def __init__(self, config, url):
"""Standard PackageInstaller initializer.
Args:
config: (ConfigInfo) Configuration information.
url: (string) The URL to download from.
"""
super(GMockPackageInstaller, self).__init__(config, url)
def MaybeTweakAfterUnpackage(self):
if self._config.compiler == VS_COMPILER:
# But this wont actually build in visual studio because VC11 changed the
# default number of variadic template parameters from 10 to 5 and we
# need 10. So patch the build flags to force 10
cmake_utils_path = os.path.join(
self._package_path, 'gtest', 'cmake', 'internal_utils.cmake')
with open(cmake_utils_path, 'r') as f:
text = f.read()
inject_flags = '-D_VARIADIC_MAX=10'
if text.find(inject_flags) < 0:
insert_after = '-DSTRICT -DWIN32_LEAN_AND_MEAN'
text = text.replace(insert_after, '%s %s' % (
insert_after, inject_flags))
with open(cmake_utils_path, 'w') as f:
f.write(text)
gtest_port_h = os.path.join(
self._package_path, 'gtest', 'include',
'gtest', 'internal', 'gtest-port.h')
with open(gtest_port_h, 'r') as f:
text = f.read()
text = text.replace(
'# define GTEST_HAS_PTHREAD ('
'GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX)',
'# define GTEST_HAS_PTHREAD ('
'GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_CYGWIN)')
with open(gtest_port_h, 'w') as f:
f.write(text)
def Configure(self):
return
def Compile(self):
return
def Install(self):
# GMock needs to be installed in the build tree (i.e. the root_dir/src
# because that's what it wants.
gmock_path = os.path.join(self._config.abs_root_dir, 'src', 'gmock')
if self._config.force and os.path.exists(gmock_path):
shutil.rmtree(gmock_path)
if os.path.exists(gmock_path):
return
shutil.copytree(self._package_path, gmock_path)
class GLogPackageInstaller(PackageInstaller):
"""Custom installer for the GLog package."""
def __init__(self, config, url, package_name=''):
"""Standard PackageInstaller initializer.
Args:
config: (ConfigInfo) Configuration information.
url: (string) The URL to download from.
"""
super(GLogPackageInstaller, self).__init__(
config, url, package_name=package_name)
self._msbuild_args = '/p:Configuration=Release;Platform=x86'
self._vc_upgrade_from_project_path = (
'%s\\vsprojects\\libglog\\libglog.vcproj' % self._package_path)
self._vc_project_path = (
'%s\\vsprojects\\libglog\\libglog.vcxproj' % self._package_path)
def MaybeTweakAfterUnpackage(self):
"""Tweaks a header file declaration under windows so it compiles."""
config_files = [
os.path.join(self._package_path, 'configure.ac'),
os.path.join(self._package_path, 'configure'),
]
for c_file in config_files:
with open(c_file, 'r') as f:
old_text = f.read()
text = old_text.replace('ac_cv_have_libgflags=1',
'ac_cv_have_libgflags=0')
with open(c_file, 'w') as f:
f.write(text)
output = subprocess.Popen([
"aclocal --version|head -n1|grep -oE '[0-9]+.[0-9]+'"
], stdout=subprocess.PIPE, shell=True).communicate()[0]
ac_file = os.path.join(self._package_path, 'aclocal.m4')
with open(ac_file, 'r') as f:
old_text = f.read()
text = old_text.replace(
"am__api_version='1.14'",
"am__api_version='{}'".format(output)
)
with open(ac_file, 'w') as f:
f.write(text)
install_shell_path = os.path.join(self._package_path, 'install-sh')
st = os.stat(install_shell_path)
os.chmod(install_shell_path, st.st_mode | stat.S_IEXEC)
os.chdir(self._package_path)
PackageInstaller.RunOrDie("aclocal", "run aclocal failed")
PackageInstaller.RunOrDie("automake", "run automake failed")
# remove_cygwin_paths = [
# ]
# for change_path in remove_cygwin_paths:
# changed = False
# with open(change_path, 'r') as f:
# old_text = f.read()
# # The source couple windows and cygwin together for some reason,
# # but that doesnt compile. CYGWIN appears to work if you take these
# # out (it will use pthreads instead of the windows API).
# text = old_text.replace('defined(OS_WINDOWS) || defined(OS_CYGWIN)',
# 'defined(OS_WINDOWS)')
# text = text.replace('defined OS_WINDOWS || defined OS_CYGWIN',
# 'defined(OS_WINDOWS)')
# changed = old_text != text
# if changed:
# with open(change_path, 'w') as f:
# f.write(text)
# print 'Hacked %s' % change_path
# logging_h_path = os.path.join(
# self._package_path, 'src', 'windows', 'glog', 'logging.h')
# changed = False
# with open(logging_h_path, 'r') as f:
# old_text = f.read()
# text = old_text.replace('class LogStreamBuf',
# 'class GOOGLE_GLOG_DLL_DECL LogStreamBuf')
# changed = old_text != text
# if changed:
# with open(logging_h_path, 'w') as f:
# f.write(text)
# print 'Hacked %s' % logging_h_path
def Install(self):
"""Overrides install to copy the generated headers and libs."""
if self._config.port != WINDOWS_PLATFORM:
super(GLogPackageInstaller, self).Install()
return
config = self._config
install_libdir = os.path.join(config.abs_install_dir, 'lib')
install_includedir = os.path.join(
config.abs_install_dir, 'include', 'glog')
print '>>> Installing %s' % self._package_name
if not os.path.exists(install_libdir):
os.makedirs(install_libdir)
if not os.path.exists(install_includedir):
os.makedirs(install_includedir)
PackageInstaller.CopyAllFiles(
os.path.join(self._package_path, 'src', 'windows', 'glog'),
install_includedir)
release_dir = os.path.join(
self._package_path, 'vsprojects', 'libglog', 'Release')
for ext in ['lib', 'dll', 'pdb']:
shutil.copyfile('%s.%s' % (os.path.join(release_dir, 'libglog'), ext),
'%s.%s' % (os.path.join(install_libdir, 'libglog'), ext))
class CurlPackageInstaller(PackageInstaller):
def __init__(self, config, url):
if config.compiler == VS_COMPILER:
config_type = CMAKE_CONFIG
else:
config_type = CONFIGURE_CONFIG
super(CurlPackageInstaller, self).__init__(
config, url, config_type=config_type)
self._extra_configure_flags = (
'--with-ssl="`pwd`/../install" --disable-shared --disable-ldap')
class Installer(object):
"""Acquires, builds, and installs dependencies for the SDK."""
def __init__(self, config, restricted_package_names):
"""Set up variables from flags. Exit on failure.
Args:
config: (ConfigInfo) Configuraton options.
restricted_package_names: (Array) Subset of package names to install.
"""
print 'Initializing....'
# If non-empty then just prepare these packages.
# The entries here are keys in url_map
self._restricted_packages = restricted_package_names
self._url_map = {}
if config.port == WINDOWS_PLATFORM or config.port == CYGWIN_PLATFORM:
self._url_map.update({
# Use CMake as our build system for the libraries and some deps
'cmake': (CMakeExeInstaller(
config,
'http://www.cmake.org/files/v3.1/cmake-3.1.1-win32-x86.exe')),
'openssl': (IgnorePackageInstaller(config, 'ignoring_openssl')),
})
else:
self._url_map.update({
# Use CMake as our build system for the libraries and some deps
'cmake': (PackageInstaller(
config,
'http://www.cmake.org/files/v3.1/cmake-3.1.1.tar.gz',
config_type=CONFIGURE_CONFIG)),
# This is used both for curl https support and
# the OpenSslCodec library for the OpenSslCodec for data encryption.
# The OpenSslCodec is not requird so if you get an https transport
# from somewhere else then you do not need this dependency.
'openssl': (OpenSslPackageInstaller(
config, 'https://www.openssl.org/source/openssl-1.0.1m.tar.gz')),
})
self._url_map.update({
# GFlags is only used for some examples.
# Only used for tests and samples.
'gflags': (GFlagsPackageInstaller(
config,
'https://github.com/gflags/gflags/archive/v2.1.2.zip',
package_name="gflags-2.1.2")),
# GLog is the logging mechanism used through the client API
'glog': (GLogPackageInstaller(
config,
'https://github.com/google/glog/archive/v0.3.4.zip',
package_name="glog-0.3.4")),
# GMock (and included GTest) are only used for tests, not runtime
# Only used for tests.
'gmock': (GMockPackageInstaller(
config,
'http://googlemock.googlecode.com/files/gmock-1.6.0.zip')),
# For now we use JsonCpp for JSON support in the Client Service Layer
# and other places where we process JSON encoded data.
'jsoncpp': (JsonCppPackageInstaller(
config,
'http://downloads.sourceforge.net/project/jsoncpp'
'/jsoncpp/0.5.0/jsoncpp-src-0.5.0.tar.gz')),
# Mongoose is used as webserver for samples.
# The ownership and license style seems to keep changing, so we do not
# download it by default.
#'mongoose': (MongoosePackageInstaller(
# config,
# 'https://github.com/cesanta/mongoose/archive/master.zip')),
'curl': (CurlPackageInstaller(
config, 'http://curl.askapache.com/download/curl-7.48.0.tar.gz')),
})
# make sure cmake occurs first since others may depend on it
if not self._restricted_packages:
self._restricted_packages = self._url_map.keys()
ordered_packages = ['cmake', 'openssl', 'glog']
for p in ordered_packages:
self._restricted_packages.remove(p)
self._restricted_packages = ordered_packages + self._restricted_packages
def ProcessDependencyOrDie(self, name):
"""Process a single dependency.
Args:
name: (string) The name of the dependency to process.
"""
value = self._url_map.get(name)
if not value:
print 'Unknown package "%s"' % name
sys.exit(1)
value.Process()
def Run(self):
"""Run the installer.
Returns:
Packages that were processed.
"""
restricts = self._restricted_packages
# Attempt to process each of the requested packages.
for key in restricts:
self.ProcessDependencyOrDie(key)
return restricts
if __name__ == '__main__':
config_info = ConfigInfo(os.getcwd(), sys.argv)
restricted_packages = []
try:
opts, restricted_packages = getopt.getopt(
sys.argv[1:], 'bdi', ['download_dir=', 'install_dir=', 'force'])
config_info.SetOptions(opts)
except getopt.GetoptError:
print ('%s: [-b] [-d] [-i]' % sys.argv[0]
+ '[--download_dir=<path>] [--install_dir=<path>] [--force]')
sys.exit(1)
installer = Installer(config_info, restricted_packages)
processed_packages = installer.Run()
print '\nFinished processing %s' % str(processed_packages)
| apache-2.0 | 4,336,298,736,616,382,500 | 34.297589 | 80 | 0.621129 | false |
coreyfarrell/testsuite | lib/python/asterisk/voicemail.py | 1 | 28506 | #!/usr/bin/env python
# vim: sw=3 et:
"""Module used for testing app_voicemail
Note that this module has been superceded by the pluggable
framework and the apptest module.
Copyright (C) 2011, Digium, Inc.
Matt Jordan <[email protected]>
This program is free software, distributed under the terms of
the GNU General Public License Version 2.
"""
import sys
import os
import glob
import shutil
import logging
import time
import random
from .config import ConfigFile
from .test_case import TestCase
from .test_state import TestState, TestStateController, FailureTestState
sys.path.append("lib/python")
LOGGER = logging.getLogger(__name__)
class TestCondition(object):
"""Class that holds the state of some test condition.
This class holds the state of a test condition and allows a callback
function to be used to evaluate whether or not that test condition has
passed
"""
def __init__(self, evaluate_fn=None, test_condition_data=None):
"""Constructor
Keyword Arguments:
evaluate_fn Function used to evaluate the condition. This
fuction should return True or False, and take in
two parameters:
- a value to be evaluated
- the test_condition_data passed to this
constructor
test_condition_data Some piece of data that will be passed to the
evaluate_fn
"""
self._evaluate_fn = evaluate_fn
self.test_condition_data = test_condition_data
self.current_state = False
def evaluate(self, value):
"""Evaluate the test condition
Keyword Arguments:
value The value to evaluate
"""
if self._evaluate_fn is not None:
self.current_state = self._evaluate_fn(value, self)
else:
LOGGER.warn("No evaluate function defined, setting "
"current_state to [%s]" % str(value))
self.current_state = value
return
def handle_redirect_failure(reason):
"""Generic AMI redirect failure handler"""
LOGGER.warn("Error sending redirect - test may or may not fail:")
LOGGER.warn(reason.getTraceback())
return reason
class VoiceMailTest(TestCase):
"""Base class for voice mail tests that use TestStateController"""
# The formats a message can be left in
formats = ["ulaw", "wav", "WAV"]
# The default expected channel to be used to send info to the voicemail
# server
default_sender_channel = "PJSIP/ast1-00000000"
def __init__(self):
"""Constructor"""
super(VoiceMailTest, self).__init__()
self.ami_receiver = None
self.ami_sender = None
self.ast_sender = None
self._test_conditions = {}
self._previous_audio = ""
self._previous_dtmf = ""
self.sender_channel = VoiceMailTest.default_sender_channel
self.test_state_controller = None
def create_test_controller(self):
"""Create the test controller.
This should be called once ami_receiver and ami_sender have both been
set by the test derived from this class.
"""
if (self.ami_receiver is not None and self.ami_sender is not None):
self.test_state_controller = TestStateController(self,
self.ami_receiver)
def hangup(self):
"""Hang up the current call"""
if self.ast_sender is None:
msg = "Attempting to send hangup to non-existant Asterisk instance"
LOGGER.error(msg)
failure = FailureTestState(self.condition_controller)
self.test_state_controller.change_state(failure)
return
deferred = self.ami_sender.redirect(self.sender_channel,
"voicemailCaller",
"hangup",
1)
deferred.addErrback(handle_redirect_failure)
def send_dtmf(self, dtmf_to_send):
"""Send a DTMF signal to the voicemail server
Keyword Arguments:
dtmf_to_send The DTMF code to send
"""
LOGGER.info("Attempting to send DTMF " + dtmf_to_send)
if self.ami_sender is None:
LOGGER.error("Attempting to send DTMF to non-connected caller AMI")
failure = FailureTestState(self.condition_controller)
self.test_state_controller.change_state(failure)
return
if (self._previous_dtmf != dtmf_to_send):
self.ami_sender.setVar(channel="", variable="DTMF_TO_SEND",
value=dtmf_to_send)
self._previous_dtmf = dtmf_to_send
# Redirect to the DTMF extension - note that we assume that we only have
# one channel to the other asterisk instance
deferred = self.ami_sender.redirect(self.sender_channel,
"voicemailCaller",
"sendDTMF",
1)
deferred.addErrback(handle_redirect_failure)
def send_sound_file(self, audio_file):
"""Send a sound file to the voicemail server
Keyword Arguments:
audio_file The local path to the file to stream
"""
if self.ami_sender is None:
msg = "Attempting to send sound file to non-connected caller AMI"
LOGGER.error(msg)
failure = FailureTestState(self.condition_controller)
self.test_state_controller.change_state(failure)
return
if (self._previous_audio != audio_file):
self.ami_sender.setVar(channel="", variable="TALK_AUDIO",
value=audio_file)
self._previous_audio = audio_file
# Redirect to the send sound file extension - note that we assume that
# we only have one channel to the other asterisk instance
deferred = self.ami_sender.redirect(self.sender_channel,
"voicemailCaller",
"sendAudio",
1)
deferred.addErrback(handle_redirect_failure)
def send_sound_file_with_dtmf(self, audio_file, dtmf_to_send):
"""Send a sound file to the voicemail server, then send a DTMF signal
Keyword Arguments:
audio_file The local path to the file to stream
dtmf_to_send The DTMF signal to send
Note that this is necessary so that when the audio file is finished, we
close the audio recording cleanly; otherwise, Asterisk will detect the
end of file as a hangup
"""
if self.ami_sender is None:
msg = "Attempting to send sound/DTMF to non-connected caller AMI"
LOGGER.error(msg)
failure = FailureTestState(self.condition_controller)
self.test_state_controller.change_state(failure)
return
if (self._previous_audio != audio_file):
self.ami_sender.setVar(channel="", variable="TALK_AUDIO",
value=audio_file)
self._previous_audio = audio_file
if (self._previous_dtmf != dtmf_to_send):
self.ami_sender.setVar(channel="", variable="DTMF_TO_SEND",
value=dtmf_to_send)
self._previous_dtmf = dtmf_to_send
# Redirect to the appropriate extension - note that we assume that
# we only have one channel to the other asterisk instance
deferred = self.ami_sender.redirect(self.sender_channel,
"voicemailCaller",
"sendAudioWithDTMF",
1)
deferred.addErrback(handle_redirect_failure)
def add_test_condition(self, condition_name, condition):
"""Add a new test condition to track
Keyword Arguments:
condition_name The unique name of the condition
condition The TestCondition object
"""
self._test_conditions[condition_name] = condition
def set_test_condition(self, condition_name, value):
"""Set a test condition to the specified value, and evalute whether or
not it has passed
Keyword Arguments:
condition_name The unique name of the condition
value The value to pass to the evaluation checker
"""
if condition_name in self._test_conditions.keys():
self._test_conditions[condition_name].evaluate(value)
def get_test_condition(self, condition_name):
"""Get the current state of a test condition
Keyword Arguments:
condition_name The unique name of the condition
Returns:
True if the condition has passed; False otherwise
"""
if condition_name in self._test_conditions.keys():
return self._test_conditions[condition_name].current_state
return False
def check_test_conditions(self):
"""Check all test conditions
Returns:
True if all have passed; False if any have not
"""
ret_val = True
for key, value in self._test_conditions.items():
if not value.current_state:
LOGGER.warn("Test Condition [" + key + "] has not passed")
ret_val = False
return ret_val
class VoiceMailState(TestState):
"""Base class for VoiceMail TestEvent state machine handling
This class exists mostly to share the VoiceMailTest object across the
concrete class implementations
"""
def __init__(self, controller, voice_mail_test):
"""Constructor
Keyword Arguments:
controller The TestStateController managing the test
voice_mail_test The main test object
"""
super(VoiceMailState, self).__init__(controller)
self.voice_mail_test = voice_mail_test
if self.voice_mail_test is None:
msg = "Failed to set voicemail test object"
LOGGER.error(msg)
raise RuntimeError(msg)
LOGGER.debug("Entering state [" + self.get_state_name() + "]")
def get_state_name(self):
"""The name of this state
Returns:
The name of the current state
"""
pass
def handle_default_state(self, event):
"""Can be called by derived classes to output an ignored state"""
LOGGER.debug("State [" + self.get_state_name() +
"] - ignoring state change " + event['state'])
class VoiceMailMailboxManagement(object):
"""Class that manages creation of, verification of, and teardown of Asterisk
mailboxes on the local filesystem
"""
# The parent directory that this test resides in
test_parent_dir = "tests/apps/voicemail"
# Name of the folder for new messages
inbox_folder_name = "INBOX"
# Name of the folder for temporary messages
temp_folder_name = "tmp"
# Name of the folder for old messages
old_folder_name = "Old"
# Name of the folder for urgent messages
urgent_folder_name = "Urgent"
# Name of the folder for recorded greetings
greetings_folder_name = "greet"
def __init__(self, ast):
"""Constructor
Keyword Arguments:
ast The instance of Asterisk to track
"""
self.__ast = ast
self.voicemail_directory = (self.__ast.directories['astspooldir'] +
'/voicemail')
self.created_voicemails = {}
def create_mailbox(self, context, mailbox, create_all_folders=False):
"""Create the basic folders needed for a mailbox on the file system
Keyword Arguments:
context The context that the mailbox will exist under
mailbox The mailbox to create
create_all_folders Optional parameter that will create all of the
various folders.
In general, app_voicemail should be responsible for making the folders
on the file system as needed. This method should only be needed when we
want to bypass some of the standard applications and create a known
state of a voicemail mailbox
Returns:
True on success, False on error
"""
mailbox_path = (self.__ast.base +
"%(vd)s/%(c)s/%(m)s" % {'vd': self.voicemail_directory,
'c': context, 'm': mailbox})
try:
if not os.path.isdir(mailbox_path):
os.makedirs(mailbox_path)
if not create_all_folders:
return True
inbox_path = ("%(mp)s/%(f)s" % {
'mp': mailbox_path,
'f': VoiceMailMailboxManagement.inbox_folder_name})
if not os.path.isdir(inbox_path):
os.makedirs(inbox_path)
temp_path = ("%(mp)s/%(f)s" % {
'mp': mailbox_path,
'f': VoiceMailMailboxManagement.temp_folder_name})
if not os.path.isdir(temp_path):
os.makedirs(temp_path)
old_path = ("%(mp)s/%(f)s" % {
'mp': mailbox_path,
'f': VoiceMailMailboxManagement.old_folder_name})
if not os.path.isdir(old_path):
os.makedirs(old_path)
urgent_path = ("%(mp)s/%(f)s" % {
'mp': mailbox_path,
'f': VoiceMailMailboxManagement.urgent_folder_name})
if not os.path.isdir(urgent_path):
os.makedirs(urgent_path)
greetings_path = ("%(mp)s/%(f)s" % {
'mp': mailbox_path,
'f': VoiceMailMailboxManagement.greetings_folder_name})
if not os.path.isdir(greetings_path):
os.makedirs(greetings_path)
except IOError as io_error:
if io_error.errno == errno.EACCESS:
LOGGER.error("You do not have sufficient permissions to "
"perform the necessary directory manipulations")
return False
return True
def create_dummy_voicemail(self, context, mailbox, folder, msgnum, formats):
"""Creates a dummy voicemail in the specified mailbox / folder
Keyword Arguments:
context The context of the mailbox
mailbox The mailbox
folder The folder to create the voicemail in
msgnum The message number
formats The formats to create the sound file as
The 'formats' merely append particular designators on the end of the
sound file, /voicemail/sounds/talking. The actual sound file is not
converted.
Returns:
True if the voicemail was created successfully
False otherwise
"""
if not self.check_folder_exists(context, mailbox, folder):
return False
msg_name = 'msg%04d' % (msgnum)
msg_env_name = msg_name + ".txt"
msg_env_path = (self.__ast.base +
"%(vd)s/%(c)s/%(m)s/%(f)s/%(n)s" % {
'vd': self.voicemail_directory,
'c': context, 'm': mailbox, 'f': folder, 'n': msg_env_name})
random.seed()
msg_id = (str(int(time.time())) + "-" +
str(random.randrange(0, 1, sys.maxint - 1)))
with open(msg_env_path, 'w') as envelope_file:
envelope_file.write(';\n')
envelope_file.write('; Message Information file\n')
envelope_file.write(';\n')
envelope_file.write('[message]\n')
envelope_file.write('origmailbox=' + mailbox + '\n')
envelope_file.write('context=' + context + '\n')
envelope_file.write('macrocontext=\n')
envelope_file.write('exten=' + mailbox + '\n')
envelope_file.write('rdnis=unknown\n')
envelope_file.write('priority=2\n')
envelope_file.write('callerchan=SIP/ast1-00000000\n')
envelope_file.write('callerid=\"Anonymous\"<555-5555>\n')
envelope_file.write('origdate=Tue Aug 9 10:05:13 PM UTC 2011\n')
envelope_file.write('origtime=1312927513\n')
envelope_file.write('msg_id=%s\n' % msg_id)
if (folder == VoiceMailMailboxManagement.urgent_folder_name):
envelope_file.write('flag=Urgent\n')
else:
envelope_file.write('flag=\n')
envelope_file.write('category=tt-weasels\n')
envelope_file.write('duration=6\n')
for snd_format in formats:
msg_format_name = msg_name + '.' + snd_format
msg_format_path = (self.__ast.base +
"%(vd)s/%(c)s/%(m)s/%(f)s/%(n)s" % {
'vd': self.voicemail_directory,
'c': context,
'm': mailbox,
'f': folder,
'n': msg_format_name})
audio_file = os.path.join(os.getcwd(),
"%s/sounds/talking.ulaw" %
(self.test_parent_dir))
shutil.copy(audio_file, msg_format_path)
if folder not in self.created_voicemails.keys():
self.created_voicemails[folder] = []
self.created_voicemails[folder].append((msgnum, msg_id))
return True
def check_folder_exists(self, context, mailbox,
folder=inbox_folder_name):
"""Checks that a folder exists for a particular user
Keyword Arguments:
context The context of the mailbox
mailbox The mailbox
folder The folder to check; defaults to the default inbox name
Returns:
True if the folder exists
False otherwise
"""
mailbox_path = (self.__ast.base + "%(vd)s/%(c)s/%(m)s" %
{'vd': self.voicemail_directory,
'c': context,
'm': mailbox})
if not (os.path.exists(mailbox_path)):
return False
folder_path = "%(mp)s/%(f)s" % {'mp': mailbox_path, 'f': folder}
return os.path.exists(folder_path)
def check_voicemail_exists(self, context, mailbox, msgnum, list_formats,
folder=inbox_folder_name):
"""Check if a voicemail exists on the filesystem
Keyword Arguments:
context The context of the mailbox
mailbox The mailbox
msgnum The 1-based index of the voicemail to check for
list_formats The formats we expect to be recorded for us
folder The folder to check under; default to the default
inbox name
Returns:
True if the voicemail exists
False otherwise
"""
ret_val = True
msg_name = 'msg%04d' % (msgnum)
for snd_format in list_formats:
file_name = msg_name + "." + snd_format
ret_val = ret_val & self.check_voice_file_exists(context,
mailbox,
file_name,
folder)
# make sure we have the message envelope file
file_name = msg_name + ".txt"
ret_val = ret_val & self.check_voice_file_exists(context,
mailbox,
file_name,
folder)
return ret_val
def check_greeting_exists(self, context, mailbox, msg_name, list_formats):
"""Check if a voicemail greeting exists on the filesystem
Keyword Arguments:
context The context of the mailbox
mailbox The mailbox
msg_name The name of the greeting to find
list_formats The formats we expect to be recorded for us
Returns:
True if the greeting exists
False otherwise
"""
ret_val = True
for snd_format in list_formats:
file_name = msg_name + "." + snd_format
ret_val = ret_val & self.check_voice_file_exists(context,
mailbox,
file_name,
"")
return ret_val
def check_voicemail_property(self, context, mailbox, msgnum,
property_name, property_value,
folder=inbox_folder_name):
"""Check if a voicemail has the property specified
Keyword Arguments:
context The context of the mailbox
mailbox The mailbox
msgnum The 1-based index of the voicemail to check for
property_name The name of the property to check
property_value The value to check for
folder The folder to check under; default to the default inbox
name
Returns:
True if the voicemail has the property and value specified
False otherwise
"""
list_formats = []
if not self.check_voicemail_exists(context, mailbox, msgnum,
list_formats, folder):
return False
msg_name = 'msg%(msgnum)04d' % {"msgnum": msgnum}
msg_name = msg_name + ".txt"
msg_path = (self.__ast.base + "%(vd)s/%(c)s/%(m)s/%(f)s/%(n)s" % {
'vd': self.voicemail_directory,
'c': context,
'm': mailbox,
'f': folder,
'n': msg_name})
config_file = ConfigFile(msg_path)
for cat in config_file.categories:
if cat.name == 'message':
for kvp in cat.options:
if kvp[0] == property_name and kvp[1] == property_value:
return True
return False
class UserObject(object):
"""An object that holds voicemail user information"""
def __init__(self):
"""Constructor"""
self.password = ""
self.fullname = ""
self.emailaddress = ""
self.pageraddress = ""
def get_user_object(self, context, mailbox, source_file="voicemail.conf"):
"""Gets user information from the voicemail configuration file
Keyword Arguments:
context The context of the mailbox
mailbox The mailbox
source_file The file containing the user information to pull from.
Defaults to voicemail.conf
Returns:
A VoiceMailMailboxManagement.UserObject object, populated with the
user's values, or an empty object
"""
file_path = (self.__ast.base + self.__ast.directories['astetcdir'] +
"/" + source_file)
config_file = ConfigFile(file_path)
user_object = VoiceMailMailboxManagement.UserObject()
for cat in config_file.categories:
if cat.name == context:
for kvp in cat.options:
if kvp[0] == mailbox:
tokens = kvp[1].split(',')
i = 0
for token in tokens:
if i == 0:
user_object.password = token
elif i == 1:
user_object.fullname = token
elif i == 2:
user_object.emailaddress = token
elif i == 3:
user_object.pageraddress = token
i += 1
return user_object
return user_object
def check_voice_file_exists(self, context, mailbox, name,
folder=inbox_folder_name):
"""Checks if a file exists under the voicemail file structure
Keyword Arguments:
context The context of the mailbox
mailbox The mailbox
msgnum The name of the file to check for
folder The folder to check under; default to the default inbox name
Returns:
True if the file exists
False otherwise
"""
if not (self.check_folder_exists(context, mailbox, folder)):
return False
msg_path = (self.__ast.base + "%(vd)s/%(c)s/%(m)s/%(f)s/%(n)s" % {
'vd': self.voicemail_directory,
'c': context,
'm': mailbox,
'f': folder,
'n': name})
if (os.path.exists(msg_path)):
return True
else:
return False
def _remove_items_from_folder(self, mailbox_path, folder):
"""Remove items from the specified mailbox folder"""
folder_path = os.path.join(self.__ast.base, "%(mp)s/%(f)s" % {
'mp': mailbox_path, 'f': folder})
if not (os.path.exists(folder_path)):
return
folder_path = folder_path + '/*'
for voicemail_file in glob.glob(folder_path):
if not os.path.isdir(voicemail_file):
os.remove(voicemail_file)
return
def remove_mailbox(self, context, mailbox, remove_folders=False):
"""Removes all items from a mailbox
Optionally removes the mailbox itself from the file system. This does
not remove the context folder
Keyword Arguments:
context The context the mailbox exists under
mailbox The mailbox to remove
remove_folders If true, the folders as well as their contents will be
removed
Returns:
True on successful removal of the messages/folders
False otherwise
"""
mailbox_path = (self.__ast.base + "/%(vd)s/%(c)s/%(m)s" % {
'vd': self.voicemail_directory,
'c': context,
'm': mailbox})
if not (os.path.exists(mailbox_path)):
return False
self._remove_items_from_folder(mailbox_path,
VoiceMailMailboxManagement.inbox_folder_name)
self._remove_items_from_folder(mailbox_path,
VoiceMailMailboxManagement.temp_folder_name)
self._remove_items_from_folder(mailbox_path,
VoiceMailMailboxManagement.old_folder_name)
self._remove_items_from_folder(mailbox_path,
VoiceMailMailboxManagement.urgent_folder_name)
self._remove_items_from_folder(mailbox_path,
VoiceMailMailboxManagement.greetings_folder_name)
if (remove_folders):
os.rmdir(os.path.join(self.__ast.base, "%(mp)s/%(f)s" % {
'mp': mailbox_path,
'f': VoiceMailMailboxManagement.inbox_folder_name}))
os.rmdir(os.path.join(self.__ast.base, "%(mp)s/%(f)s" % {
'mp': mailbox_path,
'f': VoiceMailMailboxManagement.temp_folder_name}))
os.rmdir(os.path.join(self.__ast.base, "%(mp)s/%(f)s" % {
'mp': mailbox_path,
'f': VoiceMailMailboxManagement.old_folder_name}))
os.rmdir(os.path.join(self.__ast.base, "%(mp)s/%(f)s" % {
'mp': mailbox_path,
'f': VoiceMailMailboxManagement.urgent_folder_name}))
os.rmdir(os.path.join(self.__ast.base, "%(mp)s/%(f)s" % {
'mp': mailbox_path,
'f': VoiceMailMailboxManagement.greetings_folder_name}))
os.rmdir(mailbox_path)
return True
| gpl-2.0 | -3,408,383,965,109,269,000 | 37.314516 | 88 | 0.53943 | false |
jianhuashao/WebDownloadJobsManage | post-process/post_appid_to_asin.py | 1 | 1495 | from bs4 import BeautifulSoup, Comment
import post_process_base as my_process
import sqlite3
import myutil
#######
job_target = 'appid_to_asin'
sql_init = '''
CREATE TABLE IF NOT EXISTS post_appid_to_asin (
app_id TEXT NOT NULL UNIQUE,
asin TEXT NOT NULL UNIQUE,
asin_url TEXT,
UNIQUE (app_id, asin)
);
'''
sql_insert = '''
INSERT OR IGNORE INTO post_appid_to_asin (app_id, asin, asin_url) VALUES (?,?,?)
'''
#######
# db_init
db = myutil.db_get(job_target)
myutil.db_init(db, sql_init)
def parse_html(p, job_id, job_target, k, t):
soup = BeautifulSoup(open(p).read(), 'html.parser')
bs = soup.find_all(name='b', attrs={}, text='ASIN:')
if len(bs) != 1:
# can not find asin
return False
else:
asin = bs[0].parent.text
asin = asin.replace('ASIN:', '').strip()
a_s = soup.find_all(name='a', attrs={'id':'seeAllReviewsUrl'})
#print 'a_s: ', a_s
asin_url = ''
if (len(a_s) > 0):
a_attrs = a_s[0].attrs
if a_attrs.has_key('href'):
asin_url = a_attrs['href']
asin_url = asin_url.replace('http://www.amazon.com/', '').split('/')[0]
c = db.cursor()
c.execute(sql_insert, (job_id, asin, asin_url)) # job_id == app_id
db.commit()
c.close()
#print asin, job_id, k, t
def post_process():
my_process.loop_dir(job_target, parse_html)
# or
#parse_html('/Users/jianhuashao/github/data_row/web_jobs/appid_to_asin/com.rovio.angrybirdsseasons.html', 'com.rovio.angrybirdsseasons', 'appid_to_asin', 1, 1);
if __name__ == '__main__':
post_process()
| apache-2.0 | -175,063,746,277,168,670 | 24.793103 | 161 | 0.630769 | false |
GehirnInc/python-oidc | oidc/userinfo.py | 1 | 1539 | # -*- coding: utf-8 -*-
from py3oauth2.message import (
Message,
Parameter,
)
class UserInfo(Message):
__scopes__ = {
'openid': {'sub'},
'profile': {'name', 'given_name', 'family_name', 'middle_name',
'nickname', 'preferred_username', 'profile', 'picture',
'website', 'gender', 'birthdate', 'zoneinfo', 'locale',
'update_at'},
'email': {'email', 'email_verified'},
'address': {'address'},
'phone': {'phone_number', 'phone_number_verified'},
}
sub = Parameter(str, required=True)
# scope = profile
name = Parameter(str)
given_name = Parameter(str)
family_name = Parameter(str)
middle_name = Parameter(str)
nickname = Parameter(str)
preferred_username = Parameter(str)
profile = Parameter(str)
picture = Parameter(str)
website = Parameter(str)
gender = Parameter(str)
birthdate = Parameter(str)
zoneinfo = Parameter(str)
locale = Parameter(str)
update_at = Parameter(int)
# email
email = Parameter(str)
email_verified = Parameter(bool)
# address
address = Parameter(dict)
# phone
phone_number = Parameter(str)
phone_number_verified = Parameter(bool)
def filter(self, scopes):
inst = self.__class__()
params = set()
for scope in scopes:
params.update(self.__scopes__[scope])
for param in params:
setattr(inst, param, getattr(self, param))
return inst
| mit | 8,365,824,870,575,421,000 | 25.084746 | 75 | 0.573099 | false |
riccardoklinger/qgis2web | qgis2web/qgis2webProvider.py | 2 | 3211 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
Process2Web
A QGIS plugin
Processing plugin for qgis2web
-------------------
begin : 2017-04-03
copyright : (C) 2017 by Tom Chadwin
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from qgis.core import QgsProcessingProvider
from .qgis2webAlgorithm import exportProject, exportVector, exportRaster
__author__ = 'Tom Chadwin'
__date__ = '2017-04-03'
__copyright__ = '(C) 2017 by Tom Chadwin'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
class qgis2webProvider(QgsProcessingProvider):
def __init__(self):
QgsProcessingProvider.__init__(self)
# Deactivate provider by default
self.activate = False
def unload(self):
"""Setting should be removed here, so they do not appear anymore
when the plugin is unloaded.
"""
QgsProcessingProvider.unload(self)
# ProcessingConfig.removeSetting(
# qgis2webProvider.MY_DUMMY_SETTING)
def id(self):
"""This is the name that will appear on the toolbox group.
It is also used to create the command line name of all the
algorithms from this provider.
"""
return 'qgis2web'
def name(self):
"""This is the provired full name.
"""
return 'qgis2web'
def icon(self):
"""We return the default icon.
"""
return QgsProcessingProvider.icon(self)
def load(self):
self.refreshAlgorithms()
return True
def loadAlgorithms(self):
"""Here we fill the list of algorithms in self.algs.
This method is called whenever the list of algorithms should
be updated. If the list of algorithms can change (for instance,
if it contains algorithms from user-defined scripts and a new
script might have been added), you should create the list again
here.
In this case, since the list is always the same, we assign from
the pre-made list. This assignment has to be done in this method
even if the list does not change, since the self.algs list is
cleared before calling this method.
"""
self.alglist = [exportProject(), exportVector(), exportRaster()]
for alg in self.alglist:
self.addAlgorithm(alg)
| gpl-2.0 | -8,803,471,639,096,117,000 | 34.285714 | 77 | 0.519776 | false |
kvarq/kvarq | analyse/convert.py | 1 | 1485 |
import argparse
import json
import sys
import time
parser = argparse.ArgumentParser(description='converts .json from one version to another')
parser.add_argument('-v', '--verbose', action='store_true',
help='print some information to stderr')
parser.add_argument('json',type=file,
help='name of .json file to process')
args = parser.parse_args()
data = json.load(args.json)
if not 'info' in data:
# convert version 0 -> version 1
if args.verbose: sys.stderr.write('converting '+args.json.name+'\n')
for test,posstr in data['hits'].items():
poss = []
lpos = 0
overflow = 0
for pos in map(int, posstr.split(',')):
if lpos<0 and pos>=0:
sys.stderr.write('*** probable overflow in %s : %d -> %d\n'%(test,lpos,pos))
overflow += 1
lpos = pos
if pos<0:
pos = (pos-(-2147483648)) + 0x80000000
poss.append(pos)
data['hits'][test] = ','.join(map(str,poss))
data['analyses'] = {
'spoligo': data['spoligo'],
'lineage': data['lineage'],
}
del data['spoligo']
del data['lineage']
descr = 'converted 0->1 on '+time.asctime(time.localtime())
if overflow>0:
descr+='; probably contains overflows that were not fixed'
data['info'] = {
'format':'kvarq',
'fastq':'?',
'when':'?',
'descr': descr,
}
print json.dumps(data, indent=2)
| gpl-3.0 | 8,435,191,959,356,598,000 | 23.344262 | 92 | 0.558249 | false |
vjmac15/Lyilis | lib/youtube_dl/extractor/vier (VJ Washington's conflicted copy 2017-08-29).py | 46 | 10008 | # coding: utf-8
from __future__ import unicode_literals
import re
import itertools
from .common import InfoExtractor
from ..utils import (
urlencode_postdata,
int_or_none,
unified_strdate,
)
class VierIE(InfoExtractor):
IE_NAME = 'vier'
IE_DESC = 'vier.be and vijf.be'
_VALID_URL = r'''(?x)
https?://
(?:www\.)?(?P<site>vier|vijf)\.be/
(?:
(?:
[^/]+/videos|
video(?:/[^/]+)*
)/
(?P<display_id>[^/]+)(?:/(?P<id>\d+))?|
(?:
video/v3/embed|
embed/video/public
)/(?P<embed_id>\d+)
)
'''
_NETRC_MACHINE = 'vier'
_TESTS = [{
'url': 'http://www.vier.be/planb/videos/het-wordt-warm-de-moestuin/16129',
'md5': 'e4ae2054a6b040ef1e289e20d111b46e',
'info_dict': {
'id': '16129',
'display_id': 'het-wordt-warm-de-moestuin',
'ext': 'mp4',
'title': 'Het wordt warm in De Moestuin',
'description': 'De vele uren werk eisen hun tol. Wim droomt van assistentie...',
'upload_date': '20121025',
'series': 'Plan B',
'tags': ['De Moestuin', 'Moestuin', 'meisjes', 'Tomaat', 'Wim', 'Droom'],
},
}, {
'url': 'http://www.vijf.be/temptationisland/videos/zo-grappig-temptation-island-hosts-moeten-kiezen-tussen-onmogelijke-dilemmas/2561614',
'info_dict': {
'id': '2561614',
'display_id': 'zo-grappig-temptation-island-hosts-moeten-kiezen-tussen-onmogelijke-dilemmas',
'ext': 'mp4',
'title': 'md5:84f45fe48b8c1fa296a7f6d208d080a7',
'description': 'md5:0356d4981e58b8cbee19355cbd51a8fe',
'upload_date': '20170228',
'series': 'Temptation Island',
'tags': list,
},
'params': {
'skip_download': True,
},
}, {
'url': 'http://www.vier.be/janigaat/videos/jani-gaat-naar-tokio-aflevering-4/2674839',
'info_dict': {
'id': '2674839',
'display_id': 'jani-gaat-naar-tokio-aflevering-4',
'ext': 'mp4',
'title': 'Jani gaat naar Tokio - Aflevering 4',
'description': 'md5:aa8d611541db6ae9e863125704511f88',
'upload_date': '20170501',
'series': 'Jani gaat',
'episode_number': 4,
'tags': ['Jani Gaat', 'Volledige Aflevering'],
},
'params': {
'skip_download': True,
},
'skip': 'Requires account credentials',
}, {
# Requires account credentials but bypassed extraction via v3/embed page
# without metadata
'url': 'http://www.vier.be/janigaat/videos/jani-gaat-naar-tokio-aflevering-4/2674839',
'info_dict': {
'id': '2674839',
'display_id': 'jani-gaat-naar-tokio-aflevering-4',
'ext': 'mp4',
'title': 'jani-gaat-naar-tokio-aflevering-4',
},
'params': {
'skip_download': True,
},
'expected_warnings': ['Log in to extract metadata'],
}, {
# Without video id in URL
'url': 'http://www.vier.be/planb/videos/dit-najaar-plan-b',
'only_matching': True,
}, {
'url': 'http://www.vier.be/video/v3/embed/16129',
'only_matching': True,
}, {
'url': 'https://www.vijf.be/embed/video/public/4093',
'only_matching': True,
}, {
'url': 'https://www.vier.be/video/blockbusters/in-juli-en-augustus-summer-classics',
'only_matching': True,
}, {
'url': 'https://www.vier.be/video/achter-de-rug/2017/achter-de-rug-seizoen-1-aflevering-6',
'only_matching': True,
}]
def _real_initialize(self):
self._logged_in = False
def _login(self, site):
username, password = self._get_login_info()
if username is None or password is None:
return
login_page = self._download_webpage(
'http://www.%s.be/user/login' % site,
None, note='Logging in', errnote='Unable to log in',
data=urlencode_postdata({
'form_id': 'user_login',
'name': username,
'pass': password,
}),
headers={'Content-Type': 'application/x-www-form-urlencoded'})
login_error = self._html_search_regex(
r'(?s)<div class="messages error">\s*<div>\s*<h2.+?</h2>(.+?)<',
login_page, 'login error', default=None)
if login_error:
self.report_warning('Unable to log in: %s' % login_error)
else:
self._logged_in = True
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
embed_id = mobj.group('embed_id')
display_id = mobj.group('display_id') or embed_id
video_id = mobj.group('id') or embed_id
site = mobj.group('site')
if not self._logged_in:
self._login(site)
webpage = self._download_webpage(url, display_id)
if r'id="user-login"' in webpage:
self.report_warning(
'Log in to extract metadata', video_id=display_id)
webpage = self._download_webpage(
'http://www.%s.be/video/v3/embed/%s' % (site, video_id),
display_id)
video_id = self._search_regex(
[r'data-nid="(\d+)"', r'"nid"\s*:\s*"(\d+)"'],
webpage, 'video id', default=video_id or display_id)
playlist_url = self._search_regex(
r'data-file=(["\'])(?P<url>(?:https?:)?//[^/]+/.+?\.m3u8.*?)\1',
webpage, 'm3u8 url', default=None, group='url')
if not playlist_url:
application = self._search_regex(
[r'data-application="([^"]+)"', r'"application"\s*:\s*"([^"]+)"'],
webpage, 'application', default=site + '_vod')
filename = self._search_regex(
[r'data-filename="([^"]+)"', r'"filename"\s*:\s*"([^"]+)"'],
webpage, 'filename')
playlist_url = 'http://vod.streamcloud.be/%s/_definst_/mp4:%s.mp4/playlist.m3u8' % (application, filename)
formats = self._extract_wowza_formats(
playlist_url, display_id, skip_protocols=['dash'])
self._sort_formats(formats)
title = self._og_search_title(webpage, default=display_id)
description = self._html_search_regex(
r'(?s)<div\b[^>]+\bclass=(["\'])[^>]*?\bfield-type-text-with-summary\b[^>]*?\1[^>]*>.*?<p>(?P<value>.+?)</p>',
webpage, 'description', default=None, group='value')
thumbnail = self._og_search_thumbnail(webpage, default=None)
upload_date = unified_strdate(self._html_search_regex(
r'(?s)<div\b[^>]+\bclass=(["\'])[^>]*?\bfield-name-post-date\b[^>]*?\1[^>]*>.*?(?P<value>\d{2}/\d{2}/\d{4})',
webpage, 'upload date', default=None, group='value'))
series = self._search_regex(
r'data-program=(["\'])(?P<value>(?:(?!\1).)+)\1', webpage,
'series', default=None, group='value')
episode_number = int_or_none(self._search_regex(
r'(?i)aflevering (\d+)', title, 'episode number', default=None))
tags = re.findall(r'<a\b[^>]+\bhref=["\']/tags/[^>]+>([^<]+)<', webpage)
return {
'id': video_id,
'display_id': display_id,
'title': title,
'description': description,
'thumbnail': thumbnail,
'upload_date': upload_date,
'series': series,
'episode_number': episode_number,
'tags': tags,
'formats': formats,
}
class VierVideosIE(InfoExtractor):
IE_NAME = 'vier:videos'
_VALID_URL = r'https?://(?:www\.)?(?P<site>vier|vijf)\.be/(?P<program>[^/]+)/videos(?:\?.*\bpage=(?P<page>\d+)|$)'
_TESTS = [{
'url': 'http://www.vier.be/demoestuin/videos',
'info_dict': {
'id': 'demoestuin',
},
'playlist_mincount': 153,
}, {
'url': 'http://www.vijf.be/temptationisland/videos',
'info_dict': {
'id': 'temptationisland',
},
'playlist_mincount': 159,
}, {
'url': 'http://www.vier.be/demoestuin/videos?page=6',
'info_dict': {
'id': 'demoestuin-page6',
},
'playlist_mincount': 20,
}, {
'url': 'http://www.vier.be/demoestuin/videos?page=7',
'info_dict': {
'id': 'demoestuin-page7',
},
'playlist_mincount': 13,
}]
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
program = mobj.group('program')
site = mobj.group('site')
page_id = mobj.group('page')
if page_id:
page_id = int(page_id)
start_page = page_id
playlist_id = '%s-page%d' % (program, page_id)
else:
start_page = 0
playlist_id = program
entries = []
for current_page_id in itertools.count(start_page):
current_page = self._download_webpage(
'http://www.%s.be/%s/videos?page=%d' % (site, program, current_page_id),
program,
'Downloading page %d' % (current_page_id + 1))
page_entries = [
self.url_result('http://www.' + site + '.be' + video_url, 'Vier')
for video_url in re.findall(
r'<h[23]><a href="(/[^/]+/videos/[^/]+(?:/\d+)?)">', current_page)]
entries.extend(page_entries)
if page_id or '>Meer<' not in current_page:
break
return self.playlist_result(entries, playlist_id)
| gpl-3.0 | -1,312,040,345,676,478,700 | 36.909091 | 145 | 0.495803 | false |
probablytom/behaviour-modelling | software_engineering_atoms.py | 1 | 6208 | import random, environment, dag, time
from logger import Logger
from decorators import atom # Will need renaming
# For keeping a log / printing to the console
# filepath-----\/ Logging--\/ printing--\/
log = Logger( "event.log", False, False)
# -----------------------------------------------------------------------------
# HELPER FUNCTIONS
# -----------------------------------------------------------------------------
def is_tested(chunk):
for test in environment.resources["tests"]:
if test.chunk() is chunk: return True
return False
def has_bug(chunk):
for bug in environment.resources["bugs"]:
if bug.affects(chunk): return True
return False
def detects_bug(test, bug):
if test is None: return False
if bug is None: return False
if test.chunk is None or bug.chunks == []: return False
return bug.affects(test.chunk) and test.works
def bug_found(bug):
for test in environment.resources["tests"]:
if detects_bug(test, bug):
return True
return False
def get_feature_of_chunk(chunk):
for feature in range(environment.resources["features"]):
if chunk in environment.resources["features"][feature]: return feature
return None
def test_passes(test):
for bug in environment.resources["bugs"]:
if detects_bug(test, bug): return False
return True
def remove_bug(bug):
environment.resources["bugs"].remove(bug)
def cost_of_bug(bug):
return bug.age() / 20 + 1
def number_of_detected_bugs():
n = 0
for bug in environment.resources["bugs"]:
for test in environment.resources["tests"]:
if detects_bug(test, bug):
n += 1
break
return n
# -----------------------------------------------------------------------------
# LOW LEVEL ACTIONS
# atomic activity for actual activity within the sociotechnical system
# all interactions with environment.resources, shouldn't be anything else...
# -----------------------------------------------------------------------------
@atom
def create_feature():
environment.resources["features"].append([])
environment.resources["current feature"] = len(environment.resources["features"])-1
@atom
def add_chunk(testing=False):
environment.resources["time"] += 2
feature = environment.resources["current feature"]
chunk = dag.Chunk()
# Add a test if it's necessary
if testing:
test = environment.resources["tests"][-1]
chunk.test = test
test.chunk = chunk
environment.resources["tests"].append(test)
# Record this chunk of code
environment.resources["features"][feature].append(chunk)
# Conditionally add a bug to the chunk
if random.randint(3,5) is 4:
bug = dag.Bug(chunk)
environment.resources["bugs"].append(bug)
# We're now working on the chunk we just created, so...
environment.resources["current chunk"] = chunk
@atom
def add_chunk_waterfall(testing=False):
environment.resources["time"] += 2
chunk = dag.Chunk()
# Add a test if it's necessary
if testing:
if len(environment.resources["tests"]) is not 0:
test = environment.resources["tests"][-1]
if test is not None:
chunk.test = test
test.chunk = chunk
environment.resources["tests"].append(test)
# Record this chunk of code
environment.resources["features"].append(chunk)
# Conditionally add a bug to the chunk
if random.randint(3,5) is 4:
bug = dag.Bug(chunk)
environment.resources["bugs"].append(bug)
# We're now working on the chunk we just created, so...
environment.resources["current chunk"] = chunk
@atom
def add_chunk_tdd(testing=True):
environment.resources["time"] += 2
feature = environment.resources["current feature"]
chunk = dag.Chunk()
# Add a test if it's necessary
if testing:
if len(environment.resources["tests"]) is not 0:
test = environment.resources["tests"][-1]
if test is not None:
chunk.test = test
test.chunk = chunk
environment.resources["tests"].append(test)
# Record this chunk of code
environment.resources["features"][feature].append(chunk)
# Conditionally add a bug to the chunk
if random.randint(3,5) is 4:
bug = dag.Bug(chunk)
environment.resources["bugs"].append(bug)
# We're now working on the chunk we just created, so...
environment.resources["current chunk"] = chunk
@atom
def create_test_for_chunk(chunk):
environment.resources["time"] += 1
if chunk.test is None:
test = dag.Test(chunk)
environment.resources["tests"].append(test)
chunk.test = test
def create_test_tdd():
environment.resources["time"] += 1
test = dag.Test()
environment.resources["tests"].append(test)
@atom
def fix_chunk(chunk=None):
if chunk is None: chunk = environment.resources["current chunk"]
# Iterate over bugs that affect the chunk and thrash until fixed
for bug in environment.resources["bugs"]:
while detects_bug(chunk.test, bug):
environment.resources["time"] += cost_of_bug(bug)
if random.randint(0, 5) is 4:
remove_bug(bug)
break
@atom
def perform_integration_tests():
if len(environment.resources["bugs"]) == 0:
environment.resources["integration tests passing"] = True
return True
number_of_messy_bugs = random.randint(0,len(environment.resources["bugs"]))
environment.resources["integration tests passing"] = number_of_messy_bugs == 0
return environment.resources["integration tests passing"]
@atom
def run_tests():
environment.resources["unit tests passing"] = number_of_detected_bugs() == 0
return environment.resources["unit tests passing"]
@atom
def perform_user_acceptance_testing():
environment.resources["time"] += 1
environment.resources["user acceptance tests passing"] = environment.resources["unit tests passing"]
return environment.resources["user acceptance tests passing"]
| artistic-2.0 | 1,352,275,259,262,162,400 | 28.561905 | 104 | 0.615818 | false |
PacktPublishing/OpenCV-Computer-Vision-Projects-with-Python | Module 3/07_code/chapter7.py | 1 | 11356 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""OpenCV with Python Blueprints
Chapter 7: Learning to Recognize Emotion in Faces
An app that combines both face detection and face recognition, with a
focus on recognizing emotional expressions in the detected faces.
The process flow is as follows:
* Run the GUI in Training Mode to assemble a training set. Upon exiting
the app will dump all assembled training samples to a pickle file
"datasets/faces_training.pkl".
* Run the script train_test_mlp.py to train a MLP classifier on the
dataset. This file will store the parameters of the trained MLP in
a file "params/mlp.xml" and dump the preprocessed dataset to a
pickle file "datasets/faces_preprocessed.pkl".
* Run the GUI in Testing Mode to apply the pre-trained MLP classifier
to the live stream of the webcam.
"""
import cv2
import numpy as np
import time
import wx
from os import path
import cPickle as pickle
from datasets import homebrew
from detectors import FaceDetector
from classifiers import MultiLayerPerceptron
from gui import BaseLayout
__author__ = "Michael Beyeler"
__license__ = "GNU GPL 3.0 or later"
class FaceLayout(BaseLayout):
"""A custom layout for face detection and facial expression recognition
A GUI to both assemble a training set and to perform real-time
classification on the live stream of a webcam using a pre-trained
classifier.
The GUI operates in two different modes:
* Training Mode: In training mode, the app will collect image frames,
detect a face therein, assignassign a label depending
on the facial expression, and upon exiting save all
collected data samples in a file, so that it can be
parsed by datasets.homebrew.
* Testing Mode: In testing mode, the app will detect a face in each
video frame and predict the corresponding class
label using a pre-trained MLP.
"""
def _init_custom_layout(self):
"""Initializes GUI"""
# initialize data structure
self.samples = []
self.labels = []
# call method to save data upon exiting
self.Bind(wx.EVT_CLOSE, self._on_exit)
def init_algorithm(
self,
save_training_file='datasets/faces_training.pkl',
load_preprocessed_data='datasets/faces_preprocessed.pkl',
load_mlp='params/mlp.xml',
face_casc='params/haarcascade_frontalface_default.xml',
left_eye_casc='params/haarcascade_lefteye_2splits.xml',
right_eye_casc='params/haarcascade_righteye_2splits.xml'):
"""Initializes face detector and facial expression classifier
This method initializes both the face detector and the facial
expression classifier.
:param save_training_file: filename for storing the assembled
training set
:param load_preprocessed_data: filename for loading a previously
preprocessed dataset (for
classification in Testing Mode)
:param load_mlp: filename for loading a pre-trained
MLP classifier (use the script
train_test_mlp.py)
:param face_casc: path to a face cascade
:param left_eye_casc: path to a left-eye cascade
:param right_eye_casc: path to a right-eye cascade
"""
self.data_file = save_training_file
self.faces = FaceDetector(face_casc, left_eye_casc, right_eye_casc)
# load preprocessed dataset to access labels and PCA params
if path.isfile(load_preprocessed_data):
(_, y_train), (_, y_test), V, m = homebrew.load_from_file(
load_preprocessed_data)
self.pca_V = V
self.pca_m = m
self.all_labels = np.unique(np.hstack((y_train, y_test)))
# load pre-trained multi-layer perceptron
if path.isfile(load_mlp):
layer_sizes = np.array([self.pca_V.shape[1],
len(self.all_labels)])
self.MLP = MultiLayerPerceptron(layer_sizes, self.all_labels)
self.MLP.load(load_mlp)
else:
print "Warning: Testing is disabled"
print "Could not find pre-trained MLP file ", load_mlp
self.testing.Disable()
else:
print "Warning: Testing is disabled"
print "Could not find data file ", load_preprocessed_data
self.testing.Disable()
def _create_custom_layout(self):
"""Decorates the GUI with buttons for assigning class labels"""
# create horizontal layout with train/test buttons
pnl1 = wx.Panel(self, -1)
self.training = wx.RadioButton(pnl1, -1, 'Train', (10, 10),
style=wx.RB_GROUP)
self.Bind(wx.EVT_RADIOBUTTON, self._on_training, self.training)
self.testing = wx.RadioButton(pnl1, -1, 'Test')
self.Bind(wx.EVT_RADIOBUTTON, self._on_testing, self.testing)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
hbox1.Add(self.training, 1)
hbox1.Add(self.testing, 1)
pnl1.SetSizer(hbox1)
# create a horizontal layout with all buttons
pnl2 = wx.Panel(self, -1)
self.neutral = wx.RadioButton(pnl2, -1, 'neutral', (10, 10),
style=wx.RB_GROUP)
self.happy = wx.RadioButton(pnl2, -1, 'happy')
self.sad = wx.RadioButton(pnl2, -1, 'sad')
self.surprised = wx.RadioButton(pnl2, -1, 'surprised')
self.angry = wx.RadioButton(pnl2, -1, 'angry')
self.disgusted = wx.RadioButton(pnl2, -1, 'disgusted')
hbox2 = wx.BoxSizer(wx.HORIZONTAL)
hbox2.Add(self.neutral, 1)
hbox2.Add(self.happy, 1)
hbox2.Add(self.sad, 1)
hbox2.Add(self.surprised, 1)
hbox2.Add(self.angry, 1)
hbox2.Add(self.disgusted, 1)
pnl2.SetSizer(hbox2)
# create horizontal layout with single snapshot button
pnl3 = wx.Panel(self, -1)
self.snapshot = wx.Button(pnl3, -1, 'Take Snapshot')
self.Bind(wx.EVT_BUTTON, self._on_snapshot, self.snapshot)
hbox3 = wx.BoxSizer(wx.HORIZONTAL)
hbox3.Add(self.snapshot, 1)
pnl3.SetSizer(hbox3)
# arrange all horizontal layouts vertically
self.panels_vertical.Add(pnl1, flag=wx.EXPAND | wx.TOP, border=1)
self.panels_vertical.Add(pnl2, flag=wx.EXPAND | wx.BOTTOM, border=1)
self.panels_vertical.Add(pnl3, flag=wx.EXPAND | wx.BOTTOM, border=1)
def _process_frame(self, frame):
"""Processes each captured frame
This method processes each captured frame.
* Training mode: Performs face detection.
* Testing mode: Performs face detection, and predicts the class
label of the facial expression.
"""
# detect face
success, frame, self.head = self.faces.detect(frame)
if success and self.testing.GetValue():
# if face found: preprocess (align)
success, head = self.faces.align_head(self.head)
if success:
# extract features using PCA (loaded from file)
X, _, _ = homebrew.extract_features([head.flatten()],
self.pca_V, self.pca_m)
# predict label with pre-trained MLP
label = self.MLP.predict(np.array(X))[0]
# draw label above bounding box
cv2.putText(frame, str(label), (x, y - 20),
cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2)
return frame
def _on_training(self, evt):
"""Enables all training-related buttons when Training Mode is on"""
self.neutral.Enable()
self.happy.Enable()
self.sad.Enable()
self.surprised.Enable()
self.angry.Enable()
self.disgusted.Enable()
self.snapshot.Enable()
def _on_testing(self, evt):
"""Disables all training-related buttons when Testing Mode is on"""
self.neutral.Disable()
self.happy.Disable()
self.sad.Disable()
self.surprised.Disable()
self.angry.Disable()
self.disgusted.Disable()
self.snapshot.Disable()
def _on_snapshot(self, evt):
"""Takes a snapshot of the current frame
This method takes a snapshot of the current frame, preprocesses
it to extract the head region, and upon success adds the data
sample to the training set.
"""
if self.neutral.GetValue():
label = 'neutral'
elif self.happy.GetValue():
label = 'happy'
elif self.sad.GetValue():
label = 'sad'
elif self.surprised.GetValue():
label = 'surprised'
elif self.angry.GetValue():
label = 'angry'
elif self.disgusted.GetValue():
label = 'disgusted'
if self.head is None:
print "No face detected"
else:
success, head = self.faces.align_head(self.head)
if success:
print "Added sample to training set"
self.samples.append(head.flatten())
self.labels.append(label)
else:
print "Could not align head (eye detection failed?)"
def _on_exit(self, evt):
"""Dumps the training data to file upon exiting"""
# if we have collected some samples, dump them to file
if len(self.samples) > 0:
# make sure we don't overwrite an existing file
if path.isfile(self.data_file):
# file already exists, construct new load_from_file
load_from_file, fileext = path.splitext(self.data_file)
offset = 0
while True:
file = load_from_file + "-" + str(offset) + fileext
if path.isfile(file):
offset += 1
else:
break
self.data_file = file
# dump samples and labels to file
f = open(self.data_file, 'wb')
pickle.dump(self.samples, f)
pickle.dump(self.labels, f)
f.close()
# inform user that file was created
print "Saved", len(self.samples), "samples to", self.data_file
# deallocate
self.Destroy()
def main():
capture = cv2.VideoCapture(0)
if not(capture.isOpened()):
capture.open()
capture.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 640)
capture.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 480)
# start graphical user interface
app = wx.App()
layout = FaceLayout(None, -1, 'Facial Expression Recognition', capture)
layout.init_algorithm()
layout.Show(True)
app.MainLoop()
if __name__ == '__main__':
main()
| mit | -2,689,338,171,623,602,000 | 38.430556 | 78 | 0.57714 | false |
js0701/chromium-crosswalk | third_party/WebKit/Tools/Scripts/webkitpy/common/checkout/scm/scm_mock.py | 11 | 4081 | # Copyright (C) 2011 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from webkitpy.common.system.filesystem_mock import MockFileSystem
from webkitpy.common.system.executive_mock import MockExecutive
class MockSCM(object):
executable_name = "MockSCM"
def __init__(self, filesystem=None, executive=None):
self.checkout_root = "/mock-checkout"
self.added_paths = set()
self._filesystem = filesystem or MockFileSystem()
self._executive = executive or MockExecutive()
def add(self, destination_path, return_exit_code=False):
self.add_list([destination_path], return_exit_code)
def add_list(self, destination_paths, return_exit_code=False):
self.added_paths.update(set(destination_paths))
if return_exit_code:
return 0
def has_working_directory_changes(self):
return False
def ensure_cleanly_tracking_remote_master(self):
pass
def current_branch(self):
return "mock-branch-name"
def checkout_branch(self, name):
pass
def create_clean_branch(self, name):
pass
def delete_branch(self, name):
pass
def supports_local_commits(self):
return True
def exists(self, path):
# TestRealMain.test_real_main (and several other rebaseline tests) are sensitive to this return value.
# We should make those tests more robust, but for now we just return True always (since no test needs otherwise).
return True
def absolute_path(self, *comps):
return self._filesystem.join(self.checkout_root, *comps)
def commit_position(self, path):
return 5678
def commit_position_from_git_commit(self, git_commit):
if git_commit == '6469e754a1':
return 1234
if git_commit == '624c3081c0':
return 5678
if git_commit == '624caaaaaa':
return 10000
return None
def timestamp_of_revision(self, path, revision):
return '2013-02-01 08:48:05 +0000'
def commit_locally_with_message(self, message, commit_all_working_directory_changes=True):
pass
def delete(self, path):
return self.delete_list([path])
def delete_list(self, paths):
if not self._filesystem:
return
for path in paths:
if self._filesystem.exists(path):
self._filesystem.remove(path)
def move(self, origin, destination):
if self._filesystem:
self._filesystem.move(self.absolute_path(origin), self.absolute_path(destination))
def changed_files(self):
return []
| bsd-3-clause | 2,878,566,153,286,109,000 | 35.4375 | 121 | 0.694683 | false |
MridulS/BinPy | BinPy/examples/source/ic/Series_4000/IC4072.py | 5 | 1255 | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <headingcell level=2>
# Usage of IC 4072
# <codecell>
from __future__ import print_function
from BinPy import *
# <codecell>
# Usage of IC 4072:
ic = IC_4072()
print(ic.__doc__)
# <codecell>
# The Pin configuration is:
inp = {2: 0, 3: 1, 4: 0, 5: 1, 7: 0, 9: 1, 10: 1, 11: 1, 12: 1, 14: 1}
# Pin initinalization
# Powering up the IC - using -- ic.setIC({14: 1, 7: 0}) -- \n
ic.setIC({14: 1, 7: 0})
# Setting the inputs of the ic
ic.setIC(inp)
# Draw the IC with the current configuration\n
ic.drawIC()
# <codecell>
# Run the IC with the current configuration using -- print ic.run() --
# Note that the ic.run() returns a dict of pin configuration similar to
print (ic.run())
# <codecell>
# Seting the outputs to the current IC configuration using --
# ic.setIC(ic.run()) --\n
ic.setIC(ic.run())
# Draw the final configuration
ic.drawIC()
# <codecell>
# Seting the outputs to the current IC configuration using --
# ic.setIC(ic.run()) --
ic.setIC(ic.run())
# Draw the final configuration
ic.drawIC()
# Run the IC
print (ic.run())
# <codecell>
# Connector Outputs
c = Connector()
# Set the output connector to a particular pin of the ic
ic.setOutput(13, c)
print(c)
| bsd-3-clause | 6,033,693,259,011,766,000 | 14.120482 | 71 | 0.647012 | false |
ncollins/lis.py | test_eval.py | 1 | 2737 |
from lex import tokenize
from parse import parse_tokens
from evaluate import eval_in_env, Environment
def test_eval_add_const():
exp = ['+', 3, 4]
res = eval_in_env(exp, Environment([]))
assert res == 7
def test_eval_if():
exp = ['if', True, 3, 4]
assert eval_in_env(exp, Environment([])) == 3
def test_eval_cond_true():
exp = ['cond', [['>', 4, 3], 1], ['else', 0]]
assert eval_in_env(exp, Environment([])) == 1
def test_eval_cond_false():
exp = ['cond', [['>', 4, 4], 1], ['else', 0]]
assert eval_in_env(exp, Environment([])) == 0
def test_eval_let():
exp = ['let', [['x', 3], ['y', 10]], ['+', 'x', 'y']]
assert eval_in_env(exp, Environment([])) == 13
def test_eval_define():
env = Environment([])
exp = ['define', 'a', 3]
eval_in_env(exp, env)
#assert env._env == [['a', 3]]
assert env.lookup('a') == 3
def test_eval_closure():
env = Environment([['add3', ['closure', ['lambda', ['x'], ['+', 'x', 3]], []]]])
exp = ['add3', 10]
assert eval_in_env(exp, env) == 13
def test_eval_closure_2():
env = Environment([['ifthen', ['closure', ['lambda', ['x'], ['if', True, 'x', 3]], []]]])
exp = ['ifthen', 10]
assert eval_in_env(exp, env) == 10
def test_eval_recursion():
env = Environment([['sumto', ['closure', ['lambda', ['n'],
['if', ['<', 'n', 1],
0,
['+', 'n', ['sumto', ['-', 'n', 1]]]]],
[]]]])
exp = ['sumto', 3]
assert eval_in_env(exp, env) == 6
def test_eval_recursion_2():
env = Environment([['factorial', ['closure', ['lambda', ['n'],
['if', ['<', 'n', 1], 1, ['*', 'n', ['factorial', ['-', 'n', 1]]]]], []]]])
exp = ['factorial', 5]
assert eval_in_env(exp, env) == 120
def test_eval_anon():
exp = [['lambda', ['x'], ['+', 'x', 'x']], 7]
assert eval_in_env(exp, Environment([])) == 14
def test_eval_set():
env = Environment([['a', 0]])
exp = ['set!', 'a', 10]
eval_in_env(exp, env)
assert env.lookup('a') == 10
def test_eval_begin():
exp = ['begin', ['define', 'a', 0], ['set!', 'a', 10], 'a']
assert eval_in_env(exp, Environment([])) == 10
def test_eval_modulo():
assert 0 == eval_in_env(['modulo', 9, 3], Environment([]))
assert 1 == eval_in_env(['modulo', 10, 3], Environment([]))
assert 2 == eval_in_env(['modulo', 11, 3], Environment([]))
def test_eval_not():
assert True == eval_in_env(['not', False], Environment([]))
assert False == eval_in_env(['not', True], Environment([]))
assert False == eval_in_env(['not', 'null'], Environment([]))
| bsd-3-clause | -8,867,205,229,933,264,000 | 27.810526 | 101 | 0.480453 | false |
moonrisewarrior/line-memebot | SDK/linebot/models/error.py | 4 | 1976 | # -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""linebot.models.error module."""
from __future__ import unicode_literals
from .base import Base
class Error(Base):
"""Error response of LINE messaging API.
https://devdocs.line.me/en/#error-response
"""
def __init__(self, message=None, details=None, **kwargs):
"""__init__ method.
:param str message: Summary of the error
:param details: ErrorDetail instance list
:type details: list[T <= :py:class:`linebot.models.error.ErrorDetail`]
:type
:param kwargs:
"""
super(Error, self).__init__(**kwargs)
self.message = message
new_details = []
if details:
for detail in details:
new_details.append(
self.get_or_new_from_json_dict(detail, ErrorDetail)
)
self.details = new_details
class ErrorDetail(Base):
"""ErrorDetail response of LINE messaging API.
https://devdocs.line.me/en/#error-response
"""
def __init__(self, message=None, property=None, **kwargs):
"""__init__ method.
https://devdocs.line.me/en/#error-response
:param str message: Details of the error message
:param str property: Related property
:param kwargs:
"""
super(ErrorDetail, self).__init__(**kwargs)
self.message = message
self.property = property
| apache-2.0 | 2,348,168,993,860,958,700 | 28.058824 | 78 | 0.62753 | false |
ghtdak/txtorcon | test/test_torcontrolprotocol.py | 1 | 34121 | from __future__ import with_statement
from os.path import exists
from twisted.python import log, failure
from twisted.trial import unittest
from twisted.test import proto_helpers
from twisted.internet import defer, error
from txtorcon import TorControlProtocol, TorProtocolFactory, TorState
from txtorcon import ITorControlProtocol
from txtorcon.torcontrolprotocol import parse_keywords, DEFAULT_VALUE
from txtorcon.util import hmac_sha256
import types
import functools
import tempfile
import base64
class CallbackChecker:
def __init__(self, expected):
self.expected_value = expected
self.called_back = False
def __call__(self, *args, **kwargs):
v = args[0]
if v != self.expected_value:
print "WRONG"
raise RuntimeError(
'Expected "%s" but got "%s"' % (self.expected_value, v)
)
self.called_back = True
return v
class InterfaceTests(unittest.TestCase):
def test_implements(self):
self.assertTrue(ITorControlProtocol.implementedBy(TorControlProtocol))
def test_object_implements(self):
self.assertTrue(ITorControlProtocol.providedBy(TorControlProtocol()))
class LogicTests(unittest.TestCase):
def setUp(self):
self.protocol = TorControlProtocol()
self.protocol.connectionMade = lambda: None
self.transport = proto_helpers.StringTransport()
self.protocol.makeConnection(self.transport)
def test_set_conf_wrong_args(self):
ctl = TorControlProtocol()
d = ctl.set_conf('a')
self.assertTrue(d.called)
self.assertTrue(d.result)
self.assertTrue('even number' in d.result.getErrorMessage())
# ignore the error so trial doesn't get unhappy
d.addErrback(lambda foo: True)
return d
class FactoryTests(unittest.TestCase):
def test_create(self):
TorProtocolFactory().buildProtocol(None)
class AuthenticationTests(unittest.TestCase):
def setUp(self):
self.protocol = TorControlProtocol()
self.transport = proto_helpers.StringTransport()
def send(self, line):
self.protocol.dataReceived(line.strip() + "\r\n")
def test_authenticate_cookie(self):
self.protocol.makeConnection(self.transport)
self.assertEqual(self.transport.value(), 'PROTOCOLINFO 1\r\n')
self.transport.clear()
cookie_data = 'cookiedata!cookiedata!cookiedata'
with open('authcookie', 'w') as f:
f.write(cookie_data)
self.send('250-PROTOCOLINFO 1')
self.send('250-AUTH METHODS=COOKIE,HASHEDPASSWORD COOKIEFILE="authcookie"')
self.send('250-VERSION Tor="0.2.2.34"')
self.send('250 OK')
self.assertEqual(
self.transport.value(),
'AUTHENTICATE %s\r\n' % cookie_data.encode("hex")
)
def test_authenticate_password(self):
self.protocol.password_function = lambda: 'foo'
self.protocol.makeConnection(self.transport)
self.assertEqual(self.transport.value(), 'PROTOCOLINFO 1\r\n')
self.transport.clear()
self.send('250-PROTOCOLINFO 1')
self.send('250-AUTH METHODS=HASHEDPASSWORD')
self.send('250-VERSION Tor="0.2.2.34"')
self.send('250 OK')
self.assertEqual(self.transport.value(), 'AUTHENTICATE %s\r\n' % "foo".encode("hex"))
def test_authenticate_password_deferred(self):
d = defer.Deferred()
self.protocol.password_function = lambda: d
self.protocol.makeConnection(self.transport)
self.assertEqual(self.transport.value(), 'PROTOCOLINFO 1\r\n')
self.transport.clear()
self.send('250-PROTOCOLINFO 1')
self.send('250-AUTH METHODS=HASHEDPASSWORD')
self.send('250-VERSION Tor="0.2.2.34"')
self.send('250 OK')
# make sure we haven't tried to authenticate before getting
# the password callback
self.assertEqual(self.transport.value(), '')
d.callback('foo')
# now make sure we DID try to authenticate
self.assertEqual(
self.transport.value(),
'AUTHENTICATE %s\r\n' % "foo".encode("hex")
)
def test_authenticate_password_deferred_but_no_password(self):
d = defer.Deferred()
self.protocol.password_function = lambda: d
self.protocol.makeConnection(self.transport)
self.assertEqual(self.transport.value(), 'PROTOCOLINFO 1\r\n')
self.transport.clear()
self.send('250-PROTOCOLINFO 1')
self.send('250-AUTH METHODS=HASHEDPASSWORD')
self.send('250-VERSION Tor="0.2.2.34"')
self.send('250 OK')
d.callback(None)
return self.assertFailure(self.protocol.post_bootstrap, RuntimeError)
def confirmAuthFailed(self, *args):
self.auth_failed = True
def test_authenticate_no_password(self):
self.protocol.post_bootstrap.addErrback(self.confirmAuthFailed)
self.auth_failed = False
self.protocol.makeConnection(self.transport)
self.assertEqual(self.transport.value(), 'PROTOCOLINFO 1\r\n')
self.send('250-PROTOCOLINFO 1')
self.send('250-AUTH METHODS=HASHEDPASSWORD')
self.send('250-VERSION Tor="0.2.2.34"')
self.send('250 OK')
self.assertTrue(self.auth_failed)
class DisconnectionTests(unittest.TestCase):
def setUp(self):
self.protocol = TorControlProtocol()
self.protocol.connectionMade = lambda: None
self.transport = proto_helpers.StringTransportWithDisconnection()
self.protocol.makeConnection(self.transport)
# why doesn't makeConnection do this?
self.transport.protocol = self.protocol
def tearDown(self):
self.protocol = None
def test_disconnect_callback(self):
"""
see that we get our callback on_disconnect if the transport
goes away
"""
def it_was_called(*args):
it_was_called.yes = True
return None
it_was_called.yes = False
self.protocol.on_disconnect.addCallback(it_was_called)
self.protocol.on_disconnect.addErrback(it_was_called)
f = failure.Failure(error.ConnectionDone("It's all over"))
self.protocol.connectionLost(f)
self.assertTrue(it_was_called.yes)
def test_disconnect_errback(self):
"""
see that we get our callback on_disconnect if the transport
goes away
"""
def it_was_called(*args):
it_was_called.yes = True
return None
it_was_called.yes = False
self.protocol.on_disconnect.addCallback(it_was_called)
self.protocol.on_disconnect.addErrback(it_was_called)
f = failure.Failure(RuntimeError("The thing didn't do the stuff."))
self.protocol.connectionLost(f)
self.assertTrue(it_was_called.yes)
class ProtocolTests(unittest.TestCase):
def setUp(self):
self.protocol = TorControlProtocol()
self.protocol.connectionMade = lambda: None
self.transport = proto_helpers.StringTransport()
self.protocol.makeConnection(self.transport)
def tearDown(self):
self.protocol = None
def send(self, line):
self.protocol.dataReceived(line.strip() + "\r\n")
def test_statemachine_broadcast_no_code(self):
try:
self.protocol._broadcast_response("foo")
self.fail()
except RuntimeError, e:
self.assertTrue('No code set yet' in str(e))
def test_statemachine_broadcast_unknown_code(self):
try:
self.protocol.code = 999
self.protocol._broadcast_response("foo")
self.fail()
except RuntimeError, e:
self.assertTrue('Unknown code' in str(e))
def test_statemachine_is_finish(self):
self.assertTrue(not self.protocol._is_finish_line(''))
self.assertTrue(self.protocol._is_finish_line('.'))
self.assertTrue(self.protocol._is_finish_line('300 '))
self.assertTrue(not self.protocol._is_finish_line('250-'))
def test_statemachine_singleline(self):
self.assertTrue(not self.protocol._is_single_line_response('foo'))
def test_statemachine_continuation(self):
try:
self.protocol.code = 250
self.protocol._is_continuation_line("123 ")
self.fail()
except RuntimeError, e:
self.assertTrue('Unexpected code' in str(e))
def test_statemachine_multiline(self):
try:
self.protocol.code = 250
self.protocol._is_multi_line("123 ")
self.fail()
except RuntimeError, e:
self.assertTrue('Unexpected code' in str(e))
def auth_failed(self, msg):
self.assertEqual(str(msg.value), '551 go away')
self.got_auth_failed = True
def test_authenticate_fail(self):
self.got_auth_failed = False
self.protocol._auth_failed = self.auth_failed
self.protocol.password_function = lambda: 'foo'
self.protocol._do_authenticate('''PROTOCOLINFO 1
AUTH METHODS=HASHEDPASSWORD
VERSION Tor="0.2.2.35"
OK''')
self.send('551 go away\r\n')
self.assertTrue(self.got_auth_failed)
def test_authenticate_no_auth_line(self):
try:
self.protocol._do_authenticate('''PROTOCOLINFO 1
FOOAUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/dev/null"
VERSION Tor="0.2.2.35"
OK''')
self.assertTrue(False)
except RuntimeError, e:
self.assertTrue('find AUTH line' in str(e))
def test_authenticate_not_enough_cookie_data(self):
with tempfile.NamedTemporaryFile() as cookietmp:
cookietmp.write('x' * 35) # too much data
cookietmp.flush()
try:
self.protocol._do_authenticate('''PROTOCOLINFO 1
AUTH METHODS=COOKIE COOKIEFILE="%s"
VERSION Tor="0.2.2.35"
OK''' % cookietmp.name)
self.assertTrue(False)
except RuntimeError, e:
self.assertTrue('cookie to be 32' in str(e))
def test_authenticate_not_enough_safecookie_data(self):
with tempfile.NamedTemporaryFile() as cookietmp:
cookietmp.write('x' * 35) # too much data
cookietmp.flush()
try:
self.protocol._do_authenticate('''PROTOCOLINFO 1
AUTH METHODS=SAFECOOKIE COOKIEFILE="%s"
VERSION Tor="0.2.2.35"
OK''' % cookietmp.name)
self.assertTrue(False)
except RuntimeError, e:
self.assertTrue('cookie to be 32' in str(e))
def test_authenticate_safecookie(self):
with tempfile.NamedTemporaryFile() as cookietmp:
cookiedata = str(bytearray([0] * 32))
cookietmp.write(cookiedata)
cookietmp.flush()
self.protocol._do_authenticate('''PROTOCOLINFO 1
AUTH METHODS=SAFECOOKIE COOKIEFILE="%s"
VERSION Tor="0.2.2.35"
OK''' % cookietmp.name)
self.assertTrue(
'AUTHCHALLENGE SAFECOOKIE ' in self.transport.value()
)
client_nonce = base64.b16decode(self.transport.value().split()[-1])
self.transport.clear()
server_nonce = str(bytearray([0] * 32))
server_hash = hmac_sha256(
"Tor safe cookie authentication server-to-controller hash",
cookiedata + client_nonce + server_nonce
)
self.send(
'250 AUTHCHALLENGE SERVERHASH=%s SERVERNONCE=%s' %
(base64.b16encode(server_hash), base64.b16encode(server_nonce))
)
self.assertTrue('AUTHENTICATE ' in self.transport.value())
def test_authenticate_safecookie_wrong_hash(self):
cookiedata = str(bytearray([0] * 32))
server_nonce = str(bytearray([0] * 32))
server_hash = str(bytearray([0] * 32))
# pretend we already did PROTOCOLINFO and read the cookie
# file
self.protocol.cookie_data = cookiedata
self.protocol.client_nonce = server_nonce # all 0's anyway
try:
self.protocol._safecookie_authchallenge(
'250 AUTHCHALLENGE SERVERHASH=%s SERVERNONCE=%s' %
(base64.b16encode(server_hash), base64.b16encode(server_nonce))
)
self.assertTrue(False)
except RuntimeError, e:
self.assertTrue('hash not expected' in str(e))
def confirm_version_events(self, arg):
self.assertEqual(self.protocol.version, 'foo')
events = 'GUARD STREAM CIRC NS NEWCONSENSUS ORCONN NEWDESC ADDRMAP STATUS_GENERAL'.split()
self.assertEqual(len(self.protocol.valid_events), len(events))
self.assertTrue(all(x in self.protocol.valid_events for x in events))
def test_bootstrap_callback(self):
d = self.protocol.post_bootstrap
d.addCallback(CallbackChecker(self.protocol))
d.addCallback(self.confirm_version_events)
events = 'GUARD STREAM CIRC NS NEWCONSENSUS ORCONN NEWDESC ADDRMAP STATUS_GENERAL'
self.protocol._bootstrap()
# answer all the requests generated by boostrapping etc.
self.send("250-signal/names=")
self.send("250 OK")
self.send("250-version=foo")
self.send("250 OK")
self.send("250-events/names=" + events)
self.send("250 OK")
self.send("250 OK") # for USEFEATURE
return d
def test_bootstrap_tor_does_not_support_signal_names(self):
self.protocol._bootstrap()
self.send('552 Unrecognized key "signal/names"')
valid_signals = ["RELOAD", "DUMP", "DEBUG", "NEWNYM", "CLEARDNSCACHE"]
self.assertEqual(self.protocol.valid_signals, valid_signals)
def test_async(self):
"""
test the example from control-spec.txt to see that we
handle interleaved async notifications properly.
"""
self.protocol._set_valid_events('CIRC')
self.protocol.add_event_listener('CIRC', lambda _: None)
self.send("250 OK")
d = self.protocol.get_conf("SOCKSPORT ORPORT")
self.send("650 CIRC 1000 EXTENDED moria1,moria2")
self.send("250-SOCKSPORT=9050")
self.send("250 ORPORT=0")
return d
def test_async_multiline(self):
# same as above, but i think the 650's can be multline,
# too. Like:
# 650-CIRC 1000 EXTENDED moria1,moria2 0xBEEF
# 650-EXTRAMAGIC=99
# 650 ANONYMITY=high
self.protocol._set_valid_events('CIRC')
self.protocol.add_event_listener(
'CIRC',
CallbackChecker(
"1000 EXTENDED moria1,moria2\nEXTRAMAGIC=99\nANONYMITY=high"
)
)
self.send("250 OK")
d = self.protocol.get_conf("SOCKSPORT ORPORT")
d.addCallback(CallbackChecker({"ORPORT": "0", "SOCKSPORT": "9050"}))
self.send("650-CIRC 1000 EXTENDED moria1,moria2")
self.send("650-EXTRAMAGIC=99")
self.send("650 ANONYMITY=high")
self.send("250-SOCKSPORT=9050")
self.send("250 ORPORT=0")
return d
def test_multiline_plus(self):
"""
"""
d = self.protocol.get_info("FOO")
d.addCallback(CallbackChecker({"FOO": "\na\nb\nc"}))
self.send("250+FOO=")
self.send("a")
self.send("b")
self.send("c")
self.send(".")
self.send("250 OK")
return d
def incremental_check(self, expected, actual):
if '=' in actual:
return
self.assertEqual(expected, actual)
def test_getinfo_incremental(self):
d = self.protocol.get_info_incremental(
"FOO",
functools.partial(self.incremental_check, "bar")
)
self.send("250+FOO=")
self.send("bar")
self.send("bar")
self.send(".")
self.send("250 OK")
return d
def test_getinfo_incremental_continuation(self):
d = self.protocol.get_info_incremental(
"FOO",
functools.partial(self.incremental_check, "bar")
)
self.send("250-FOO=")
self.send("250-bar")
self.send("250-bar")
self.send("250 OK")
return d
def test_getinfo_one_line(self):
d = self.protocol.get_info(
"foo",
functools.partial(self.incremental_check, "bar")
)
self.send('250 foo=bar')
return d
def test_getconf(self):
d = self.protocol.get_conf("SOCKSPORT ORPORT")
d.addCallback(CallbackChecker({'SocksPort': '9050', 'ORPort': '0'}))
self.send("250-SocksPort=9050")
self.send("250 ORPort=0")
return d
def test_getconf_raw(self):
d = self.protocol.get_conf_raw("SOCKSPORT ORPORT")
d.addCallback(CallbackChecker('SocksPort=9050\nORPort=0'))
self.send("250-SocksPort=9050")
self.send("250 ORPort=0")
return d
def response_ok(self, v):
self.assertEqual(v, '')
def test_setconf(self):
d = self.protocol.set_conf("foo", "bar").addCallback(
functools.partial(self.response_ok)
)
self.send("250 OK")
self._wait(d)
self.assertEqual(self.transport.value(), "SETCONF foo=bar\r\n")
def test_setconf_with_space(self):
d = self.protocol.set_conf("foo", "a value with a space")
d.addCallback(functools.partial(self.response_ok))
self.send("250 OK")
self._wait(d)
self.assertEqual(
self.transport.value(),
'SETCONF foo="a value with a space"\r\n'
)
def test_setconf_multi(self):
d = self.protocol.set_conf("foo", "bar", "baz", 1)
self.send("250 OK")
self._wait(d)
self.assertEqual(self.transport.value(), "SETCONF foo=bar baz=1\r\n")
def test_quit(self):
d = self.protocol.quit()
self.send("250 OK")
self._wait(d)
self.assertEqual(self.transport.value(), "QUIT\r\n")
def test_dot(self):
# just checking we don't expode
self.protocol.graphviz_data()
def test_debug(self):
self.protocol.start_debug()
self.assertTrue(exists('txtorcon-debug.log'))
def error(self, failure):
print "ERROR", failure
self.assertTrue(False)
def test_twocommands(self):
"Two commands on the wire before first response."
d1 = self.protocol.get_conf("FOO")
ht = {"a": "one", "b": "two"}
d1.addCallback(CallbackChecker(ht)).addErrback(log.err)
d2 = self.protocol.get_info_raw("BAR")
d2.addCallback(CallbackChecker("bar")).addErrback(log.err)
self.send("250-a=one")
self.send("250-b=two")
self.send("250 OK")
self.send("250 bar")
return d2
def test_signal_error(self):
try:
self.protocol.signal('FOO')
self.fail()
except Exception, e:
self.assertTrue('Invalid signal' in str(e))
def test_signal(self):
self.protocol.valid_signals = ['NEWNYM']
self.protocol.signal('NEWNYM')
self.assertEqual(self.transport.value(), 'SIGNAL NEWNYM\r\n')
def test_650_after_authenticate(self):
self.protocol._set_valid_events('CONF_CHANGED')
self.protocol.add_event_listener(
'CONF_CHANGED',
CallbackChecker("Foo=bar")
)
self.send("250 OK")
self.send("650-CONF_CHANGED")
self.send("650-Foo=bar")
def test_notify_after_getinfo(self):
self.protocol._set_valid_events('CIRC')
self.protocol.add_event_listener(
'CIRC',
CallbackChecker("1000 EXTENDED moria1,moria2")
)
self.send("250 OK")
d = self.protocol.get_info("a")
d.addCallback(CallbackChecker({'a': 'one'})).addErrback(self.fail)
self.send("250-a=one")
self.send("250 OK")
self.send("650 CIRC 1000 EXTENDED moria1,moria2")
return d
def test_notify_error(self):
self.protocol._set_valid_events('CIRC')
self.send("650 CIRC 1000 EXTENDED moria1,moria2")
def test_getinfo(self):
d = self.protocol.get_info("version")
d.addCallback(CallbackChecker({'version': '0.2.2.34'}))
d.addErrback(self.fail)
self.send("250-version=0.2.2.34")
self.send("250 OK")
self.assertEqual(self.transport.value(), "GETINFO version\r\n")
return d
def test_getinfo_for_descriptor(self):
descriptor_info = """250+desc/name/moria1=
router moria1 128.31.0.34 9101 0 9131
platform Tor 0.2.5.0-alpha-dev on Linux
protocols Link 1 2 Circuit 1
published 2013-07-05 23:48:52
fingerprint 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31
uptime 1818933
bandwidth 512000 62914560 1307929
extra-info-digest 17D0142F6EBCDF60160EB1794FA6C9717D581F8C
caches-extra-info
onion-key
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBALzd4bhz1usB7wpoaAvP+BBOnNIk7mByAKV6zvyQ0p1M09oEmxPMc3qD
AAm276oJNf0eq6KWC6YprzPWFsXEIdXSqA6RWXCII1JG/jOoy6nt478BkB8TS9I9
1MJW27ppRaqnLiTmBmM+qzrsgJGwf+onAgUKKH2GxlVgahqz8x6xAgMBAAE=
-----END RSA PUBLIC KEY-----
signing-key
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBALtJ9uD7cD7iHjqNA3AgsX9prES5QN+yFQyr2uOkxzhvunnaf6SNhzWW
bkfylnMrRm/qCz/czcjZO6N6EKHcXmypehvP566B7gAQ9vDsb+l7VZVWgXvzNc2s
tl3P7qpC08rgyJh1GqmtQTCesIDqkEyWxwToympCt09ZQRq+fIttAgMBAAE=
-----END RSA PUBLIC KEY-----
hidden-service-dir
contact 1024D/28988BF5 arma mit edu
ntor-onion-key 9ZVjNkf/iLEnD685SpC5kcDytQ7u5ViiI9JOftdbE0k=
reject *:*
router-signature
-----BEGIN SIGNATURE-----
Y8Tj2e7mPbFJbguulkPEBVYzyO57p4btpWEXvRMD6vxIh/eyn25pehg5dUVBtZlL
iO3EUE0AEYah2W9gdz8t+i3Dtr0zgqLS841GC/TyDKCm+MKmN8d098qnwK0NGF9q
01NZPuSqXM1b6hnl2espFzL7XL8XEGRU+aeg+f/ukw4=
-----END SIGNATURE-----
.
250 OK"""
d = self.protocol.get_info("desc/name/moria1")
d.addCallback(CallbackChecker({'desc/name/moria1': '\n' + '\n'.join(descriptor_info.split('\n')[1:-2])}))
d.addErrback(self.fail)
for line in descriptor_info.split('\n'):
self.send(line)
return d
def test_addevent(self):
self.protocol._set_valid_events('FOO BAR')
self.protocol.add_event_listener('FOO', lambda _: None)
# is it dangerous/ill-advised to depend on internal state of
# class under test?
d = self.protocol.defer
self.send("250 OK")
self._wait(d)
self.assertEqual(
self.transport.value().split('\r\n')[-2],
"SETEVENTS FOO"
)
self.transport.clear()
self.protocol.add_event_listener('BAR', lambda _: None)
d = self.protocol.defer
self.send("250 OK")
self.assertTrue(self.transport.value() == "SETEVENTS FOO BAR\r\n" or
self.transport.value() == "SETEVENTS BAR FOO\r\n")
self._wait(d)
try:
self.protocol.add_event_listener(
'SOMETHING_INVALID', lambda _: None
)
self.assertTrue(False)
except:
pass
def test_eventlistener(self):
self.protocol._set_valid_events('STREAM')
class EventListener(object):
stream_events = 0
def __call__(self, data):
self.stream_events += 1
listener = EventListener()
self.protocol.add_event_listener('STREAM', listener)
d = self.protocol.defer
self.send("250 OK")
self._wait(d)
self.send("650 STREAM 1234 NEW 4321 1.2.3.4:555 REASON=MISC")
self.send("650 STREAM 2345 NEW 4321 2.3.4.5:666 REASON=MISC")
self.assertEqual(listener.stream_events, 2)
def test_remove_eventlistener(self):
self.protocol._set_valid_events('STREAM')
class EventListener(object):
stream_events = 0
def __call__(self, data):
self.stream_events += 1
listener = EventListener()
self.protocol.add_event_listener('STREAM', listener)
self.assertEqual(self.transport.value(), 'SETEVENTS STREAM\r\n')
self.protocol.lineReceived("250 OK")
self.transport.clear()
self.protocol.remove_event_listener('STREAM', listener)
self.assertEqual(self.transport.value(), 'SETEVENTS \r\n')
def test_remove_eventlistener_multiple(self):
self.protocol._set_valid_events('STREAM')
class EventListener(object):
stream_events = 0
def __call__(self, data):
self.stream_events += 1
listener0 = EventListener()
listener1 = EventListener()
self.protocol.add_event_listener('STREAM', listener0)
self.assertEqual(self.transport.value(), 'SETEVENTS STREAM\r\n')
self.protocol.lineReceived("250 OK")
self.transport.clear()
# add another one, shouldn't issue a tor command
self.protocol.add_event_listener('STREAM', listener1)
self.assertEqual(self.transport.value(), '')
# remove one, should still not issue a tor command
self.protocol.remove_event_listener('STREAM', listener0)
self.assertEqual(self.transport.value(), '')
# remove the other one, NOW should issue a command
self.protocol.remove_event_listener('STREAM', listener1)
self.assertEqual(self.transport.value(), 'SETEVENTS \r\n')
# try removing invalid event
try:
self.protocol.remove_event_listener('FOO', listener0)
self.fail()
except Exception, e:
self.assertTrue('FOO' in str(e))
def checkContinuation(self, v):
self.assertEqual(v, "key=\nvalue0\nvalue1")
def test_continuationLine(self):
d = self.protocol.get_info_raw("key")
d.addCallback(self.checkContinuation)
self.send("250+key=")
self.send("value0")
self.send("value1")
self.send(".")
self.send("250 OK")
return d
def test_newdesc(self):
"""
FIXME: this test is now maybe a little silly, it's just testing
multiline GETINFO... (Real test is in
TorStateTests.test_newdesc_parse)
"""
self.protocol.get_info_raw('ns/id/624926802351575FF7E4E3D60EFA3BFB56E67E8A')
d = self.protocol.defer
d.addCallback(CallbackChecker("""ns/id/624926802351575FF7E4E3D60EFA3BFB56E67E8A=
r fake YkkmgCNRV1/35OPWDvo7+1bmfoo tanLV/4ZfzpYQW0xtGFqAa46foo 2011-12-12 16:29:16 12.45.56.78 443 80
s Exit Fast Guard HSDir Named Running Stable V2Dir Valid
w Bandwidth=518000
p accept 43,53,79-81,110,143,194,220,443,953,989-990,993,995,1194,1293,1723,1863,2082-2083,2086-2087,2095-2096,3128,4321,5050,5190,5222-5223,6679,6697,7771,8000,8008,8080-8081,8090,8118,8123,8181,8300,8443,8888"""))
self.send("250+ns/id/624926802351575FF7E4E3D60EFA3BFB56E67E8A=")
self.send("r fake YkkmgCNRV1/35OPWDvo7+1bmfoo tanLV/4ZfzpYQW0xtGFqAa46foo 2011-12-12 16:29:16 12.45.56.78 443 80")
self.send("s Exit Fast Guard HSDir Named Running Stable V2Dir Valid")
self.send("w Bandwidth=518000")
self.send("p accept 43,53,79-81,110,143,194,220,443,953,989-990,993,995,1194,1293,1723,1863,2082-2083,2086-2087,2095-2096,3128,4321,5050,5190,5222-5223,6679,6697,7771,8000,8008,8080-8081,8090,8118,8123,8181,8300,8443,8888")
self.send(".")
self.send("250 OK")
return d
def test_plus_line_no_command(self):
self.protocol.lineReceived("650+NS\r\n")
self.protocol.lineReceived("r Gabor gFpAHsFOHGATy12ZUswRf0ZrqAU GG6GDp40cQfR3ODvkBT0r+Q09kw 2012-05-12 16:54:56 91.219.238.71 443 80\r\n")
def test_minus_line_no_command(self):
"""
haven't seen 600's use - "in the wild" but don't see why it's not
possible
"""
self.protocol._set_valid_events('NS')
self.protocol.add_event_listener('NS', lambda _: None)
self.protocol.lineReceived("650-NS\r\n")
self.protocol.lineReceived("650 OK\r\n")
class ParseTests(unittest.TestCase):
def setUp(self):
self.controller = TorState(TorControlProtocol())
self.controller.connectionMade = lambda _: None
def test_keywords(self):
x = parse_keywords('events/names=CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER GUARD STREAM_BW CLIENTS_SEEN NEWCONSENSUS BUILDTIMEOUT_SET')
self.assertTrue('events/names' in x)
self.assertEqual(x['events/names'], 'CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER GUARD STREAM_BW CLIENTS_SEEN NEWCONSENSUS BUILDTIMEOUT_SET')
self.assertEqual(len(x.keys()), 1)
def test_keywords_mutli_equals(self):
x = parse_keywords('foo=something subvalue="foo"')
self.assertEqual(len(x), 1)
self.assertTrue('foo' in x)
self.assertEqual(x['foo'], 'something subvalue="foo"')
def test_default_keywords(self):
x = parse_keywords('foo')
self.assertEqual(len(x), 1)
self.assertTrue('foo' in x)
self.assertEqual(x['foo'], DEFAULT_VALUE)
def test_multientry_keywords_2(self):
x = parse_keywords('foo=bar\nfoo=zarimba')
self.assertEqual(len(x), 1)
self.assertTrue(isinstance(x['foo'], types.ListType))
self.assertEqual(len(x['foo']), 2)
self.assertEqual(x['foo'][0], 'bar')
self.assertEqual(x['foo'][1], 'zarimba')
def test_multientry_keywords_3(self):
x = parse_keywords('foo=bar\nfoo=baz\nfoo=zarimba')
self.assertEqual(len(x), 1)
self.assertTrue(isinstance(x['foo'], types.ListType))
self.assertEqual(len(x['foo']), 3)
self.assertEqual(x['foo'][0], 'bar')
self.assertEqual(x['foo'][1], 'baz')
self.assertEqual(x['foo'][2], 'zarimba')
def test_multientry_keywords_4(self):
x = parse_keywords('foo=bar\nfoo=baz\nfoo=zarimba\nfoo=foo')
self.assertEqual(len(x), 1)
self.assertTrue(isinstance(x['foo'], types.ListType))
self.assertEqual(len(x['foo']), 4)
self.assertEqual(x['foo'][0], 'bar')
self.assertEqual(x['foo'][1], 'baz')
self.assertEqual(x['foo'][2], 'zarimba')
self.assertEqual(x['foo'][3], 'foo')
def test_multiline_keywords_with_spaces(self):
x = parse_keywords('''ns/name/foo=
r foo aaaam7E7h1vY5Prk8v9/nSRCydY BBBBOfum4CtAYuOgf/D33Qq5+rk 2013-10-27 06:22:18 1.2.3.4 9001 9030
s Fast Guard HSDir Running Stable V2Dir Valid
w Bandwidth=1234
ns/name/bar=
r bar aaaaHgNYtTVPw5hHTO28J4je5i8 BBBBBUaJaBFSU/HDrTxnSh+D3+fY 2013-10-27 07:48:56 1.2.4.5 9001 9030
s Exit Fast Guard HSDir Named Running Stable V2Dir Valid
w Bandwidth=1234
OK
''')
self.assertEqual(2, len(x))
keys = x.keys()
keys.sort()
self.assertEqual(keys, ['ns/name/bar', 'ns/name/foo'])
def test_multiline_keywords(self):
x = parse_keywords('''Foo=bar\nBar''')
self.assertEqual(x, {'Foo': 'bar\nBar'})
x = parse_keywords('''Foo=bar\nBar''', multiline_values=False)
self.assertEqual(x, {'Foo': 'bar',
'Bar': DEFAULT_VALUE})
def test_unquoted_keywords(self):
x = parse_keywords('''Tor="0.1.2.3.4-rc44"''')
self.assertEqual(x, {'Tor': '0.1.2.3.4-rc44'})
def test_unquoted_keywords_singlequote(self):
x = parse_keywords("Tor='0.1.2.3.4-rc44'")
self.assertEqual(x, {'Tor': '0.1.2.3.4-rc44'})
def test_unquoted_keywords_empty(self):
x = parse_keywords('foo=')
self.assertEqual(x, {'foo': ''})
def test_network_status(self):
self.controller._update_network_status("""ns/all=
r right2privassy3 ADQ6gCT3DiFHKPDFr3rODBUI8HM JehnjB8l4Js47dyjLCEmE8VJqao 2011-12-02 03:36:40 50.63.8.215 9023 0
s Exit Fast Named Running Stable Valid
w Bandwidth=53
p accept 80,1194,1220,1293,1500,1533,1677,1723,1863,2082-2083,2086-2087,2095-2096,2102-2104,3128,3389,3690,4321,4643,5050,5190,5222-5223,5228,5900,6660-6669,6679,6697,8000,8008,8074,8080,8087-8088,8443,8888,9418,9999-10000,19294,19638
r Unnamed AHe2V2pmj4Yfn0H9+Np3lci7htU T/g7ZLzG/ooqCn+gdLd9Jjh+AEI 2011-12-02 15:52:09 84.101.216.232 443 9030
s Exit Fast Running V2Dir Valid
w Bandwidth=33
p reject 25,119,135-139,445,563,1214,4661-4666,6346-6429,6699,6881-6999""")
# the routers list is always keyed with both name and hash
self.assertEqual(len(self.controller.routers_by_name), 2)
self.assertEqual(len(self.controller.routers_by_hash), 2)
self.assertTrue('right2privassy3' in self.controller.routers)
self.assertTrue('Unnamed' in self.controller.routers)
self.controller.routers.clear()
self.controller.routers_by_name.clear()
self.controller.routers_by_hash.clear()
def test_circuit_status(self):
self.controller._update_network_status("""ns/all=
r wildnl f+Ty/+B6lgYr0Ntbf67O/L2M8ZI c1iK/kPPXKGZZvwXRWbvL9eCfSc 2011-12-02 19:07:05 209.159.142.164 9001 0
s Exit Fast Named Running Stable Valid
w Bandwidth=1900
p reject 25,119,135-139,445,563,1214,4661-4666,6346-6429,6699,6881-6999
r l0l wYXUpLBpzVWfzVSMgGO0dThdd38 KIJC+W1SHeaFOj/BVsEAgxbtQNM 2011-12-02 13:43:39 94.23.168.39 443 80
s Fast Named Running Stable V2Dir Valid
w Bandwidth=22800
p reject 1-65535
r Tecumseh /xAD0tFLS50Dkz+O37xGyVLoKlk yJHbad7MFl1VW2/23RxrPKBTOIE 2011-12-02 09:44:10 76.73.48.211 22 9030
s Fast Guard HSDir Named Running Stable V2Dir Valid
w Bandwidth=18700
p reject 1-65535""")
self.controller._circuit_status("""circuit-status=
4472 BUILT $FF1003D2D14B4B9D03933F8EDFBC46C952E82A59=Tecumseh,$C185D4A4B069CD559FCD548C8063B475385D777F=l0l,$7FE4F2FFE07A96062BD0DB5B7FAECEFCBD8CF192=wildnl PURPOSE=GENERAL""")
self.assertEqual(len(self.controller.circuits), 1)
self.assertTrue(4472 in self.controller.circuits)
self.controller.routers.clear()
self.controller.routers_by_name.clear()
self.controller.routers_by_hash.clear()
self.controller.circuits.clear()
| mit | 6,601,869,624,420,765,000 | 35.493048 | 245 | 0.634741 | false |
mlperf/training_results_v0.7 | Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/tvm/tutorials/language/reduction.py | 2 | 7668 | # 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.
"""
Reduction
=========
**Author**: `Tianqi Chen <https://tqchen.github.io>`_
This is an introduction material on how to do reduction in TVM.
Associative reduction operators like sum/max/min are typical
construction blocks of linear algebra operations.
In this tutorial, we will demonstrate how to do reduction in TVM.
"""
from __future__ import absolute_import, print_function
import tvm
import numpy as np
######################################################################
# Describe Sum of Rows
# --------------------
# Assume we want to compute sum of rows as our example.
# In numpy semantics this can be written as :code:`B = numpy.sum(A, axis=1)`
#
# The following lines describe the row sum operation.
# To create a reduction formula, we declare a reduction axis using
# :any:`tvm.reduce_axis`. :any:`tvm.reduce_axis` takes in the range of reductions.
# :any:`tvm.sum` takes in the expression to be reduced as well as the reduction
# axis and compute the sum of value over all k in the declared range.
#
# The equivalent C code is as follows:
#
# .. code-block:: c
#
# for (int i = 0; i < n; ++i) {
# B[i] = 0;
# for (int k = 0; k < m; ++k) {
# B[i] = B[i] + A[i][k];
# }
# }
#
n = tvm.var("n")
m = tvm.var("m")
A = tvm.placeholder((n, m), name='A')
k = tvm.reduce_axis((0, m), "k")
B = tvm.compute((n,), lambda i: tvm.sum(A[i, k], axis=k), name="B")
######################################################################
# Schedule the Reduction
# ----------------------
# There are several ways to schedule a reduction.
# Before doing anything, let us print out the IR code of default schedule.
#
s = tvm.create_schedule(B.op)
print(tvm.lower(s, [A, B], simple_mode=True))
######################################################################
# You can find that the IR code is quite like the C code.
# The reduction axis is similar to a normal axis, it can be splitted.
#
# In the following code we split both the row axis of B as well
# axis by different factors. The result is a nested reduction.
#
ko, ki = s[B].split(B.op.reduce_axis[0], factor=16)
xo, xi = s[B].split(B.op.axis[0], factor=32)
print(tvm.lower(s, [A, B], simple_mode=True))
######################################################################
# If we are building a GPU kernel, we can bind the rows of B to GPU threads.
s[B].bind(xo, tvm.thread_axis("blockIdx.x"))
s[B].bind(xi, tvm.thread_axis("threadIdx.x"))
print(tvm.lower(s, [A, B], simple_mode=True))
######################################################################
# Reduction Factoring and Parallelization
# ---------------------------------------
# One problem of building a reduction is that we cannot simply
# parallelize over the reduction axis. We need to divide the computation
# of the reduction, store the local reduction result in a temporal array
# before doing a reduction over the temp array.
#
# The rfactor primitive does such rewrite of the computation.
# In the following schedule, the result of B is written to a temporary
# result B.rf. The factored dimension becomes the first dimension of B.rf.
#
s = tvm.create_schedule(B.op)
ko, ki = s[B].split(B.op.reduce_axis[0], factor=16)
BF = s.rfactor(B, ki)
print(tvm.lower(s, [A, B], simple_mode=True))
######################################################################
# The scheduled operator of B also get rewritten to be sum over
# the first axis of reduced result of B.f
#
print(s[B].op.body)
######################################################################
# Cross Thread Reduction
# ----------------------
# We can now parallelize over the factored axis.
# Here the reduction axis of B is marked to be a thread.
# TVM allows reduction axis to be marked as thread if it is the only
# axis in reduction and cross thread reduction is possible in the device.
#
# This is indeed the case after the factoring.
# We can directly compute BF at the reduction axis as well.
# The final generated kernel will divide the rows by blockIdx.x and threadIdx.y
# columns by threadIdx.x and finally do a cross thread reduction over threadIdx.x
#
xo, xi = s[B].split(s[B].op.axis[0], factor=32)
s[B].bind(xo, tvm.thread_axis("blockIdx.x"))
s[B].bind(xi, tvm.thread_axis("threadIdx.y"))
tx = tvm.thread_axis("threadIdx.x")
s[B].bind(s[B].op.reduce_axis[0], tx)
s[BF].compute_at(s[B], s[B].op.reduce_axis[0])
s[B].set_store_predicate(tx.var.equal(0))
fcuda = tvm.build(s, [A, B], "cuda")
print(fcuda.imported_modules[0].get_source())
######################################################################
# Verify the correctness of result kernel by comparing it to numpy.
#
nn = 128
ctx = tvm.gpu(0)
a = tvm.nd.array(np.random.uniform(size=(nn, nn)).astype(A.dtype), ctx)
b = tvm.nd.array(np.zeros(nn, dtype=B.dtype), ctx)
fcuda(a, b)
tvm.testing.assert_allclose(
b.asnumpy(), np.sum(a.asnumpy(), axis=1), rtol=1e-4)
######################################################################
# Describe Convolution via 2D Reduction
# -------------------------------------
# In TVM, we can describe convolution via 2D reduction in a simple way.
# Here is an example for 2D convolution with filter size = [3, 3] and strides = [1, 1].
#
n = tvm.var('n')
Input = tvm.placeholder((n, n), name='Input')
Filter = tvm.placeholder((3, 3), name='Filter')
di = tvm.reduce_axis((0, 3), name='di')
dj = tvm.reduce_axis((0, 3), name='dj')
Output = tvm.compute(
(n - 2, n - 2),
lambda i, j: tvm.sum(Input[i + di, j + dj] * Filter[di, dj], axis=[di, dj]),
name='Output')
s = tvm.create_schedule(Output.op)
print(tvm.lower(s, [Input, Filter, Output], simple_mode=True))
######################################################################
# .. _general-reduction:
#
# Define General Commutative Reduction Operation
# ----------------------------------------------
# Besides the built-in reduction operations like :any:`tvm.sum`,
# :any:`tvm.min` and :any:`tvm.max`, you can also define your
# commutative reduction operation by :any:`tvm.comm_reducer`.
#
n = tvm.var('n')
m = tvm.var('m')
product = tvm.comm_reducer(lambda x, y: x*y,
lambda t: tvm.const(1, dtype=t), name="product")
A = tvm.placeholder((n, m), name='A')
k = tvm.reduce_axis((0, m), name='k')
B = tvm.compute((n,), lambda i: product(A[i, k], axis=k), name='B')
######################################################################
# .. note::
#
# Sometimes we would like to perform reduction that involves multiple
# values like :code:`argmax`, which can be done by tuple inputs.
# See :ref:`reduction-with-tuple-inputs` for more detail.
######################################################################
# Summary
# -------
# This tutorial provides a walk through of reduction schedule.
#
# - Describe reduction with reduce_axis.
# - Use rfactor to factor out axis if we need parallelism.
# - Define new reduction operation by :any:`tvm.comm_reducer`
| apache-2.0 | 2,992,811,413,625,208,000 | 38.323077 | 87 | 0.604851 | false |
Subsets and Splits