repo_name
stringlengths
5
100
path
stringlengths
4
375
copies
stringclasses
991 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
PaddlePaddle/Paddle
python/paddle/fluid/tests/unittests/test_dist_tree_index.py
2
8950
# Copyright (c) 2020 PaddlePaddle 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. import unittest from paddle.dataset.common import download, DATA_HOME from paddle.distributed.fleet.dataset import TreeIndex class TestTreeIndex(unittest.TestCase): def test_tree_index(self): path = download( "https://paddlerec.bj.bcebos.com/tree-based/data/demo_tree.pb", "tree_index_unittest", "cadec20089f5a8a44d320e117d9f9f1a") tree = TreeIndex("demo", path) height = tree.height() branch = tree.branch() self.assertTrue(height == 14) self.assertTrue(branch == 2) self.assertEqual(tree.total_node_nums(), 15581) self.assertEqual(tree.emb_size(), 5171136) # get_layer_codes layer_node_ids = [] layer_node_codes = [] for i in range(tree.height()): layer_node_codes.append(tree.get_layer_codes(i)) layer_node_ids.append( [node.id() for node in tree.get_nodes(layer_node_codes[-1])]) all_leaf_ids = [node.id() for node in tree.get_all_leafs()] self.assertEqual(sum(all_leaf_ids), sum(layer_node_ids[-1])) # get_travel travel_codes = tree.get_travel_codes(all_leaf_ids[0]) travel_ids = [node.id() for node in tree.get_nodes(travel_codes)] for i in range(height): self.assertIn(travel_ids[i], layer_node_ids[height - 1 - i]) self.assertIn(travel_codes[i], layer_node_codes[height - 1 - i]) # get_ancestor ancestor_codes = tree.get_ancestor_codes([all_leaf_ids[0]], height - 2) ancestor_ids = [node.id() for node in tree.get_nodes(ancestor_codes)] self.assertEqual(ancestor_ids[0], travel_ids[1]) self.assertEqual(ancestor_codes[0], travel_codes[1]) # get_pi_relation pi_relation = tree.get_pi_relation([all_leaf_ids[0]], height - 2) self.assertEqual(pi_relation[all_leaf_ids[0]], ancestor_codes[0]) # get_travel_path travel_path_codes = tree.get_travel_path(travel_codes[0], travel_codes[-1]) travel_path_ids = [ node.id() for node in tree.get_nodes(travel_path_codes) ] self.assertEquals(travel_path_ids + [travel_ids[-1]], travel_ids) self.assertEquals(travel_path_codes + [travel_codes[-1]], travel_codes) # get_children children_codes = tree.get_children_codes(travel_codes[1], height - 1) children_ids = [node.id() for node in tree.get_nodes(children_codes)] self.assertIn(all_leaf_ids[0], children_ids) class TestIndexSampler(unittest.TestCase): def test_layerwise_sampler(self): path = download( "https://paddlerec.bj.bcebos.com/tree-based/data/demo_tree.pb", "tree_index_unittest", "cadec20089f5a8a44d320e117d9f9f1a") tree = TreeIndex("demo", path) layer_nodes = [] for i in range(tree.height()): layer_codes = tree.get_layer_codes(i) layer_nodes.append( [node.id() for node in tree.get_nodes(layer_codes)]) sample_num = range(1, 10000) start_sample_layer = 1 seed = 0 sample_layers = tree.height() - start_sample_layer sample_num = sample_num[:sample_layers] layer_sample_counts = list(sample_num) + [1] * (sample_layers - len(sample_num)) total_sample_num = sum(layer_sample_counts) + len(layer_sample_counts) tree.init_layerwise_sampler(sample_num, start_sample_layer, seed) ids = [315757, 838060, 1251533, 403522, 2473624, 3321007] parent_path = {} for i in range(len(ids)): tmp = tree.get_travel_codes(ids[i], start_sample_layer) parent_path[ids[i]] = [node.id() for node in tree.get_nodes(tmp)] # check sample res with_hierarchy = False sample_res = tree.layerwise_sample( [[315757, 838060], [1251533, 403522]], [2473624, 3321007], False) idx = 0 layer = tree.height() - 1 for i in range(len(layer_sample_counts)): for j in range(layer_sample_counts[0 - (i + 1)] + 1): self.assertTrue(sample_res[idx + j][0] == 315757) self.assertTrue(sample_res[idx + j][1] == 838060) self.assertTrue(sample_res[idx + j][2] in layer_nodes[layer]) if j == 0: self.assertTrue(sample_res[idx + j][3] == 1) self.assertTrue( sample_res[idx + j][2] == parent_path[2473624][i]) else: self.assertTrue(sample_res[idx + j][3] == 0) self.assertTrue( sample_res[idx + j][2] != parent_path[2473624][i]) idx += layer_sample_counts[0 - (i + 1)] + 1 layer -= 1 self.assertTrue(idx == total_sample_num) layer = tree.height() - 1 for i in range(len(layer_sample_counts)): for j in range(layer_sample_counts[0 - (i + 1)] + 1): self.assertTrue(sample_res[idx + j][0] == 1251533) self.assertTrue(sample_res[idx + j][1] == 403522) self.assertTrue(sample_res[idx + j][2] in layer_nodes[layer]) if j == 0: self.assertTrue(sample_res[idx + j][3] == 1) self.assertTrue( sample_res[idx + j][2] == parent_path[3321007][i]) else: self.assertTrue(sample_res[idx + j][3] == 0) self.assertTrue( sample_res[idx + j][2] != parent_path[3321007][i]) idx += layer_sample_counts[0 - (i + 1)] + 1 layer -= 1 self.assertTrue(idx == total_sample_num * 2) # check sample res with_hierarchy = True sample_res_with_hierarchy = tree.layerwise_sample( [[315757, 838060], [1251533, 403522]], [2473624, 3321007], True) idx = 0 layer = tree.height() - 1 for i in range(len(layer_sample_counts)): for j in range(layer_sample_counts[0 - (i + 1)] + 1): self.assertTrue(sample_res_with_hierarchy[idx + j][0] == parent_path[315757][i]) self.assertTrue(sample_res_with_hierarchy[idx + j][1] == parent_path[838060][i]) self.assertTrue( sample_res_with_hierarchy[idx + j][2] in layer_nodes[layer]) if j == 0: self.assertTrue(sample_res_with_hierarchy[idx + j][3] == 1) self.assertTrue(sample_res_with_hierarchy[idx + j][2] == parent_path[2473624][i]) else: self.assertTrue(sample_res_with_hierarchy[idx + j][3] == 0) self.assertTrue(sample_res_with_hierarchy[idx + j][2] != parent_path[2473624][i]) idx += layer_sample_counts[0 - (i + 1)] + 1 layer -= 1 self.assertTrue(idx == total_sample_num) layer = tree.height() - 1 for i in range(len(layer_sample_counts)): for j in range(layer_sample_counts[0 - (i + 1)] + 1): self.assertTrue(sample_res_with_hierarchy[idx + j][0] == parent_path[1251533][i]) self.assertTrue(sample_res_with_hierarchy[idx + j][1] == parent_path[403522][i]) self.assertTrue( sample_res_with_hierarchy[idx + j][2] in layer_nodes[layer]) if j == 0: self.assertTrue(sample_res_with_hierarchy[idx + j][3] == 1) self.assertTrue(sample_res_with_hierarchy[idx + j][2] == parent_path[3321007][i]) else: self.assertTrue(sample_res_with_hierarchy[idx + j][3] == 0) self.assertTrue(sample_res_with_hierarchy[idx + j][2] != parent_path[3321007][i]) idx += layer_sample_counts[0 - (i + 1)] + 1 layer -= 1 self.assertTrue(idx == 2 * total_sample_num) if __name__ == '__main__': unittest.main()
apache-2.0
Ashaba/rms
rmslocalenv/lib/python2.7/site-packages/django/contrib/gis/db/models/lookups.py
104
10927
from __future__ import unicode_literals import re from django.core.exceptions import FieldDoesNotExist from django.db.models.constants import LOOKUP_SEP from django.db.models.expressions import Col, Expression from django.db.models.lookups import Lookup from django.utils import six gis_lookups = {} class GISLookup(Lookup): sql_template = None transform_func = None distance = False @classmethod def _check_geo_field(cls, opts, lookup): """ Utility for checking the given lookup with the given model options. The lookup is a string either specifying the geographic field, e.g. 'point, 'the_geom', or a related lookup on a geographic field like 'address__point'. If a GeometryField exists according to the given lookup on the model options, it will be returned. Otherwise returns None. """ from django.contrib.gis.db.models.fields import GeometryField # This takes into account the situation where the lookup is a # lookup to a related geographic field, e.g., 'address__point'. field_list = lookup.split(LOOKUP_SEP) # Reversing so list operates like a queue of related lookups, # and popping the top lookup. field_list.reverse() fld_name = field_list.pop() try: geo_fld = opts.get_field(fld_name) # If the field list is still around, then it means that the # lookup was for a geometry field across a relationship -- # thus we keep on getting the related model options and the # model field associated with the next field in the list # until there's no more left. while len(field_list): opts = geo_fld.remote_field.model._meta geo_fld = opts.get_field(field_list.pop()) except (FieldDoesNotExist, AttributeError): return False # Finally, make sure we got a Geographic field and return. if isinstance(geo_fld, GeometryField): return geo_fld else: return False def get_db_prep_lookup(self, value, connection): # get_db_prep_lookup is called by process_rhs from super class if isinstance(value, (tuple, list)): # First param is assumed to be the geometric object params = [connection.ops.Adapter(value[0])] + list(value)[1:] else: params = [connection.ops.Adapter(value)] return ('%s', params) def process_rhs(self, compiler, connection): rhs, rhs_params = super(GISLookup, self).process_rhs(compiler, connection) if hasattr(self.rhs, '_as_sql'): # If rhs is some QuerySet, don't touch it return rhs, rhs_params geom = self.rhs if isinstance(self.rhs, Col): # Make sure the F Expression destination field exists, and # set an `srid` attribute with the same as that of the # destination. geo_fld = self.rhs.output_field if not hasattr(geo_fld, 'srid'): raise ValueError('No geographic field found in expression.') self.rhs.srid = geo_fld.srid elif isinstance(self.rhs, Expression): raise ValueError('Complex expressions not supported for GeometryField') elif isinstance(self.rhs, (list, tuple)): geom = self.rhs[0] rhs = connection.ops.get_geom_placeholder(self.lhs.output_field, geom, compiler) return rhs, rhs_params def get_rhs_op(self, connection, rhs): # Unlike BuiltinLookup, the GIS get_rhs_op() implementation should return # an object (SpatialOperator) with an as_sql() method to allow for more # complex computations (where the lhs part can be mixed in). return connection.ops.gis_operators[self.lookup_name] def as_sql(self, compiler, connection): lhs_sql, sql_params = self.process_lhs(compiler, connection) rhs_sql, rhs_params = self.process_rhs(compiler, connection) sql_params.extend(rhs_params) template_params = {'lhs': lhs_sql, 'rhs': rhs_sql} rhs_op = self.get_rhs_op(connection, rhs_sql) return rhs_op.as_sql(connection, self, template_params, sql_params) # ------------------ # Geometry operators # ------------------ class OverlapsLeftLookup(GISLookup): """ The overlaps_left operator returns true if A's bounding box overlaps or is to the left of B's bounding box. """ lookup_name = 'overlaps_left' gis_lookups['overlaps_left'] = OverlapsLeftLookup class OverlapsRightLookup(GISLookup): """ The 'overlaps_right' operator returns true if A's bounding box overlaps or is to the right of B's bounding box. """ lookup_name = 'overlaps_right' gis_lookups['overlaps_right'] = OverlapsRightLookup class OverlapsBelowLookup(GISLookup): """ The 'overlaps_below' operator returns true if A's bounding box overlaps or is below B's bounding box. """ lookup_name = 'overlaps_below' gis_lookups['overlaps_below'] = OverlapsBelowLookup class OverlapsAboveLookup(GISLookup): """ The 'overlaps_above' operator returns true if A's bounding box overlaps or is above B's bounding box. """ lookup_name = 'overlaps_above' gis_lookups['overlaps_above'] = OverlapsAboveLookup class LeftLookup(GISLookup): """ The 'left' operator returns true if A's bounding box is strictly to the left of B's bounding box. """ lookup_name = 'left' gis_lookups['left'] = LeftLookup class RightLookup(GISLookup): """ The 'right' operator returns true if A's bounding box is strictly to the right of B's bounding box. """ lookup_name = 'right' gis_lookups['right'] = RightLookup class StrictlyBelowLookup(GISLookup): """ The 'strictly_below' operator returns true if A's bounding box is strictly below B's bounding box. """ lookup_name = 'strictly_below' gis_lookups['strictly_below'] = StrictlyBelowLookup class StrictlyAboveLookup(GISLookup): """ The 'strictly_above' operator returns true if A's bounding box is strictly above B's bounding box. """ lookup_name = 'strictly_above' gis_lookups['strictly_above'] = StrictlyAboveLookup class SameAsLookup(GISLookup): """ The "~=" operator is the "same as" operator. It tests actual geometric equality of two features. So if A and B are the same feature, vertex-by-vertex, the operator returns true. """ lookup_name = 'same_as' gis_lookups['same_as'] = SameAsLookup class ExactLookup(SameAsLookup): # Alias of same_as lookup_name = 'exact' gis_lookups['exact'] = ExactLookup class BBContainsLookup(GISLookup): """ The 'bbcontains' operator returns true if A's bounding box completely contains by B's bounding box. """ lookup_name = 'bbcontains' gis_lookups['bbcontains'] = BBContainsLookup class BBOverlapsLookup(GISLookup): """ The 'bboverlaps' operator returns true if A's bounding box overlaps B's bounding box. """ lookup_name = 'bboverlaps' gis_lookups['bboverlaps'] = BBOverlapsLookup class ContainedLookup(GISLookup): """ The 'contained' operator returns true if A's bounding box is completely contained by B's bounding box. """ lookup_name = 'contained' gis_lookups['contained'] = ContainedLookup # ------------------ # Geometry functions # ------------------ class ContainsLookup(GISLookup): lookup_name = 'contains' gis_lookups['contains'] = ContainsLookup class ContainsProperlyLookup(GISLookup): lookup_name = 'contains_properly' gis_lookups['contains_properly'] = ContainsProperlyLookup class CoveredByLookup(GISLookup): lookup_name = 'coveredby' gis_lookups['coveredby'] = CoveredByLookup class CoversLookup(GISLookup): lookup_name = 'covers' gis_lookups['covers'] = CoversLookup class CrossesLookup(GISLookup): lookup_name = 'crosses' gis_lookups['crosses'] = CrossesLookup class DisjointLookup(GISLookup): lookup_name = 'disjoint' gis_lookups['disjoint'] = DisjointLookup class EqualsLookup(GISLookup): lookup_name = 'equals' gis_lookups['equals'] = EqualsLookup class IntersectsLookup(GISLookup): lookup_name = 'intersects' gis_lookups['intersects'] = IntersectsLookup class OverlapsLookup(GISLookup): lookup_name = 'overlaps' gis_lookups['overlaps'] = OverlapsLookup class RelateLookup(GISLookup): lookup_name = 'relate' sql_template = '%(func)s(%(lhs)s, %(rhs)s, %%s)' pattern_regex = re.compile(r'^[012TF\*]{9}$') def get_db_prep_lookup(self, value, connection): if len(value) != 2: raise ValueError('relate must be passed a two-tuple') # Check the pattern argument backend_op = connection.ops.gis_operators[self.lookup_name] if hasattr(backend_op, 'check_relate_argument'): backend_op.check_relate_argument(value[1]) else: pattern = value[1] if not isinstance(pattern, six.string_types) or not self.pattern_regex.match(pattern): raise ValueError('Invalid intersection matrix pattern "%s".' % pattern) return super(RelateLookup, self).get_db_prep_lookup(value, connection) gis_lookups['relate'] = RelateLookup class TouchesLookup(GISLookup): lookup_name = 'touches' gis_lookups['touches'] = TouchesLookup class WithinLookup(GISLookup): lookup_name = 'within' gis_lookups['within'] = WithinLookup class DistanceLookupBase(GISLookup): distance = True sql_template = '%(func)s(%(lhs)s, %(rhs)s) %(op)s %%s' def get_db_prep_lookup(self, value, connection): if isinstance(value, (tuple, list)): if not 2 <= len(value) <= 3: raise ValueError("2 or 3-element tuple required for '%s' lookup." % self.lookup_name) params = [connection.ops.Adapter(value[0])] # Getting the distance parameter in the units of the field. params += connection.ops.get_distance(self.lhs.output_field, value[1:], self.lookup_name) return ('%s', params) else: return super(DistanceLookupBase, self).get_db_prep_lookup(value, connection) class DWithinLookup(DistanceLookupBase): lookup_name = 'dwithin' sql_template = '%(func)s(%(lhs)s, %(rhs)s, %%s)' gis_lookups['dwithin'] = DWithinLookup class DistanceGTLookup(DistanceLookupBase): lookup_name = 'distance_gt' gis_lookups['distance_gt'] = DistanceGTLookup class DistanceGTELookup(DistanceLookupBase): lookup_name = 'distance_gte' gis_lookups['distance_gte'] = DistanceGTELookup class DistanceLTLookup(DistanceLookupBase): lookup_name = 'distance_lt' gis_lookups['distance_lt'] = DistanceLTLookup class DistanceLTELookup(DistanceLookupBase): lookup_name = 'distance_lte' gis_lookups['distance_lte'] = DistanceLTELookup
mit
orgito/ansible
test/units/modules/network/onyx/test_onyx_ptp.py
63
5200
# # (c) 2016 Red Hat Inc. # # 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 units.compat.mock import patch from ansible.modules.network.onyx import onyx_ptp_global from units.modules.utils import set_module_args from .onyx_module import TestOnyxModule, load_fixture class TestOnyxPtpModule(TestOnyxModule): module = onyx_ptp_global def setUp(self): self._ptp_enabled = True self._ntp_enabled = True super(TestOnyxPtpModule, self).setUp() self.mock_get_ptp_config = patch.object(onyx_ptp_global.OnyxPtpGlobalModule, "_show_ptp_config") self.get_ptp_config = self.mock_get_ptp_config.start() self.mock_get_ntp_config = patch.object(onyx_ptp_global.OnyxPtpGlobalModule, "_show_ntp_config") self.get_ntp_config = self.mock_get_ntp_config.start() self.mock_load_config = patch( 'ansible.module_utils.network.onyx.onyx.load_config') self.load_config = self.mock_load_config.start() def tearDown(self): super(TestOnyxPtpModule, self).tearDown() self.mock_get_ptp_config.stop() self.mock_get_ntp_config.stop() self.mock_load_config.stop() def load_fixtures(self, commands=None, transport='cli'): if self._ptp_enabled: config_file = 'onyx_show_ptp_clock.cfg' self.get_ptp_config.return_value = load_fixture(config_file) else: self.get_ptp_config.return_value = None config_file = 'onyx_show_ntp_configured.cfg' ret_val = load_fixture(config_file) if self._ntp_enabled: ret_val[0]['NTP enabled'] = 'yes' self.get_ntp_config.return_value = ret_val self.load_config.return_value = None def test_ptp_enabled_no_change(self): set_module_args(dict(ptp_state='enabled')) self.execute_module(changed=False) def test_ptp_enabled_with_change(self): self._ptp_enabled = False set_module_args(dict(ptp_state='enabled')) commands = ['protocol ptp'] self.execute_module(changed=True, commands=commands) def test_ptp_disabled_no_change(self): self._ptp_enabled = False set_module_args(dict(ptp_state='disabled')) self.execute_module(changed=False) def test_ptp_disabled_with_change(self): set_module_args(dict(ptp_state='disabled')) commands = ['no protocol ptp'] self.execute_module(changed=True, commands=commands) def test_ntp_enabled_no_change(self): self._ptp_enabled = False set_module_args(dict(ntp_state='enabled', ptp_state='disabled')) self.execute_module(changed=False) def test_ntp_enabled_with_change(self): self._ptp_enabled = False self._ntp_enabled = False set_module_args(dict(ntp_state='enabled', ptp_state='disabled')) commands = ['ntp enable'] self.execute_module(changed=True, commands=commands) def test_ntp_disabled_no_change(self): self._ntp_enabled = False set_module_args(dict(ntp_state='disabled')) self.execute_module(changed=False) def test_ntp_disabled_with_change(self): set_module_args(dict(ntp_state='disabled')) commands = ['no ntp enable'] self.execute_module(changed=True, commands=commands) def test_set_domain_no_change(self): self._ntp_enabled = False set_module_args(dict(ntp_state='disabled', domain=127)) self.execute_module(changed=False) def test_set_domain_with_change(self): set_module_args(dict(domain=100)) commands = ['ptp domain 100'] self.execute_module(changed=True, commands=commands) def test_set_primary_priority_no_change(self): set_module_args(dict(primary_priority=128)) self.execute_module(changed=False) def test_set_primary_priority_with_change(self): set_module_args(dict(primary_priority=250)) commands = ['ptp priority1 250'] self.execute_module(changed=True, commands=commands) def test_set_secondary_priority_no_change(self): set_module_args(dict(secondary_priority=128)) self.execute_module(changed=False) def test_set_secondary_priority_with_change(self): set_module_args(dict(secondary_priority=190)) commands = ['ptp priority2 190'] self.execute_module(changed=True, commands=commands)
gpl-3.0
Johnetordoff/osf.io
api_tests/base/test_root.py
6
5164
# -*- coding: utf-8 -*- import itsdangerous import mock from nose.tools import * # noqa: import unittest from django.utils import timezone import pytest from tests.base import ApiTestCase from osf_tests.factories import ( AuthUserFactory, ApiOAuth2ScopeFactory, ) from api.base.settings.defaults import API_BASE from framework.auth.cas import CasResponse from website import settings from osf.models import ApiOAuth2PersonalToken, Session from osf.utils.permissions import ADMIN @pytest.mark.enable_quickfiles_creation class TestWelcomeToApi(ApiTestCase): def setUp(self): super(TestWelcomeToApi, self).setUp() self.user = AuthUserFactory() self.url = '/{}'.format(API_BASE) def tearDown(self): self.app.reset() super(TestWelcomeToApi, self).tearDown() def test_returns_200_for_logged_out_user(self): res = self.app.get(self.url) assert_equal(res.status_code, 200) assert_equal(res.content_type, 'application/vnd.api+json') assert_equal(res.json['meta']['current_user'], None) def test_returns_current_user_info_when_logged_in(self): res = self.app.get(self.url, auth=self.user.auth) assert_equal(res.status_code, 200) assert_equal(res.content_type, 'application/vnd.api+json') assert_equal( res.json['meta']['current_user']['data']['attributes']['given_name'], self.user.given_name ) def test_current_user_accepted_tos(self): res = self.app.get(self.url, auth=self.user.auth) assert_equal(res.status_code, 200) assert_equal(res.content_type, 'application/vnd.api+json') assert_equal( res.json['meta']['current_user']['data']['attributes']['accepted_terms_of_service'], False ) self.user.accepted_terms_of_service = timezone.now() self.user.save() res = self.app.get(self.url, auth=self.user.auth) assert_equal(res.status_code, 200) assert_equal(res.content_type, 'application/vnd.api+json') assert_equal( res.json['meta']['current_user']['data']['attributes']['accepted_terms_of_service'], True ) def test_returns_302_redirect_for_base_url(self): res = self.app.get('/') assert_equal(res.status_code, 302) assert_equal(res.location, '/v2/') def test_cookie_has_admin(self): session = Session(data={'auth_user_id': self.user._id}) session.save() cookie = itsdangerous.Signer(settings.SECRET_KEY).sign(session._id).decode() self.app.set_cookie(settings.COOKIE_NAME, str(cookie)) res = self.app.get(self.url) assert_equal(res.status_code, 200) assert_equal(res.json['meta'][ADMIN], True) def test_basic_auth_does_not_have_admin(self): res = self.app.get(self.url, auth=self.user.auth) assert_equal(res.status_code, 200) assert_not_in(ADMIN, res.json['meta'].keys()) @mock.patch('api.base.authentication.drf.OSFCASAuthentication.authenticate') # TODO: Remove when available outside of DEV_MODE @unittest.skipIf( not settings.DEV_MODE, 'DEV_MODE disabled, osf.admin unavailable' ) def test_admin_scoped_token_has_admin(self, mock_auth): token = ApiOAuth2PersonalToken( owner=self.user, name='Admin Token', ) token.save() scope = ApiOAuth2ScopeFactory() scope.name = 'osf.admin' scope.save() token.scopes.add(scope) mock_cas_resp = CasResponse( authenticated=True, user=self.user._id, attributes={ 'accessToken': token.token_id, 'accessTokenScope': [s.name for s in token.scopes.all()] } ) mock_auth.return_value = self.user, mock_cas_resp res = self.app.get( self.url, headers={ 'Authorization': 'Bearer {}'.format(token.token_id) } ) assert_equal(res.status_code, 200) assert_equal(res.json['meta'][ADMIN], True) @mock.patch('api.base.authentication.drf.OSFCASAuthentication.authenticate') def test_non_admin_scoped_token_does_not_have_admin(self, mock_auth): token = ApiOAuth2PersonalToken( owner=self.user, name='Admin Token', ) token.save() scope = ApiOAuth2ScopeFactory() scope.name = 'osf.full_write' scope.save() token.scopes.add(scope) mock_cas_resp = CasResponse( authenticated=True, user=self.user._id, attributes={ 'accessToken': token.token_id, 'accessTokenScope': [s.name for s in token.scopes.all()] } ) mock_auth.return_value = self.user, mock_cas_resp res = self.app.get( self.url, headers={ 'Authorization': 'Bearer {}'.format(token.token_id) } ) assert_equal(res.status_code, 200) assert_not_in(ADMIN, res.json['meta'].keys())
apache-2.0
aabbox/kbengine
kbe/res/scripts/common/Lib/test/test_pulldom.py
118
12467
import io import unittest import sys import xml.sax from xml.sax.xmlreader import AttributesImpl from xml.dom import pulldom from test.support import run_unittest, findfile tstfile = findfile("test.xml", subdir="xmltestdata") # A handy XML snippet, containing attributes, a namespace prefix, and a # self-closing tag: SMALL_SAMPLE = """<?xml version="1.0"?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:xdc="http://www.xml.com/books"> <!-- A comment --> <title>Introduction to XSL</title> <hr/> <p><xdc:author xdc:attrib="prefixed attribute" attrib="other attrib">A. Namespace</xdc:author></p> </html>""" class PullDOMTestCase(unittest.TestCase): def test_parse(self): """Minimal test of DOMEventStream.parse()""" # This just tests that parsing from a stream works. Actual parser # semantics are tested using parseString with a more focused XML # fragment. # Test with a filename: handler = pulldom.parse(tstfile) self.addCleanup(handler.stream.close) list(handler) # Test with a file object: with open(tstfile, "rb") as fin: list(pulldom.parse(fin)) def test_parse_semantics(self): """Test DOMEventStream parsing semantics.""" items = pulldom.parseString(SMALL_SAMPLE) evt, node = next(items) # Just check the node is a Document: self.assertTrue(hasattr(node, "createElement")) self.assertEqual(pulldom.START_DOCUMENT, evt) evt, node = next(items) self.assertEqual(pulldom.START_ELEMENT, evt) self.assertEqual("html", node.tagName) self.assertEqual(2, len(node.attributes)) self.assertEqual(node.attributes.getNamedItem("xmlns:xdc").value, "http://www.xml.com/books") evt, node = next(items) self.assertEqual(pulldom.CHARACTERS, evt) # Line break evt, node = next(items) # XXX - A comment should be reported here! # self.assertEqual(pulldom.COMMENT, evt) # Line break after swallowed comment: self.assertEqual(pulldom.CHARACTERS, evt) evt, node = next(items) self.assertEqual("title", node.tagName) title_node = node evt, node = next(items) self.assertEqual(pulldom.CHARACTERS, evt) self.assertEqual("Introduction to XSL", node.data) evt, node = next(items) self.assertEqual(pulldom.END_ELEMENT, evt) self.assertEqual("title", node.tagName) self.assertTrue(title_node is node) evt, node = next(items) self.assertEqual(pulldom.CHARACTERS, evt) evt, node = next(items) self.assertEqual(pulldom.START_ELEMENT, evt) self.assertEqual("hr", node.tagName) evt, node = next(items) self.assertEqual(pulldom.END_ELEMENT, evt) self.assertEqual("hr", node.tagName) evt, node = next(items) self.assertEqual(pulldom.CHARACTERS, evt) evt, node = next(items) self.assertEqual(pulldom.START_ELEMENT, evt) self.assertEqual("p", node.tagName) evt, node = next(items) self.assertEqual(pulldom.START_ELEMENT, evt) self.assertEqual("xdc:author", node.tagName) evt, node = next(items) self.assertEqual(pulldom.CHARACTERS, evt) evt, node = next(items) self.assertEqual(pulldom.END_ELEMENT, evt) self.assertEqual("xdc:author", node.tagName) evt, node = next(items) self.assertEqual(pulldom.END_ELEMENT, evt) evt, node = next(items) self.assertEqual(pulldom.CHARACTERS, evt) evt, node = next(items) self.assertEqual(pulldom.END_ELEMENT, evt) # XXX No END_DOCUMENT item is ever obtained: #evt, node = next(items) #self.assertEqual(pulldom.END_DOCUMENT, evt) def test_expandItem(self): """Ensure expandItem works as expected.""" items = pulldom.parseString(SMALL_SAMPLE) # Loop through the nodes until we get to a "title" start tag: for evt, item in items: if evt == pulldom.START_ELEMENT and item.tagName == "title": items.expandNode(item) self.assertEqual(1, len(item.childNodes)) break else: self.fail("No \"title\" element detected in SMALL_SAMPLE!") # Loop until we get to the next start-element: for evt, node in items: if evt == pulldom.START_ELEMENT: break self.assertEqual("hr", node.tagName, "expandNode did not leave DOMEventStream in the correct state.") # Attempt to expand a standalone element: items.expandNode(node) self.assertEqual(next(items)[0], pulldom.CHARACTERS) evt, node = next(items) self.assertEqual(node.tagName, "p") items.expandNode(node) next(items) # Skip character data evt, node = next(items) self.assertEqual(node.tagName, "html") with self.assertRaises(StopIteration): next(items) items.clear() self.assertIsNone(items.parser) self.assertIsNone(items.stream) @unittest.expectedFailure def test_comment(self): """PullDOM does not receive "comment" events.""" items = pulldom.parseString(SMALL_SAMPLE) for evt, _ in items: if evt == pulldom.COMMENT: break else: self.fail("No comment was encountered") @unittest.expectedFailure def test_end_document(self): """PullDOM does not receive "end-document" events.""" items = pulldom.parseString(SMALL_SAMPLE) # Read all of the nodes up to and including </html>: for evt, node in items: if evt == pulldom.END_ELEMENT and node.tagName == "html": break try: # Assert that the next node is END_DOCUMENT: evt, node = next(items) self.assertEqual(pulldom.END_DOCUMENT, evt) except StopIteration: self.fail( "Ran out of events, but should have received END_DOCUMENT") class ThoroughTestCase(unittest.TestCase): """Test the hard-to-reach parts of pulldom.""" def test_thorough_parse(self): """Test some of the hard-to-reach parts of PullDOM.""" self._test_thorough(pulldom.parse(None, parser=SAXExerciser())) @unittest.expectedFailure def test_sax2dom_fail(self): """SAX2DOM can"t handle a PI before the root element.""" pd = SAX2DOMTestHelper(None, SAXExerciser(), 12) self._test_thorough(pd) def test_thorough_sax2dom(self): """Test some of the hard-to-reach parts of SAX2DOM.""" pd = SAX2DOMTestHelper(None, SAX2DOMExerciser(), 12) self._test_thorough(pd, False) def _test_thorough(self, pd, before_root=True): """Test some of the hard-to-reach parts of the parser, using a mock parser.""" evt, node = next(pd) self.assertEqual(pulldom.START_DOCUMENT, evt) # Just check the node is a Document: self.assertTrue(hasattr(node, "createElement")) if before_root: evt, node = next(pd) self.assertEqual(pulldom.COMMENT, evt) self.assertEqual("a comment", node.data) evt, node = next(pd) self.assertEqual(pulldom.PROCESSING_INSTRUCTION, evt) self.assertEqual("target", node.target) self.assertEqual("data", node.data) evt, node = next(pd) self.assertEqual(pulldom.START_ELEMENT, evt) self.assertEqual("html", node.tagName) evt, node = next(pd) self.assertEqual(pulldom.COMMENT, evt) self.assertEqual("a comment", node.data) evt, node = next(pd) self.assertEqual(pulldom.PROCESSING_INSTRUCTION, evt) self.assertEqual("target", node.target) self.assertEqual("data", node.data) evt, node = next(pd) self.assertEqual(pulldom.START_ELEMENT, evt) self.assertEqual("p", node.tagName) evt, node = next(pd) self.assertEqual(pulldom.CHARACTERS, evt) self.assertEqual("text", node.data) evt, node = next(pd) self.assertEqual(pulldom.END_ELEMENT, evt) self.assertEqual("p", node.tagName) evt, node = next(pd) self.assertEqual(pulldom.END_ELEMENT, evt) self.assertEqual("html", node.tagName) evt, node = next(pd) self.assertEqual(pulldom.END_DOCUMENT, evt) class SAXExerciser(object): """A fake sax parser that calls some of the harder-to-reach sax methods to ensure it emits the correct events""" def setContentHandler(self, handler): self._handler = handler def parse(self, _): h = self._handler h.startDocument() # The next two items ensure that items preceding the first # start_element are properly stored and emitted: h.comment("a comment") h.processingInstruction("target", "data") h.startElement("html", AttributesImpl({})) h.comment("a comment") h.processingInstruction("target", "data") h.startElement("p", AttributesImpl({"class": "paraclass"})) h.characters("text") h.endElement("p") h.endElement("html") h.endDocument() def stub(self, *args, **kwargs): """Stub method. Does nothing.""" pass setProperty = stub setFeature = stub class SAX2DOMExerciser(SAXExerciser): """The same as SAXExerciser, but without the processing instruction and comment before the root element, because S2D can"t handle it""" def parse(self, _): h = self._handler h.startDocument() h.startElement("html", AttributesImpl({})) h.comment("a comment") h.processingInstruction("target", "data") h.startElement("p", AttributesImpl({"class": "paraclass"})) h.characters("text") h.endElement("p") h.endElement("html") h.endDocument() class SAX2DOMTestHelper(pulldom.DOMEventStream): """Allows us to drive SAX2DOM from a DOMEventStream.""" def reset(self): self.pulldom = pulldom.SAX2DOM() # This content handler relies on namespace support self.parser.setFeature(xml.sax.handler.feature_namespaces, 1) self.parser.setContentHandler(self.pulldom) class SAX2DOMTestCase(unittest.TestCase): def confirm(self, test, testname="Test"): self.assertTrue(test, testname) def test_basic(self): """Ensure SAX2DOM can parse from a stream.""" with io.StringIO(SMALL_SAMPLE) as fin: sd = SAX2DOMTestHelper(fin, xml.sax.make_parser(), len(SMALL_SAMPLE)) for evt, node in sd: if evt == pulldom.START_ELEMENT and node.tagName == "html": break # Because the buffer is the same length as the XML, all the # nodes should have been parsed and added: self.assertGreater(len(node.childNodes), 0) def testSAX2DOM(self): """Ensure SAX2DOM expands nodes as expected.""" sax2dom = pulldom.SAX2DOM() sax2dom.startDocument() sax2dom.startElement("doc", {}) sax2dom.characters("text") sax2dom.startElement("subelm", {}) sax2dom.characters("text") sax2dom.endElement("subelm") sax2dom.characters("text") sax2dom.endElement("doc") sax2dom.endDocument() doc = sax2dom.document root = doc.documentElement (text1, elm1, text2) = root.childNodes text3 = elm1.childNodes[0] self.assertIsNone(text1.previousSibling) self.assertIs(text1.nextSibling, elm1) self.assertIs(elm1.previousSibling, text1) self.assertIs(elm1.nextSibling, text2) self.assertIs(text2.previousSibling, elm1) self.assertIsNone(text2.nextSibling) self.assertIsNone(text3.previousSibling) self.assertIsNone(text3.nextSibling) self.assertIs(root.parentNode, doc) self.assertIs(text1.parentNode, root) self.assertIs(elm1.parentNode, root) self.assertIs(text2.parentNode, root) self.assertIs(text3.parentNode, elm1) doc.unlink() def test_main(): run_unittest(PullDOMTestCase, ThoroughTestCase, SAX2DOMTestCase) if __name__ == "__main__": test_main()
lgpl-3.0
thedrow/django
django/db/backends/sqlite3/creation.py
193
2859
import os import sys from django.core.exceptions import ImproperlyConfigured from django.db.backends.base.creation import BaseDatabaseCreation from django.utils.six.moves import input class DatabaseCreation(BaseDatabaseCreation): def _get_test_db_name(self): test_database_name = self.connection.settings_dict['TEST']['NAME'] if test_database_name and test_database_name != ':memory:': if 'mode=memory' in test_database_name: raise ImproperlyConfigured( "Using `mode=memory` parameter in the database name is not allowed, " "use `:memory:` instead." ) return test_database_name if self.connection.features.can_share_in_memory_db: return 'file:memorydb_%s?mode=memory&cache=shared' % self.connection.alias return ':memory:' def _create_test_db(self, verbosity, autoclobber, keepdb=False): test_database_name = self._get_test_db_name() if keepdb: return test_database_name if not self.connection.is_in_memory_db(test_database_name): # Erase the old test database if verbosity >= 1: print("Destroying old test database '%s'..." % self.connection.alias) if os.access(test_database_name, os.F_OK): if not autoclobber: confirm = input( "Type 'yes' if you would like to try deleting the test " "database '%s', or 'no' to cancel: " % test_database_name ) if autoclobber or confirm == 'yes': try: os.remove(test_database_name) except Exception as e: sys.stderr.write("Got an error deleting the old test database: %s\n" % e) sys.exit(2) else: print("Tests cancelled.") sys.exit(1) return test_database_name def _destroy_test_db(self, test_database_name, verbosity): if test_database_name and not self.connection.is_in_memory_db(test_database_name): # Remove the SQLite database file os.remove(test_database_name) def test_db_signature(self): """ Returns a tuple that uniquely identifies a test database. This takes into account the special cases of ":memory:" and "" for SQLite since the databases will be distinct despite having the same TEST NAME. See http://www.sqlite.org/inmemorydb.html """ test_database_name = self._get_test_db_name() sig = [self.connection.settings_dict['NAME']] if self.connection.is_in_memory_db(test_database_name): sig.append(self.connection.alias) return tuple(sig)
bsd-3-clause
PuZZleDucK/pixelated-platform
test/features/page_objects/pixelated_page.py
2
2282
# # Copyright (c) 2015 ThoughtWorks, Inc. # # Pixelated is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pixelated is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Pixelated. If not, see <http://www.gnu.org/licenses/>. from compose_box import ComposeBox from maillist_actions import MailListActions from mail_list import MailList from tag_list import TagList import random import string class PixelatedPage(object): def __init__(self, context, timeout=10): self.maillist_actions = MailListActions(context) self.compose_box = ComposeBox(context) self.mail_list = MailList(context) self.tag_list = TagList(context) def compose_and_send_email(self, mail_fields): self.maillist_actions.open_compose_box() self.compose_box.enter_subject(mail_fields['subject']).enter_body(mail_fields['body']).enter_recipients(mail_fields['recipients']) self.compose_box.send_mail() self.compose_box.wait_compose_box_to_disappear() return self def delete_mail(self, sender, subject, timeout=None): self.mail_list.select_mail(sender, subject, timeout) self.maillist_actions.delete_selected_mails() assert(self.mail_list.is_mail_not_on_the_list(sender, subject)) return self def is_mail_on_list(self, sender, subject, timeout=None): assert(self.mail_list.is_mail_on_list(sender, subject, timeout)) def go_to_trash(self): self.tag_list.go_to_trash() def random_subject(self): if 'random_subject_string' not in globals(): global random_subject_string random_string = ''.join(random.choice(string.lowercase) for i in range(8)) random_subject_string = 'Automated test, TBD (To Be Deleted): '+ random_string return random_subject_string
agpl-3.0
Yarrick13/hwasp
tests/sat/Models/c745.180.SAT.dimacs.test.py
5
10374
input = """ c num blocks = 1 c num vars = 180 c minblockids[0] = 1 c maxblockids[0] = 180 p cnf 180 745 -91 56 -175 0 118 74 115 0 -36 -83 167 0 16 44 142 0 -88 33 20 0 177 132 -8 0 115 121 2 0 -13 -47 28 0 48 -174 163 0 -67 -54 123 0 -130 -132 -71 0 -171 -158 2 0 -35 23 83 0 129 109 -137 0 -8 -139 75 0 -52 -42 -79 0 56 -53 -104 0 -74 -80 95 0 18 -49 81 0 -175 -53 -131 0 49 99 156 0 131 -24 -35 0 19 151 -2 0 -7 -10 -101 0 -1 -27 121 0 87 -65 -137 0 81 -45 -58 0 158 -159 -154 0 -26 -105 162 0 60 -147 -27 0 -98 -74 -44 0 50 10 107 0 11 -69 152 0 109 -151 118 0 -113 -31 -7 0 84 -116 81 0 69 86 43 0 -43 -36 19 0 49 -151 86 0 116 -3 -106 0 131 -35 -3 0 78 -20 37 0 -69 45 133 0 -174 31 51 0 -45 160 153 0 142 -140 -5 0 37 -174 119 0 159 -27 149 0 -163 -54 95 0 -78 -117 -43 0 -74 35 -12 0 -60 -110 10 0 178 -163 1 0 -165 -133 -97 0 -51 -52 -91 0 -174 -171 105 0 -163 43 -112 0 -15 146 -163 0 -34 127 170 0 88 117 -43 0 89 -52 47 0 95 28 -61 0 121 -45 100 0 -29 170 48 0 -175 -85 154 0 -96 48 -51 0 51 -87 72 0 -118 147 75 0 -143 -77 -171 0 142 -62 -22 0 -71 47 -156 0 -120 -119 -56 0 -1 100 -175 0 -141 -120 -55 0 -59 -172 28 0 -153 100 -62 0 -151 -103 136 0 -16 -170 -8 0 97 102 133 0 -4 -109 -15 0 -112 95 109 0 -112 -31 -74 0 -49 -26 -88 0 -126 -60 39 0 76 99 136 0 22 -93 100 0 93 -111 153 0 5 -179 22 0 -72 53 143 0 109 -174 39 0 -7 -41 -28 0 36 -34 -78 0 -167 38 -16 0 -18 -75 153 0 -14 88 -47 0 113 -153 159 0 -133 -155 -148 0 -18 -180 -117 0 -10 -42 177 0 158 131 61 0 101 99 -163 0 -104 162 175 0 -170 -92 18 0 -56 72 5 0 120 -82 -73 0 2 72 142 0 112 -76 -75 0 82 144 153 0 160 -42 -54 0 -106 178 -32 0 156 -121 -132 0 -136 -89 28 0 34 65 61 0 -81 104 -155 0 -117 156 159 0 100 70 -34 0 -35 61 40 0 22 -114 34 0 -30 92 156 0 -168 -176 -85 0 -114 -162 -82 0 -118 -140 -64 0 1 -127 -104 0 -21 167 174 0 54 -42 -173 0 -179 -165 161 0 -119 80 136 0 -161 -93 -49 0 80 117 115 0 -15 142 -75 0 -142 58 -39 0 131 16 98 0 168 -6 -177 0 -48 21 163 0 25 -72 -37 0 159 -178 129 0 124 -176 -14 0 167 92 -50 0 11 123 48 0 -95 51 165 0 -139 17 161 0 139 178 158 0 -14 135 100 0 -52 6 133 0 -39 166 -108 0 121 -93 -87 0 -167 116 4 0 -20 -53 -50 0 -169 64 78 0 -48 -140 108 0 -2 -161 89 0 124 -10 -3 0 179 103 -53 0 127 -7 -99 0 -84 164 -34 0 65 172 -104 0 20 123 -146 0 -143 -179 165 0 -61 -37 -157 0 172 44 -10 0 108 -105 47 0 88 24 61 0 -159 3 171 0 -171 -54 30 0 -140 131 -43 0 -29 -179 -69 0 -41 50 17 0 74 -71 61 0 -73 -170 126 0 -116 -173 160 0 161 -164 174 0 -108 175 172 0 -39 28 46 0 -106 117 -152 0 126 -141 73 0 134 103 1 0 -169 150 20 0 -153 -44 -128 0 135 145 -8 0 70 -4 74 0 -85 -82 -104 0 113 133 62 0 41 158 6 0 94 58 119 0 150 -175 125 0 31 142 -39 0 -150 102 75 0 -135 -174 96 0 -57 -143 140 0 16 91 3 0 21 141 -144 0 35 -22 -176 0 115 -12 25 0 52 -94 160 0 -170 91 88 0 -56 162 -53 0 28 115 144 0 -97 -140 66 0 4 50 108 0 177 120 86 0 -105 17 21 0 -51 -135 -57 0 -96 69 -53 0 -45 -18 61 0 62 -65 147 0 -117 -21 -70 0 106 115 122 0 7 12 176 0 65 -36 -179 0 -30 -118 -131 0 -89 114 -55 0 -180 90 158 0 45 -101 173 0 -74 -168 -71 0 38 23 -78 0 -62 180 22 0 -129 124 -154 0 -55 136 -115 0 -5 -65 -78 0 77 -115 123 0 -55 -17 -64 0 74 -51 132 0 -43 -135 87 0 -154 -180 -144 0 -178 -102 -7 0 -81 105 73 0 26 70 -15 0 -162 -131 56 0 170 -37 -178 0 79 91 -15 0 45 100 105 0 52 -43 119 0 116 23 20 0 -76 -167 -34 0 50 -2 5 0 -155 61 156 0 62 21 153 0 142 -105 27 0 -81 -83 -52 0 82 -139 -53 0 -178 -71 -140 0 177 173 -156 0 -143 170 -172 0 -88 -73 86 0 -106 79 -45 0 125 155 175 0 15 3 -156 0 -43 15 156 0 123 -179 -55 0 -58 146 28 0 161 -113 103 0 -131 -76 -70 0 91 -55 49 0 127 90 5 0 87 -51 139 0 -48 -75 -40 0 147 -173 -160 0 37 24 45 0 -16 -20 8 0 167 37 -101 0 -61 -17 -116 0 -176 128 57 0 42 62 130 0 -92 30 84 0 -48 44 -148 0 99 -119 84 0 -79 -131 -121 0 156 -118 58 0 180 33 121 0 -72 143 -101 0 -114 13 42 0 -79 93 38 0 42 65 -78 0 -151 -125 -104 0 -158 -99 163 0 106 -93 161 0 -175 173 -102 0 -137 79 138 0 -109 50 -56 0 -58 10 -130 0 70 -95 -122 0 112 162 98 0 168 129 -138 0 -26 -21 -112 0 -106 -138 54 0 76 46 23 0 -112 -114 -70 0 48 99 179 0 -4 -175 105 0 -15 58 -163 0 -149 132 -75 0 -166 125 31 0 -16 -78 161 0 -111 16 -60 0 -127 27 -54 0 63 99 151 0 157 -7 132 0 -127 144 162 0 -25 -160 -148 0 15 -124 -49 0 97 31 77 0 -14 -80 110 0 167 -36 164 0 -175 27 -94 0 86 66 37 0 -128 60 17 0 -103 19 -109 0 61 -9 -60 0 95 -20 141 0 -63 36 -121 0 95 43 73 0 1 48 122 0 -132 92 118 0 -168 -57 -135 0 -35 90 -27 0 -110 99 62 0 21 155 90 0 -140 -32 -51 0 -47 -16 -159 0 77 -109 -93 0 105 14 -85 0 167 127 -132 0 111 83 -149 0 72 130 137 0 56 12 101 0 -131 -19 25 0 118 -169 -15 0 159 -136 10 0 -126 166 -107 0 129 -169 -124 0 140 178 -2 0 152 -4 34 0 -56 -2 10 0 -53 -132 -109 0 78 -77 49 0 87 -94 -62 0 -105 -30 113 0 61 134 -159 0 148 137 -56 0 -92 -83 -21 0 153 -80 -67 0 17 70 -43 0 51 138 87 0 -124 102 26 0 53 65 139 0 -154 170 175 0 124 166 87 0 -173 65 -148 0 -116 -81 43 0 173 -11 -134 0 -13 -154 -161 0 178 -116 152 0 178 -116 -161 0 19 -81 128 0 -132 12 -95 0 45 23 -48 0 81 133 -139 0 161 -126 -46 0 63 136 -48 0 -110 136 65 0 -18 12 -142 0 63 -47 123 0 31 -60 91 0 -20 140 -104 0 -25 -16 93 0 -3 -12 52 0 75 -107 -87 0 -160 42 -43 0 -30 137 -143 0 29 -2 -33 0 -34 116 -14 0 65 90 74 0 38 -83 -136 0 155 153 43 0 -154 20 -120 0 132 61 -100 0 121 -11 107 0 -113 128 163 0 -124 21 10 0 173 -143 -127 0 -152 -65 -23 0 25 -68 80 0 49 -103 142 0 169 39 119 0 -94 -180 -171 0 78 -26 -130 0 57 -164 171 0 11 27 -61 0 -59 -89 23 0 104 106 79 0 176 119 164 0 173 11 116 0 -93 -155 -121 0 96 180 176 0 80 -174 152 0 -44 136 -166 0 -135 56 84 0 125 159 45 0 -10 -3 -140 0 140 -47 -88 0 -19 -72 128 0 -126 144 50 0 155 -165 172 0 133 -27 -110 0 28 34 -53 0 69 179 143 0 -3 -144 -137 0 -18 -179 -159 0 117 -95 151 0 152 148 -76 0 -128 89 130 0 16 -89 64 0 101 11 -168 0 1 -28 155 0 -123 -49 45 0 -48 -81 -139 0 150 -135 -142 0 -30 -29 -82 0 90 -83 -66 0 85 -29 162 0 -12 116 -84 0 -116 175 -112 0 -94 33 -127 0 76 -61 153 0 172 87 -3 0 -104 -159 -29 0 -23 -6 -180 0 -117 170 -70 0 -19 118 89 0 116 59 -87 0 174 -16 166 0 179 -26 72 0 -149 19 -111 0 12 -18 -132 0 -169 123 129 0 -10 82 -139 0 -115 147 89 0 -118 121 -42 0 -7 107 177 0 169 71 -60 0 -105 142 -101 0 28 163 -44 0 76 -17 -164 0 -3 91 -52 0 -139 153 -176 0 -41 65 127 0 -40 164 -110 0 -31 -103 160 0 -5 -90 -149 0 71 -52 46 0 -142 -107 -177 0 -167 88 78 0 -99 65 -142 0 108 115 73 0 -82 -50 53 0 -179 -78 128 0 -17 -42 -26 0 -28 -115 -2 0 110 -76 36 0 130 -101 -23 0 152 69 17 0 71 168 -95 0 81 -169 -70 0 -40 -52 -126 0 -141 147 -108 0 -136 175 146 0 59 136 -23 0 -140 170 -41 0 23 109 -80 0 66 -141 24 0 -74 85 163 0 -72 62 15 0 -154 -81 -162 0 29 128 53 0 164 -173 100 0 78 -169 128 0 -138 -51 -148 0 63 15 162 0 -120 -27 150 0 45 -135 120 0 -30 -159 28 0 152 138 103 0 46 156 -140 0 -39 -58 -139 0 -5 65 84 0 114 -157 -74 0 -87 171 -157 0 177 53 150 0 -128 137 74 0 39 36 -163 0 -32 5 -20 0 10 -170 125 0 -160 3 -161 0 -96 -36 -30 0 -84 -120 -12 0 -140 -97 -110 0 -149 -77 47 0 147 -152 79 0 63 130 58 0 -133 138 5 0 25 -20 -138 0 -174 -36 -17 0 -149 20 27 0 -16 -15 -5 0 -2 -115 150 0 56 -168 128 0 104 -164 143 0 97 -72 -167 0 19 -146 -42 0 171 158 55 0 57 106 -70 0 167 -153 -27 0 92 -93 168 0 -72 -113 -5 0 152 115 165 0 30 143 119 0 -137 -6 -15 0 8 171 -155 0 -51 174 92 0 -60 -26 71 0 96 83 -90 0 101 109 46 0 -43 51 -131 0 -36 59 -163 0 -98 -119 -43 0 -175 36 73 0 -148 99 162 0 -92 50 -136 0 64 -122 82 0 20 -36 159 0 49 -13 -84 0 -53 122 -156 0 50 63 84 0 135 5 -74 0 -5 -60 -142 0 -129 160 -158 0 -14 101 -49 0 -53 145 62 0 -134 121 -58 0 35 -160 -60 0 -161 -23 -71 0 -116 -128 87 0 -112 -28 139 0 -88 80 129 0 165 154 19 0 159 45 -131 0 125 -118 -10 0 -169 -123 -23 0 177 128 -14 0 95 -172 -121 0 11 -145 133 0 146 -131 165 0 -29 -12 42 0 -157 34 -43 0 21 50 -41 0 -22 41 14 0 -59 -75 28 0 -6 -8 157 0 -124 171 -41 0 -94 -114 -9 0 -177 88 -109 0 -5 -127 -82 0 -163 -179 27 0 -68 -155 21 0 -169 48 149 0 -80 65 -170 0 11 -89 -103 0 -39 51 -83 0 42 -3 -25 0 -37 8 -151 0 -31 157 -35 0 -141 160 -54 0 -65 101 -29 0 52 145 44 0 146 -6 18 0 -12 -171 -105 0 -89 -88 112 0 -56 140 -60 0 -102 -25 -171 0 -16 -18 70 0 -114 146 -166 0 -151 5 74 0 -174 -71 -130 0 154 -57 -125 0 -14 91 136 0 -3 53 -131 0 6 -74 79 0 63 -56 -141 0 -47 117 -27 0 11 109 -42 0 172 2 30 0 150 147 -154 0 -174 177 117 0 -61 160 -144 0 -45 85 -84 0 157 -70 150 0 80 -85 14 0 -175 85 4 0 -47 -92 113 0 -174 -68 -157 0 -65 47 -153 0 167 -28 85 0 122 -56 85 0 -95 -41 -125 0 180 54 156 0 -80 -92 -133 0 -70 -21 -124 0 114 -175 -101 0 127 170 163 0 71 -168 77 0 -93 68 67 0 115 155 167 0 132 -113 42 0 104 -116 51 0 -138 -142 108 0 -36 -178 155 0 -94 73 69 0 72 -137 -78 0 -136 103 4 0 146 -73 66 0 14 34 156 0 71 108 -162 0 91 -124 -77 0 -138 -114 177 0 73 1 26 0 -79 66 69 0 51 62 178 0 113 96 -111 0 172 -24 -77 0 -81 66 -7 0 -105 -111 -153 0 -46 -91 -121 0 99 103 42 0 26 87 -9 0 75 66 -106 0 -150 -133 -180 0 -154 97 64 0 13 143 110 0 29 -168 -128 0 -180 -32 -163 0 180 155 105 0 -19 30 104 0 -94 45 -144 0 -28 172 -40 0 81 -115 82 0 78 -18 146 0 -169 -58 19 0 140 -157 -138 0 177 51 38 0 -168 -117 40 0 156 114 -33 0 48 84 153 0 -44 118 -96 0 -131 13 -165 0 -120 -105 -173 0 94 172 -121 0 -38 -54 56 0 -36 -57 -172 0 10 -80 4 0 123 -136 -159 0 74 143 148 0 21 -103 -13 0 92 -79 -2 0 84 -74 -123 0 -50 78 153 0 24 -72 95 0 140 -121 -116 0 -74 -37 4 0 36 114 149 0 43 156 168 0 33 -82 79 0 154 -21 -19 0 127 169 122 0 -96 -95 -119 0 135 147 -5 0 134 -56 87 0 -114 -178 -58 0 -82 -102 93 0 -39 -176 -7 0 -130 -52 46 0 55 146 65 0 28 -161 -167 0 70 -167 -140 0 50 -31 -154 0 140 -70 165 0 133 -73 -10 0 129 126 -142 0 -42 180 -114 0 -25 -95 160 0 99 -163 126 0 -11 -48 33 0 91 23 -161 0 -126 155 -29 0 60 -35 -44 0 -100 -21 41 0 -129 170 -14 0 1 -42 -131 0 -36 11 -109 0 -89 -142 45 0 -61 125 38 0 173 -160 5 0 137 164 34 0 63 112 -32 0 -46 -132 -20 0 101 169 36 0 -173 92 26 0 -78 161 -34 0 126 -166 25 0 -87 113 24 0 180 -47 -79 0 -149 37 -19 0 22 138 14 0 71 67 117 0 60 -129 72 0 120 -79 -170 0 -58 -45 -59 0 -61 176 6 0 39 -1 112 0 11 24 6 0 -148 -114 171 0 47 103 36 0 -77 -129 25 0 -58 90 76 0 145 -86 56 0 90 -65 125 0 -176 -86 53 0 -94 115 -131 0 -61 4 -5 0 -161 137 -122 0 73 162 34 0 73 -93 122 0 -126 171 55 0 -170 168 -12 0 -8 -33 37 0 36 -135 24 0 -179 -123 -101 0 48 -6 61 0 -71 -128 37 0 176 -175 138 0 84 60 146 0 -123 130 -178 0 42 -18 -48 0 127 -112 64 0 -23 -146 137 0 104 111 154 0 """ output = "SAT"
apache-2.0
iamsarin/geonode
geonode/groups/tests.py
27
16338
import json from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from django.core.urlresolvers import reverse from django.test import TestCase from django.conf import settings from guardian.shortcuts import get_anonymous_user from geonode.groups.models import GroupProfile, GroupInvitation from geonode.documents.models import Document from geonode.layers.models import Layer from geonode.maps.models import Map from geonode.base.populate_test_data import create_models from geonode.security.views import _perms_info_json class SmokeTest(TestCase): """ Basic checks to make sure pages load, etc. """ fixtures = ["group_test_data"] def setUp(self): create_models(type='layer') create_models(type='map') create_models(type='document') self.norman = get_user_model().objects.get(username="norman") self.norman.groups.add(Group.objects.get(name='anonymous')) self.test_user = get_user_model().objects.get(username='test_user') self.test_user.groups.add(Group.objects.get(name='anonymous')) self.bar = GroupProfile.objects.get(slug='bar') self.anonymous_user = get_anonymous_user() def test_group_permissions_extend_to_user(self): """ Ensures that when a user is in a group, the group permissions extend to the user. """ layer = Layer.objects.all()[0] # Set the default permissions layer.set_default_permissions() # Test that the anonymous user can read self.assertTrue(self.anonymous_user.has_perm('view_resourcebase', layer.get_self_resource())) # Test that the default perms give Norman view permissions but not # write permissions self.assertTrue(self.norman.has_perm('view_resourcebase', layer.get_self_resource())) self.assertFalse(self.norman.has_perm('change_resourcebase', layer.get_self_resource())) # Make sure Norman is not in the bar group. self.assertFalse(self.bar.user_is_member(self.norman)) # Add norman to the bar group. self.bar.join(self.norman) # Ensure Norman is in the bar group. self.assertTrue(self.bar.user_is_member(self.norman)) # Give the bar group permissions to change the layer. permissions = {'groups': {'bar': ['view_resourcebase', 'change_resourcebase']}} layer.set_permissions(permissions) self.assertTrue(self.norman.has_perm('view_resourcebase', layer.get_self_resource())) # check that now norman can change the layer self.assertTrue(self.norman.has_perm('change_resourcebase', layer.get_self_resource())) # Test adding a new user to the group after setting permissions on the layer. # Make sure Test User is not in the bar group. self.assertFalse(self.bar.user_is_member(self.test_user)) self.assertFalse(self.test_user.has_perm('change_resourcebase', layer.get_self_resource())) self.bar.join(self.test_user) self.assertTrue(self.test_user.has_perm('change_resourcebase', layer.get_self_resource())) def test_group_resource(self): """ Tests the resources method on a Group object. """ layer = Layer.objects.all()[0] map = Map.objects.all()[0] perm_spec = {'groups': {'bar': ['change_resourcebase']}} # Give the self.bar group write perms on the layer layer.set_permissions(perm_spec) map.set_permissions(perm_spec) # Ensure the layer is returned in the group's resources self.assertTrue(layer.get_self_resource() in self.bar.resources()) self.assertTrue(map.get_self_resource() in self.bar.resources()) # Test the resource filter self.assertTrue(layer.get_self_resource() in self.bar.resources(resource_type='layer')) self.assertTrue(map.get_self_resource() not in self.bar.resources(resource_type='layer')) # Revoke permissions on the layer from the self.bar group layer.set_permissions("{}") # Ensure the layer is no longer returned in the groups resources self.assertFalse(layer.get_self_resource() in self.bar.resources()) def test_perms_info(self): """ Tests the perms_info function (which passes permissions to the response context). """ # Add test to test perms being sent to the front end. layer = Layer.objects.all()[0] layer.set_default_permissions() perms_info = layer.get_all_level_info() # Ensure there is only one group 'anonymous' by default self.assertEqual(len(perms_info['groups'].keys()), 1) # Add the foo group to the layer object groups layer.set_permissions({'groups': {'bar': ['view_resourcebase']}}) perms_info = _perms_info_json(layer) # Ensure foo is in the perms_info output self.assertDictEqual(json.loads(perms_info)['groups'], {'bar': ['view_resourcebase']}) def test_resource_permissions(self): """ Tests that the client can get and set group permissions through the test_resource_permissions view. """ self.assertTrue(self.client.login(username="admin", password="admin")) layer = Layer.objects.all()[0] document = Document.objects.all()[0] map_obj = Map.objects.all()[0] layer.set_default_permissions() document.set_default_permissions() map_obj.set_default_permissions() objects = layer, document, map_obj for obj in objects: response = self.client.get(reverse('resource_permissions', kwargs=dict(resource_id=obj.id))) self.assertEqual(response.status_code, 200) js = json.loads(response.content) permissions = js.get('permissions', dict()) if isinstance(permissions, unicode) or isinstance(permissions, str): permissions = json.loads(permissions) # Ensure the groups value is empty by default expected_permissions = {} if settings.DEFAULT_ANONYMOUS_DOWNLOAD_PERMISSION: expected_permissions.setdefault(u'anonymous', []).append(u'download_resourcebase') if settings.DEFAULT_ANONYMOUS_VIEW_PERMISSION: expected_permissions.setdefault(u'anonymous', []).append(u'view_resourcebase') self.assertDictEqual(permissions.get('groups'), expected_permissions) permissions = { 'groups': { 'bar': ['change_resourcebase'] }, 'users': { 'admin': ['change_resourcebase'] } } # Give the bar group permissions response = self.client.post( reverse( 'resource_permissions', kwargs=dict(resource_id=obj.id)), data=json.dumps(permissions), content_type="application/json") self.assertEqual(response.status_code, 200) response = self.client.get(reverse('resource_permissions', kwargs=dict(resource_id=obj.id))) js = json.loads(response.content) permissions = js.get('permissions', dict()) if isinstance(permissions, unicode) or isinstance(permissions, str): permissions = json.loads(permissions) # Make sure the bar group now has write permissions self.assertDictEqual(permissions['groups'], {'bar': ['change_resourcebase']}) # Remove group permissions permissions = {"users": {"admin": ['change_resourcebase']}} # Update the object's permissions to remove the bar group response = self.client.post( reverse( 'resource_permissions', kwargs=dict(resource_id=obj.id)), data=json.dumps(permissions), content_type="application/json") self.assertEqual(response.status_code, 200) response = self.client.get(reverse('resource_permissions', kwargs=dict(resource_id=obj.id))) js = json.loads(response.content) permissions = js.get('permissions', dict()) if isinstance(permissions, unicode) or isinstance(permissions, str): permissions = json.loads(permissions) # Assert the bar group no longer has permissions self.assertDictEqual(permissions['groups'], {}) def test_create_new_group(self): """ Tests creating a group through the group_create route. """ d = dict(title='TestGroup', description='This is a test group.', access='public', keywords='testing, groups') self.client.login(username="admin", password="admin") response = self.client.post(reverse('group_create'), data=d) # successful POSTS will redirect to the group's detail view. self.assertEqual(response.status_code, 302) self.assertTrue(GroupProfile.objects.get(title='TestGroup')) def test_delete_group_view(self): """ Tests deleting a group through the group_delete route. """ # Ensure the group exists self.assertTrue(GroupProfile.objects.get(id=self.bar.id)) self.client.login(username="admin", password="admin") # Delete the group response = self.client.post(reverse('group_remove', args=[self.bar.slug])) # successful POSTS will redirect to the group list view. self.assertEqual(response.status_code, 302) self.assertFalse(GroupProfile.objects.filter(id=self.bar.id).count() > 0) def test_delete_group_view_no_perms(self): """ Tests deleting a group through the group_delete with a non-manager. """ # Ensure the group exists self.assertTrue(GroupProfile.objects.get(id=self.bar.id)) self.client.login(username="norman", password="norman") # Delete the group response = self.client.post(reverse('group_remove', args=[self.bar.slug])) self.assertEqual(response.status_code, 403) # Ensure the group still exists self.assertTrue(GroupProfile.objects.get(id=self.bar.id)) def test_groupmember_manager(self): """ Tests the get_managers method. """ norman = get_user_model().objects.get(username="norman") admin = get_user_model().objects.get(username='admin') # Make sure norman is not a user self.assertFalse(self.bar.user_is_member(norman)) # Add norman to the self.bar group self.bar.join(norman) # Ensure norman is now a member self.assertTrue(self.bar.user_is_member(norman)) # Ensure norman is not in the managers queryset self.assertTrue(norman not in self.bar.get_managers()) # Ensure admin is in the managers queryset self.assertTrue(admin in self.bar.get_managers()) def test_public_pages_render(self): """ Verify pages that do not require login load without internal error """ response = self.client.get("/groups/") self.assertEqual(200, response.status_code) response = self.client.get("/groups/group/bar/") self.assertEqual(200, response.status_code) response = self.client.get("/groups/group/bar/members/") self.assertEqual(200, response.status_code) # 302 for auth failure since we redirect to login page response = self.client.get("/groups/create/") self.assertEqual(302, response.status_code) response = self.client.get("/groups/group/bar/update/") self.assertEqual(302, response.status_code) # 405 - json endpoint, doesn't support GET response = self.client.get("/groups/group/bar/invite/") self.assertEqual(405, response.status_code) def test_protected_pages_render(self): """ Verify pages that require login load without internal error """ self.assertTrue(self.client.login(username="admin", password="admin")) response = self.client.get("/groups/") self.assertEqual(200, response.status_code) response = self.client.get("/groups/group/bar/") self.assertEqual(200, response.status_code) response = self.client.get("/groups/group/bar/members/") self.assertEqual(200, response.status_code) response = self.client.get("/groups/create/") self.assertEqual(200, response.status_code) response = self.client.get("/groups/group/bar/update/") self.assertEqual(200, response.status_code) # 405 - json endpoint, doesn't support GET response = self.client.get("/groups/group/bar/invite/") self.assertEqual(405, response.status_code) class MembershipTest(TestCase): """ Tests membership logic in the geonode.groups models """ fixtures = ["group_test_data"] def test_group_is_member(self): """ Tests checking group membership """ anon = get_anonymous_user() normal = get_user_model().objects.get(username="norman") group = GroupProfile.objects.get(slug="bar") self.assert_(not group.user_is_member(anon)) self.assert_(not group.user_is_member(normal)) def test_group_add_member(self): """ Tests adding a user to a group """ anon = get_anonymous_user() normal = get_user_model().objects.get(username="norman") group = GroupProfile.objects.get(slug="bar") group.join(normal) self.assert_(group.user_is_member(normal)) self.assertRaises(ValueError, lambda: group.join(anon)) class InvitationTest(TestCase): """ Tests invitation logic in geonode.groups models """ fixtures = ["group_test_data"] def test_invite_user(self): """ Tests inviting a registered user """ normal = get_user_model().objects.get(username="norman") admin = get_user_model().objects.get(username="admin") group = GroupProfile.objects.get(slug="bar") group.invite(normal, admin, role="member", send=False) self.assert_(GroupInvitation.objects.filter(user=normal, from_user=admin, group=group).exists()) invite = GroupInvitation.objects.get(user=normal, from_user=admin, group=group) # Test that the user can access the token url. self.client.login(username="norman", password="norman") response = self.client.get("/groups/group/{group}/invite/{token}/".format(group=group, token=invite.token)) self.assertEqual(200, response.status_code) def test_accept_invitation(self): """ Tests accepting an invitation """ anon = get_anonymous_user() normal = get_user_model().objects.get(username="norman") admin = get_user_model().objects.get(username="admin") group = GroupProfile.objects.get(slug="bar") group.invite(normal, admin, role="member", send=False) invitation = GroupInvitation.objects.get(user=normal, from_user=admin, group=group) self.assertRaises(ValueError, lambda: invitation.accept(anon)) self.assertRaises(ValueError, lambda: invitation.accept(admin)) invitation.accept(normal) self.assert_(group.user_is_member(normal)) self.assert_(invitation.state == "accepted") def test_decline_invitation(self): """ Tests declining an invitation """ anon = get_anonymous_user() normal = get_user_model().objects.get(username="norman") admin = get_user_model().objects.get(username="admin") group = GroupProfile.objects.get(slug="bar") group.invite(normal, admin, role="member", send=False) invitation = GroupInvitation.objects.get(user=normal, from_user=admin, group=group) self.assertRaises(ValueError, lambda: invitation.decline(anon)) self.assertRaises(ValueError, lambda: invitation.decline(admin)) invitation.decline(normal) self.assert_(not group.user_is_member(normal)) self.assert_(invitation.state == "declined")
gpl-3.0
DarkPurple141/Maps
MapGen/voronoi.py
1
28973
#!/usr/bin/env python3 import pygame, os, random, numpy, math, color_palettes, queue, name_gen, triangle from pygame.locals import * from geom import * from PIL import ImageFilter, Image class City: """docstring for City.""" def __init__(self, location, name="default"): self.name = name self.location = location self.owner = random.randrange(10) def __centre_dist_inc(origin,dest,centre): x1,y1 = origin.get_cords() x2,y2 = dest.get_cords() dista = (y1 -centre[1])**2+(x1-centre[0])**2 distb = (y2 -centre[1])**2+(x2-centre[0])**2 if distb > dista: return True else: return False def _make_roads(city_sites): road_list = [] candidates = {} count = 0 #for _ in range(3): for c in city_sites: ## find best candidate least = 1000000 for a in city_sites: if c == a: continue try: if candidates[(c,a)]: continue except KeyError: if c.distance(a) < least: next_item = a least = c.distance(a) origin = c re = True for duplicate in city_sites: if duplicate == c or duplicate == a: continue if (duplicate,c) in candidates: if (duplicate.distance(a) + 10000) < least: least = duplicate.distance(a) next_item = a origin = duplicate candidates[(c,next_item)] = 1 candidates[(next_item,c)] = 1 candidates[(origin,next_item)] = 1 candidates[(next_item,origin)] = 1 road_list.append(_best_road_route(origin,next_item)) count+=1 return road_list def _best_road_route(origin,dest): pt_list = [] q = queue.PriorityQueue() q.put((0,origin)) came_from = {} cost_so_far = {} cost_so_far[origin] = 0 came_from[origin] = None found = False while not q.empty(): curr = q.get()[1] if curr == dest: found = True break for next_item in curr.v_neighbours: river_cost = alt_cost = 0 if next_item.elevation < -0.8 or next_item.elevation > 6: continue elif came_from[curr] and next_item.river: if came_from[curr].river and curr.river: continue else: river_cost = 10 elif next_item.elevation > curr.elevation: alt_cost = 5 dist = next_item.distance(curr) + cost_so_far[curr] + river_cost + alt_cost if (next_item not in cost_so_far) or (dist < cost_so_far[next_item]): cost_so_far[next_item] = dist priority = dist + next_item.distance(dest) q.put((priority,next_item)) came_from[next_item] = curr if found: curr = dest while curr != origin: pt_list.append(curr) curr = came_from[curr] pt_list.append(origin) return pt_list def render_roads(road_list): for i in road_list: ptlist = [j.get_cords() for j in i] if len(ptlist) > 1: pygame.draw.lines(pygame.display.get_surface(), (120,88,20), False, ptlist, 2) def _determine_terrain(count,poly_site,polygons,centre,max_dist): rivers = 2*count centrex,centrey = centre[0],centre[1] for p in polygons: p._add_neighbours(poly_site) # populates vertices with neighbour data if p.terrain == -2: # water terrain p.fresh_or_salt(poly_site) if p.terrain == 0: #lake terrain a = [i for i in p.get_neighbours(poly_site) if i.terrain <= 0] if not a: p.terrain = 2 p.color = (50,150,0) elif len(a) > 2: for i in p.get_neighbours(poly_site): if i.terrain > 0 and not [j for j in i.get_neighbours(poly_site) if j.terrain < 0]: i.terrain = 0 i.color = color_palettes.shallows[2] mountains = [] for p in polygons: if (abs((p.centre.x-centrex)/max_dist) < .6 and abs((p.centre.y-centrey)/max_dist) < .5) or ( (p.centre.x < (centrex - (5/8)*max_dist)) and (p.centre.y < (centrey - (5/8)*max_dist)) ): #0.1 if p.terrain == 2 and (len([i for i in p.get_neighbours(poly_site) if i.terrain <= 0]) == 0 and count > 0): mountains.append(p) p.make_mountain(poly_site) count -= 1 # mountains for m in mountains: s = set() s.add(m) q = queue.Queue() q.put(m) while not q.empty(): curr = q.get() fringe = [i for i in curr.get_neighbours(poly_site) if i.terrain > 1 and i not in s] while fringe: new = fringe.pop() if new.terrain >= 2 and new.terrain <= 11: q.put(new) s.add(new) if new.terrain < 11 and curr.terrain > 2 and (new.terrain < curr.terrain): new.terrain = curr.terrain-1 new.color = random.choice(color_palettes.terrain[10-new.terrain]) # rivers river_sources = set() river_mouth = set() for p in polygons: if (p.terrain > 3 and p.terrain < 9) or p.terrain == 0: river_sources.add(p) for v in p.vertices: v.elevation = sum([i.terrain for i in v.neighbours])/len(v.neighbours) river_sources = list(river_sources) land = [p for p in polygons if p.terrain > 1] regions = [] for i in range(4): while True: found = True candidate = random.choice(land).centre if ((candidate.x-centrex)**2 + (candidate.y-centrey)**2) < 100000: for r in regions: if candidate.distance(r.location) < 70000: found = False break else: found = False if found: regions.append(name_gen.Region(location=candidate)) break if river_sources: while rivers > 0: temp = random.choice(river_sources) if temp in river_mouth: continue else: river_mouth.add(temp) rivers-=1 river_point_list = [] while len(river_mouth): temp = river_mouth.pop() newriver = _make_river(temp,centre) if newriver: river_point_list.append(newriver) else: river_mouth.add(random.choice(river_sources)) #return river_point_list else: return [] city_count = 22 potential_city = [i for river in river_point_list for i in river if i.elevation < 7] coast = [j for p in polygons for j in p.vertices if p.terrain >= 2 if j.elevation < 2] potential_city += coast city_sites = set() while potential_city and city_count > 0: temp = random.choice(potential_city) if temp not in city_sites: approved = True for i in city_sites: if temp.distance(i) < 8000: # NB distance isn't squarerooted for speed approved = False break if approved: least = regions[0].location.distance(temp) region = regions[0] for i in regions: holding = i.location.distance(temp) if holding < least: least = holding region = i temp.city = City(location=temp,name=region.regional_name()) city_count -=1 region.cities.append(temp) city_sites.add(temp) for i in coast: for j in i.neighbours: if j.terrain == -2: i.coast = True return river_point_list,city_sites,regions def render_coast(coast_lines): ptlist = [j.get_cords() for j in coast_lines] pygame.draw.lines(pygame.display.get_surface(), color_palettes.sand[2], False, ptlist, 4) def render_cities(city_sites,font): for i in city_sites: city = i.city x,y = i.get_cords() screen = pygame.display.get_surface() pygame.draw.rect(screen,(0,0,0),(x-8,y-8,16,16)) toWrite = font.render(city.name, True, (30,30,30)) w,h = toWrite.get_size() s = pygame.Surface((w,h ), pygame.SRCALPHA) # per-pixel alpha s.fill((255,255,255,128)) screen.blit(s,(x-28,y+12)) screen.blit(toWrite,(x-28,y+12)) def render_regions(regions,font): for r in regions: x,y = r.location.get_cords() screen = pygame.display.get_surface() screen.blit((font.render(r.name, True, (30,30,30))),(x-16,y+8)) def _make_river(river_source,centre): seen = set() start = random.choice(river_source.vertices) seen.add(start) start.river = True river_list = [] river_list.append(start) q = queue.Queue() q.put(start) exceptions = [] while not q.empty(): curr = q.get() next_item = None for v in curr.v_neighbours: if v in seen: continue seen.add(v) if v and ((v.elevation <= curr.elevation or ((curr.elevation<2) and v.elevation>4)) and __centre_dist_inc(curr,v,centre)) and (v.elevation >= 0): next_item = v if next_item: if len([i.terrain for i in next_item.neighbours if i.terrain <0]) > 1: break else: q.put(next_item) if next_item.river: exceptions.append(next_item) next_item.river = True river_list.append(next_item) if len(river_list) < 11: for i in river_list: if i not in exceptions: i.river = False return return river_list def render_rivers(river_list): for i in river_list: if len([j for j in i[0].neighbours if j.terrain == 0]) > 0: size = 6 else: size = 4 ptlist = [j.get_cords() for j in i] pygame.draw.lines(pygame.display.get_surface(), color_palettes.shallows[2], False, ptlist, size) class Polygon: def __init__(self,vertices,site,neighbours): self.centre = site self.color = (site.x%256,site.y%256,(site.x*site.y)%256) self.neighbours = neighbours self.vertices = sorted(vertices,key=self.vertex_sort) # needs to be sorted self.terrain = None def draw (self): if len(self.vertices) <= 2: print("===============") else: pygame.draw.polygon(pygame.display.get_surface(),self.color,[i.get_cords() for i in self.vertices]) #if self.terrain > 0: # pygame.draw.polygon(pygame.display.get_surface(),color_palettes.simple_colours[11-self.terrain],[i.get_cords() for i in self.vertices]) #else: # pygame.draw.polygon(pygame.display.get_surface(),self.color,[i.get_cords() for i in self.vertices]) def vertex_sort(self,b): x,y = self.centre.get_cords() px, py = b.get_cords() y = py-y x = px-x theta = numpy.arctan2(y, x) return theta def sea_or_land(self,centre,max_dist,island): x, y = self.centre.get_cords() point = (x - centre[0])/max_dist,(y - centre[1])/max_dist land = island.inside(point) if not land: self.terrain = -2 self.color = random.choice(color_palettes.ocean) else: self.terrain = 2 self.color = (50,150,0) def get_neighbours(self,PolygonList): return [PolygonList[i.get_cords()] for i in self.neighbours] def render(self,PolygonList): a = self.get_neighbours(PolygonList) land = [i.terrain for i in a if i.terrain >= 0] salt = [i for i in self.get_neighbours(PolygonList) if i.terrain < 0] if len([i for i in self.vertices if i.river == True])/len(self.vertices) > 0.88: if not salt: self.terrain = 0 self.color = color_palettes.shallows[2] if self.terrain < 0 and land: self.terrain = -1 #self.color = color_palettes.shallows[0] elif self.terrain > 0 and len(land) != len(a): #coast = [i for i in self.vertices if i.coast] #if len(coast) > 1: # render_coast(coast) if self.terrain > 2: self.color = random.choice(color_palettes.cliff) else: self.terrain = 1 #self.color = random.choice(color_palettes.sand) def inside_polygon(self, x, y): """ Return True if a coordinate (x, y) is inside a polygon defined by a list of verticies [(x1, y1), (x2, x2), ... , (xN, yN)]. Reference: http://www.ariel.com.au/a/python-point-int-poly.html """ n = len(self.vertices) inside = False p1x, p1y = self.vertices[0].get_cords() for i in range(1, n + 1): p2x, p2y = self.vertices[i % n].get_cords() if y > min(p1y, p2y): if y <= max(p1y, p2y): if x <= max(p1x, p2x): if p1y != p2y: xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x if p1x == p2x or x <= xinters: inside = not inside p1x, p1y = p2x, p2y return inside def fresh_or_salt(self,PolygonList): l = self.get_neighbours(PolygonList) sea_neighbours = [i for i in l if i.terrain < 0] lake_neighbours = [i for i in l if i.terrain == 0] if lake_neighbours: self.terrain = 0 self.color = color_palettes.shallows[2] elif len(sea_neighbours) == len(l): self.terrain = -2 else: count = 0 seen = set() while True: temp = [] for i in sea_neighbours: if i in seen: continue if i.centre == self.centre: continue temp+=i.get_neighbours(PolygonList) seen.add(i) temp = [i for i in temp if i.terrain < 0] if len(temp) == 0: self.terrain = 0 self.color = color_palettes.shallows[2] break else: sea_neighbours+=temp count+=1 if count > 7: break def make_mountain(self,polyList): self.terrain = min(self.terrain+5, 11) self.color = random.choice(color_palettes.terrain[11-self.terrain]) n = self.get_neighbours(polyList) for i in n: i.terrain = min(i.terrain+4,11) i.color = random.choice(color_palettes.terrain[11-i.terrain]) def _add_neighbours(self,poly_site): for i in self.get_neighbours(poly_site): for a,v in enumerate(self.vertices): v.v_neighbours.add(self.__add_v_neighbour(a-1)) v.v_neighbours.add(self.__add_v_neighbour(a+1)) for b,c in enumerate(i.vertices): if v == c: v.neighbours.add(i) c.neighbours.add(self) v.v_neighbours.add(i.__add_v_neighbour(b-1)) v.v_neighbours.add(i.__add_v_neighbour(b+1)) def __add_v_neighbour(self,a): try: return self.vertices[a] except IndexError: return self.vertices[0] def centroid(self): num = len(self.vertices) totalx = 0 totaly = 0 for v in self.vertices: totalx+=v.x totaly+=v.y return totalx//num,totaly//num class Polygon_Dict: """docstring for Polygon Dict.""" def __init__(self,PolygonList,PointRange): self.values = dict() self.max_x, self.max_y = PointRange self.__populate_dict(PolygonList) def __populate_dict(self,PolygonList): a=0 for y in range(self.max_y): for x in range(self.max_x): if x > 0: if self.get_polygon(x-1,y): if self.get_polygon(x-1,y).inside_polygon(x,y): self.values[x,y] = self.values[x-1,y] continue if y > 0: if self.get_polygon(x,y-1): if self.get_polygon(x,y-1).inside_polygon(x,y): self.values[x,y] = self.values[x,y-1] continue for p in PolygonList: if p.inside_polygon(x,y): self.values[x,y] = p break if '{},{}'.format(x,y) not in self.values: a+=1 print(a/(self.max_x*self.max_y)) def get_polygon(self,x,y): try: return self.values[x,y] except KeyError: return False class Floating: """docstring for Floating.""" def __init__(self,x,y): self.x = x self.y = y def update_state(self,newx,newy): self.x = newx self.y = newy pygame.draw.rect(pygame.display.get_surface(),(255,0,0),[newx,newy,32,32],0) class Island: """docstring for Island.""" def __init__(self,seed): random.seed(seed) self.ISLAND_FACTOR = 1.13 # 1.0 means no small islands; 2.0 leads to a lot self.bumps = random.randrange(1,7) self.startAngle = random.uniform(0,2*math.pi) self.dipAngle = random.uniform(0,2*math.pi) self.dipWidth = random.uniform(0.2,0.7) def inside(self,point): x, y = point # has to be 'relative' to centre not absolute point position point_length = (y**2+x**2)**.5 # from '0,0' angle = math.atan2(x,y) # from '0,0' length = 0.5* (max(abs(x)-.35,abs(y)) + point_length) #.5 r1 = 0.5 + .4*math.sin(self.startAngle + self.bumps*angle + math.cos((self.bumps+3)*angle)) r2 = 0.7 - .2*math.sin(self.startAngle + self.bumps*angle - math.sin((self.bumps+2)*angle)) if (abs(angle - self.dipAngle) < self.dipWidth or abs(angle - self.dipAngle + 2*math.pi) < self.dipWidth or abs(angle - self.dipAngle - 2*math.pi) < self.dipWidth): r1 = r2 = .6 # 0.2 #0.9 return (length < r1 or (length > r1*self.ISLAND_FACTOR and length < r2)) def setup(POLYGON_COUNT=4096,SCREEN_WIDTH=1152,SCREEN_HEIGHT=900,HUD_SIZE=32*9, main_island_shape_seed=800,small_island_shape_seed=300,improve_points=False,triangles=False): OFFSETX = int(0.04*SCREEN_WIDTH) OFFSETY = int(0.05*SCREEN_HEIGHT) polygons = [] SECTION_SIZE = POLYGON_COUNT//80 # this is for game use display_size = (SCREEN_WIDTH+HUD_SIZE, SCREEN_HEIGHT) # centre of the effective screen for map generation/display centre = tuple(map(int,((SCREEN_WIDTH+0.4*OFFSETX)/2,(SCREEN_HEIGHT+0.5*OFFSETY)/2))) # euclidean distance from diagonal map corner with a slight offset # larger max_dist will affect the size of the main island max_dist = int((centre[0]**2+centre[1]**2)**.5)-int(6.6*OFFSETX) # these are the polygon centres generator_sites = [] for i in range(POLYGON_COUNT): while True: p = Point( random.randrange(-OFFSETX,SCREEN_WIDTH+OFFSETX), random.randrange(-OFFSETY,SCREEN_HEIGHT+OFFSETY), i) if not [i for i in generator_sites if i.x == p.x and i.y == p.y]: break generator_sites.append( p ) # delaunay triangles provide co-ordinates of polygon vertices print("Generating delaunay triangles...") tris = triangle.delaunay([poly_centre.get_cords() for poly_centre in generator_sites]) Triangles = [Triangle(generator_sites[i[0]],generator_sites[i[1]],generator_sites[i[2]]) for i in tris] # these are class based functions to retain a random seed. Useful for map generation # look at the Island Class for more information print("Generating island shapes...") island_shape = Island(main_island_shape_seed) smaller_island = Island(small_island_shape_seed) # polygons are the polygon objects, poly_sites is a useful look-up dict # for x,y co-ordinates matching a polygon print("Generating polygons...") if triangles: polygons, poly_sites = __alt_polygon_generator(Triangles,centre,max_dist,island_shape,smaller_island) else: polygons, poly_sites = __polygon_generator(generator_sites,Triangles,centre,max_dist,island_shape,smaller_island) if improve_points: generator_sites = [] print("Improving points...") for counter,p in enumerate(polygons): x,y = p.centroid() generator_sites.append( Point(x,y,counter) ) tris = triangle.delaunay([poly_centre.get_cords() for poly_centre in generator_sites]) Triangles = [Triangle(generator_sites[i[0]],generator_sites[i[1]],generator_sites[i[2]]) for i in tris] if triangles: polygons, poly_sites = __alt_polygon_generator(Triangles,centre,max_dist,island_shape,smaller_island) else: polygons, poly_sites = __polygon_generator(generator_sites,Triangles,centre,max_dist,island_shape,smaller_island) ## this is arbitrary and can be changed however it appeared to work reasonably well # I've tried higher and lower. mount_count = POLYGON_COUNT//200 # this is the main generator function and will determine most of the map terrain # see relevant function for more details print("Generating mountains, rivers and city locations...") river_list,city_sites,regions = _determine_terrain(mount_count,poly_sites,polygons,centre,max_dist) print("Generating roads...") road_list = _make_roads(city_sites) print("") print("Map created...") print("Key data:") print("mountains = ",mount_count) print("rivers = ",len(river_list)) print("cities = ",len(city_sites)) print("roads = ",len(road_list)) # return data and render objects return display_size,polygons,poly_sites,river_list,city_sites,road_list,regions def __alt_polygon_generator(triangles,centre,max_dist,island_shape,smaller_island): poly_vertex_dict = {} poly_site = {} polygons = [] for a,t in enumerate(triangles): if a % 100 == 0: print(a) neighbours = [] vertices = [] mid = t.centre() for neighbour in triangles: if neighbour == t: continue for pt in neighbour.pts: if pt in t.pts: if pt not in neighbours: neighbours.append(neighbour.centre()) for v in t.pts: x,y = v.get_cords() if (x,y) in poly_vertex_dict: newVert = poly_vertex_dict[(x,y)] else: newVert = Corner(v) poly_vertex_dict[(x,y)] = newVert vertices.append(newVert) if not vertices: continue p = Polygon( vertices, mid, neighbours ) if (p.centre.x < centre[0]-(5/8)*max_dist) and (p.centre.y < centre[1]-(5/9)*max_dist): p.sea_or_land( (centre[0]-(5/9)*max_dist,centre[1]-(3/4)*max_dist), max_dist//(3.5), smaller_island ) else: p.sea_or_land(centre,max_dist,island_shape) polygons.append(p) poly_site[mid.get_cords()]= p return polygons,poly_site def __polygon_generator(sites,Triangles,centre,max_dist,island_shape,smaller_island): poly_vertex_dict = {} poly_site = {} polygons = [] for site in sites: vertices = [] neighbours = [] for tri in Triangles: if site in tri.pts: x,y = tri.centre().get_cords() if (x,y) in poly_vertex_dict: newVert = poly_vertex_dict[(x,y)] else: newVert = Corner(tri.centre()) poly_vertex_dict[(x,y)] = newVert # poly vertex dict # if already exists vertices.append(newVert) [neighbours.append(i) for i in tri.pts if i is not site if i not in neighbours] if not vertices: continue p = Polygon( vertices, site, neighbours ) if (p.centre.x < centre[0]-(5/8)*max_dist) and (p.centre.y < centre[1]-(5/9)*max_dist): p.sea_or_land( (centre[0]-(5/9)*max_dist,centre[1]-(3/4)*max_dist), max_dist//(3.5), smaller_island ) else: p.sea_or_land(centre,max_dist,island_shape) polygons.append(p) poly_site[site.get_cords()]= p return polygons,poly_site def simple_render(polygons,poly_sites,rivers,cities,roads,regions,font1,font2,flag=False): for p in polygons: if flag: p.render(poly_sites) p.draw() render_rivers(rivers) render_roads(roads) render_cities(cities,font1) render_regions(regions,font2) def pre_render(polygons,poly_sites): for p in polygons: p.render(poly_sites) p.draw() def v_fx(screen): dims = screen.get_size() im1 = pygame.image.tostring(screen,'RGB') im = Image.frombytes('RGB',(dims),im1) im1 = im.filter(ImageFilter.BLUR) im1.save('test.png','PNG') return pygame.image.load('test.png') def pygame_demo_image(): # this function is for demoing a default output size,polygons,poly_sites,rivers,cities,roads,regions = setup() pygame.init() pygame.font.init() screen = pygame.display.set_mode(size,pygame.RESIZABLE) pygame.display.set_caption('Map') city_font = pygame.font.SysFont('arial', 20) region_font = pygame.font.SysFont('arial', 30) simple_render(polygons,poly_sites,rivers,cities,roads,regions,city_font,region_font,flag=True) pygame.image.save(screen,'test.png') pygame.quit() def testVoronoi(): size,polygons,poly_site,river_list,city_sites,road_list,regions = setup(main_island_shape_seed=None) pygame.init() pygame.font.init() city_font = pygame.font.SysFont('cardinal', 20) #cardinal region_font = pygame.font.SysFont('cardinal', 30) GAMEOVER = False clock = pygame.time.Clock() screen = pygame.display.set_mode(size,pygame.RESIZABLE) screen.fill((255,255,255)) pygame.display.set_caption('Voronoi') pygame.draw.rect(screen,(255,0,0),[384,320,32,32],0) curr = Floating(384,320) poly = polyDict = False count = 0 first = False pre_render(polygons,poly_site) render_rivers(river_list) render_roads(road_list) bg = v_fx(screen) while not GAMEOVER: # --- Main event loop for event handling action = False for e in pygame.event.get(): # User did something action = True if e.type == pygame.QUIT: # If user clicked close GAMEOVER = True elif e.type == pygame.MOUSEBUTTONUP: x,y = pygame.mouse.get_pos() found = False """ for p in polygons: if p.inside_polygon(x,y) and not found: pts = [i.get_cords() for i in p.vertices] pygame.draw.polygon(screen,(40,40,40),pts) found = True else: p.draw() """ if action: for p in polygons: p.draw() render_rivers(river_list) render_roads(road_list) render_cities(city_sites,city_font) render_regions(regions,region_font) pygame.display.update() #print(pygame.image.tostring(screen,"RGB")) # --- Limit to 5 frames per second clock.tick(5) if not polyDict: polyDict = not polyDict pygame.quit() if __name__ == '__main__': #testVoronoi() pygame_demo_image()
gpl-3.0
HybridF5/jacket
jacket/db/compute/sqlalchemy/migrate_repo/versions/274_update_instances_project_id_index.py
2
1616
# Copyright 2014 Rackspace Hosting # # 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 oslo_log import log as logging from sqlalchemy import MetaData, Table, Index from jacket.i18n import _LI LOG = logging.getLogger(__name__) def upgrade(migrate_engine): """Change instances (project_id) index to cover (project_id, deleted).""" meta = MetaData(bind=migrate_engine) # Indexes can't be changed, we need to create the new one and delete # the old one instances = Table('instances', meta, autoload=True) for index in instances.indexes: if [c.name for c in index.columns] == ['project_id', 'deleted']: LOG.info(_LI('Skipped adding instances_project_id_deleted_idx ' 'because an equivalent index already exists.')) break else: index = Index('instances_project_id_deleted_idx', instances.c.project_id, instances.c.deleted) index.create() for index in instances.indexes: if [c.name for c in index.columns] == ['project_id']: index.drop()
apache-2.0
petersanchez/django-allauth
allauth/socialaccount/providers/twitch/views.py
62
1037
import requests from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView) from .provider import TwitchProvider class TwitchOAuth2Adapter(OAuth2Adapter): provider_id = TwitchProvider.id access_token_url = 'https://api.twitch.tv/kraken/oauth2/token' authorize_url = 'https://api.twitch.tv/kraken/oauth2/authorize' profile_url = 'https://api.twitch.tv/kraken/user' def complete_login(self, request, app, token, **kwargs): resp = requests.get(self.profile_url, params={'oauth_token': token.token}) extra_data = resp.json() return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(TwitchOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(TwitchOAuth2Adapter)
mit
iut-ibk/DynaMind-UrbanSim
3rdparty/opus/src/urbansim/household_x_gridcell/income_less_housing_cost_scaled.py
2
2763
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from urbansim.functions import attribute_label from numpy import reshape class income_less_housing_cost_scaled(Variable): """ (income - housing_cost) / 10000 where income > housing_cost""" housing_cost = "housing_cost" hh_income = "income" def dependencies(self): return [attribute_label("gridcell", self.housing_cost), attribute_label("household", self.hh_income)] def compute(self, dataset_pool): attr1 = reshape(self.get_dataset().get_attribute_of_dataset(self.hh_income), (self.get_dataset().get_reduced_n(), 1)) # return where(attr1 > self.get_dataset().get_2d_dataset_attribute(self.housing_cost), # ((attr1 - self.get_dataset().get_2d_dataset_attribute(self.housing_cost))/10000),0) return (attr1 - self.get_dataset().get_2d_dataset_attribute(self.housing_cost))/10000 from opus_core.tests import opus_unittest from opus_core.datasets.dataset_pool import DatasetPool from opus_core.storage_factory import StorageFactory from numpy import array from numpy import ma class Tests(opus_unittest.OpusTestCase): variable_name = "urbansim.household_x_gridcell.income_less_housing_cost_scaled" def test_my_inputs(self): storage = StorageFactory().get_storage('dict_storage') storage.write_table( table_name='gridcells', table_data={ 'grid_id': array([1,2,3]), 'housing_cost': array([10000, 20000, 100000]), } ) storage.write_table( table_name='households', table_data={ 'household_id': array([1, 2, 3]), 'income': array([10000, 20000, 500000]), } ) dataset_pool = DatasetPool(package_order=['urbansim'], storage=storage) household_x_gridcell = dataset_pool.get_dataset('household_x_gridcell') household_x_gridcell.compute_variables(self.variable_name, dataset_pool=dataset_pool) values = household_x_gridcell.get_attribute(self.variable_name) should_be = array([[0, -1, -9], [1, 0, -8], [49, 48, 40]]) self.assert_(ma.allclose(values, should_be, rtol=1e-7), msg="Error in " + self.variable_name) if __name__=='__main__': opus_unittest.main()
gpl-2.0
ogenstad/ansible
lib/ansible/modules/network/avi/avi_cloudconnectoruser.py
41
4186
#!/usr/bin/python # # @author: Gaurav Rastogi ([email protected]) # Eric Anderson ([email protected]) # module_check: supported # Avi Version: 17.1.1 # # Copyright: (c) 2017 Gaurav Rastogi, <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: avi_cloudconnectoruser author: Gaurav Rastogi ([email protected]) short_description: Module for setup of CloudConnectorUser Avi RESTful Object description: - This module is used to configure CloudConnectorUser object - more examples at U(https://github.com/avinetworks/devops) requirements: [ avisdk ] version_added: "2.4" options: state: description: - The state that should be applied on the entity. default: present choices: ["absent", "present"] avi_api_update_method: description: - Default method for object update is HTTP PUT. - Setting to patch will override that behavior to use HTTP PATCH. version_added: "2.5" default: put choices: ["put", "patch"] avi_api_patch_op: description: - Patch operation to use when using avi_api_update_method as patch. version_added: "2.5" choices: ["add", "replace", "delete"] azure_serviceprincipal: description: - Field introduced in 17.2.1. version_added: "2.5" azure_userpass: description: - Field introduced in 17.2.1. version_added: "2.5" name: description: - Name of the object. required: true private_key: description: - Private_key of cloudconnectoruser. public_key: description: - Public_key of cloudconnectoruser. tenant_ref: description: - It is a reference to an object of type tenant. url: description: - Avi controller URL of the object. uuid: description: - Unique object identifier of the object. extends_documentation_fragment: - avi ''' EXAMPLES = """ - name: Create a Cloud connector user that is used for integration into cloud platforms avi_cloudconnectoruser: controller: '{{ controller }}' name: root password: '{{ password }}' private_key: | -----BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE KEY-----' public_key: 'ssh-rsa ...' tenant_ref: admin username: '{{ username }}' """ RETURN = ''' obj: description: CloudConnectorUser (api/cloudconnectoruser) object returned: success, changed type: dict ''' from ansible.module_utils.basic import AnsibleModule try: from ansible.module_utils.network.avi.avi import ( avi_common_argument_spec, HAS_AVI, avi_ansible_api) except ImportError: HAS_AVI = False def main(): argument_specs = dict( state=dict(default='present', choices=['absent', 'present']), avi_api_update_method=dict(default='put', choices=['put', 'patch']), avi_api_patch_op=dict(choices=['add', 'replace', 'delete']), azure_serviceprincipal=dict(type='dict',), azure_userpass=dict(type='dict',), name=dict(type='str', required=True), private_key=dict(type='str', no_log=True,), public_key=dict(type='str',), tenant_ref=dict(type='str',), url=dict(type='str',), uuid=dict(type='str',), ) argument_specs.update(avi_common_argument_spec()) module = AnsibleModule( argument_spec=argument_specs, supports_check_mode=True) if not HAS_AVI: return module.fail_json(msg=( 'Avi python API SDK (avisdk>=17.1) is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) return avi_ansible_api(module, 'cloudconnectoruser', set(['private_key'])) if __name__ == '__main__': main()
gpl-3.0
lidiamcfreitas/FenixScheduleMaker
ScheduleMaker/brython/www/src/Lib/formatter.py
751
14930
"""Generic output formatting. Formatter objects transform an abstract flow of formatting events into specific output events on writer objects. Formatters manage several stack structures to allow various properties of a writer object to be changed and restored; writers need not be able to handle relative changes nor any sort of ``change back'' operation. Specific writer properties which may be controlled via formatter objects are horizontal alignment, font, and left margin indentations. A mechanism is provided which supports providing arbitrary, non-exclusive style settings to a writer as well. Additional interfaces facilitate formatting events which are not reversible, such as paragraph separation. Writer objects encapsulate device interfaces. Abstract devices, such as file formats, are supported as well as physical devices. The provided implementations all work with abstract devices. The interface makes available mechanisms for setting the properties which formatter objects manage and inserting data into the output. """ import sys AS_IS = None class NullFormatter: """A formatter which does nothing. If the writer parameter is omitted, a NullWriter instance is created. No methods of the writer are called by NullFormatter instances. Implementations should inherit from this class if implementing a writer interface but don't need to inherit any implementation. """ def __init__(self, writer=None): if writer is None: writer = NullWriter() self.writer = writer def end_paragraph(self, blankline): pass def add_line_break(self): pass def add_hor_rule(self, *args, **kw): pass def add_label_data(self, format, counter, blankline=None): pass def add_flowing_data(self, data): pass def add_literal_data(self, data): pass def flush_softspace(self): pass def push_alignment(self, align): pass def pop_alignment(self): pass def push_font(self, x): pass def pop_font(self): pass def push_margin(self, margin): pass def pop_margin(self): pass def set_spacing(self, spacing): pass def push_style(self, *styles): pass def pop_style(self, n=1): pass def assert_line_data(self, flag=1): pass class AbstractFormatter: """The standard formatter. This implementation has demonstrated wide applicability to many writers, and may be used directly in most circumstances. It has been used to implement a full-featured World Wide Web browser. """ # Space handling policy: blank spaces at the boundary between elements # are handled by the outermost context. "Literal" data is not checked # to determine context, so spaces in literal data are handled directly # in all circumstances. def __init__(self, writer): self.writer = writer # Output device self.align = None # Current alignment self.align_stack = [] # Alignment stack self.font_stack = [] # Font state self.margin_stack = [] # Margin state self.spacing = None # Vertical spacing state self.style_stack = [] # Other state, e.g. color self.nospace = 1 # Should leading space be suppressed self.softspace = 0 # Should a space be inserted self.para_end = 1 # Just ended a paragraph self.parskip = 0 # Skipped space between paragraphs? self.hard_break = 1 # Have a hard break self.have_label = 0 def end_paragraph(self, blankline): if not self.hard_break: self.writer.send_line_break() self.have_label = 0 if self.parskip < blankline and not self.have_label: self.writer.send_paragraph(blankline - self.parskip) self.parskip = blankline self.have_label = 0 self.hard_break = self.nospace = self.para_end = 1 self.softspace = 0 def add_line_break(self): if not (self.hard_break or self.para_end): self.writer.send_line_break() self.have_label = self.parskip = 0 self.hard_break = self.nospace = 1 self.softspace = 0 def add_hor_rule(self, *args, **kw): if not self.hard_break: self.writer.send_line_break() self.writer.send_hor_rule(*args, **kw) self.hard_break = self.nospace = 1 self.have_label = self.para_end = self.softspace = self.parskip = 0 def add_label_data(self, format, counter, blankline = None): if self.have_label or not self.hard_break: self.writer.send_line_break() if not self.para_end: self.writer.send_paragraph((blankline and 1) or 0) if isinstance(format, str): self.writer.send_label_data(self.format_counter(format, counter)) else: self.writer.send_label_data(format) self.nospace = self.have_label = self.hard_break = self.para_end = 1 self.softspace = self.parskip = 0 def format_counter(self, format, counter): label = '' for c in format: if c == '1': label = label + ('%d' % counter) elif c in 'aA': if counter > 0: label = label + self.format_letter(c, counter) elif c in 'iI': if counter > 0: label = label + self.format_roman(c, counter) else: label = label + c return label def format_letter(self, case, counter): label = '' while counter > 0: counter, x = divmod(counter-1, 26) # This makes a strong assumption that lowercase letters # and uppercase letters form two contiguous blocks, with # letters in order! s = chr(ord(case) + x) label = s + label return label def format_roman(self, case, counter): ones = ['i', 'x', 'c', 'm'] fives = ['v', 'l', 'd'] label, index = '', 0 # This will die of IndexError when counter is too big while counter > 0: counter, x = divmod(counter, 10) if x == 9: label = ones[index] + ones[index+1] + label elif x == 4: label = ones[index] + fives[index] + label else: if x >= 5: s = fives[index] x = x-5 else: s = '' s = s + ones[index]*x label = s + label index = index + 1 if case == 'I': return label.upper() return label def add_flowing_data(self, data): if not data: return prespace = data[:1].isspace() postspace = data[-1:].isspace() data = " ".join(data.split()) if self.nospace and not data: return elif prespace or self.softspace: if not data: if not self.nospace: self.softspace = 1 self.parskip = 0 return if not self.nospace: data = ' ' + data self.hard_break = self.nospace = self.para_end = \ self.parskip = self.have_label = 0 self.softspace = postspace self.writer.send_flowing_data(data) def add_literal_data(self, data): if not data: return if self.softspace: self.writer.send_flowing_data(" ") self.hard_break = data[-1:] == '\n' self.nospace = self.para_end = self.softspace = \ self.parskip = self.have_label = 0 self.writer.send_literal_data(data) def flush_softspace(self): if self.softspace: self.hard_break = self.para_end = self.parskip = \ self.have_label = self.softspace = 0 self.nospace = 1 self.writer.send_flowing_data(' ') def push_alignment(self, align): if align and align != self.align: self.writer.new_alignment(align) self.align = align self.align_stack.append(align) else: self.align_stack.append(self.align) def pop_alignment(self): if self.align_stack: del self.align_stack[-1] if self.align_stack: self.align = align = self.align_stack[-1] self.writer.new_alignment(align) else: self.align = None self.writer.new_alignment(None) def push_font(self, font): size, i, b, tt = font if self.softspace: self.hard_break = self.para_end = self.softspace = 0 self.nospace = 1 self.writer.send_flowing_data(' ') if self.font_stack: csize, ci, cb, ctt = self.font_stack[-1] if size is AS_IS: size = csize if i is AS_IS: i = ci if b is AS_IS: b = cb if tt is AS_IS: tt = ctt font = (size, i, b, tt) self.font_stack.append(font) self.writer.new_font(font) def pop_font(self): if self.font_stack: del self.font_stack[-1] if self.font_stack: font = self.font_stack[-1] else: font = None self.writer.new_font(font) def push_margin(self, margin): self.margin_stack.append(margin) fstack = [m for m in self.margin_stack if m] if not margin and fstack: margin = fstack[-1] self.writer.new_margin(margin, len(fstack)) def pop_margin(self): if self.margin_stack: del self.margin_stack[-1] fstack = [m for m in self.margin_stack if m] if fstack: margin = fstack[-1] else: margin = None self.writer.new_margin(margin, len(fstack)) def set_spacing(self, spacing): self.spacing = spacing self.writer.new_spacing(spacing) def push_style(self, *styles): if self.softspace: self.hard_break = self.para_end = self.softspace = 0 self.nospace = 1 self.writer.send_flowing_data(' ') for style in styles: self.style_stack.append(style) self.writer.new_styles(tuple(self.style_stack)) def pop_style(self, n=1): del self.style_stack[-n:] self.writer.new_styles(tuple(self.style_stack)) def assert_line_data(self, flag=1): self.nospace = self.hard_break = not flag self.para_end = self.parskip = self.have_label = 0 class NullWriter: """Minimal writer interface to use in testing & inheritance. A writer which only provides the interface definition; no actions are taken on any methods. This should be the base class for all writers which do not need to inherit any implementation methods. """ def __init__(self): pass def flush(self): pass def new_alignment(self, align): pass def new_font(self, font): pass def new_margin(self, margin, level): pass def new_spacing(self, spacing): pass def new_styles(self, styles): pass def send_paragraph(self, blankline): pass def send_line_break(self): pass def send_hor_rule(self, *args, **kw): pass def send_label_data(self, data): pass def send_flowing_data(self, data): pass def send_literal_data(self, data): pass class AbstractWriter(NullWriter): """A writer which can be used in debugging formatters, but not much else. Each method simply announces itself by printing its name and arguments on standard output. """ def new_alignment(self, align): print("new_alignment(%r)" % (align,)) def new_font(self, font): print("new_font(%r)" % (font,)) def new_margin(self, margin, level): print("new_margin(%r, %d)" % (margin, level)) def new_spacing(self, spacing): print("new_spacing(%r)" % (spacing,)) def new_styles(self, styles): print("new_styles(%r)" % (styles,)) def send_paragraph(self, blankline): print("send_paragraph(%r)" % (blankline,)) def send_line_break(self): print("send_line_break()") def send_hor_rule(self, *args, **kw): print("send_hor_rule()") def send_label_data(self, data): print("send_label_data(%r)" % (data,)) def send_flowing_data(self, data): print("send_flowing_data(%r)" % (data,)) def send_literal_data(self, data): print("send_literal_data(%r)" % (data,)) class DumbWriter(NullWriter): """Simple writer class which writes output on the file object passed in as the file parameter or, if file is omitted, on standard output. The output is simply word-wrapped to the number of columns specified by the maxcol parameter. This class is suitable for reflowing a sequence of paragraphs. """ def __init__(self, file=None, maxcol=72): self.file = file or sys.stdout self.maxcol = maxcol NullWriter.__init__(self) self.reset() def reset(self): self.col = 0 self.atbreak = 0 def send_paragraph(self, blankline): self.file.write('\n'*blankline) self.col = 0 self.atbreak = 0 def send_line_break(self): self.file.write('\n') self.col = 0 self.atbreak = 0 def send_hor_rule(self, *args, **kw): self.file.write('\n') self.file.write('-'*self.maxcol) self.file.write('\n') self.col = 0 self.atbreak = 0 def send_literal_data(self, data): self.file.write(data) i = data.rfind('\n') if i >= 0: self.col = 0 data = data[i+1:] data = data.expandtabs() self.col = self.col + len(data) self.atbreak = 0 def send_flowing_data(self, data): if not data: return atbreak = self.atbreak or data[0].isspace() col = self.col maxcol = self.maxcol write = self.file.write for word in data.split(): if atbreak: if col + len(word) >= maxcol: write('\n') col = 0 else: write(' ') col = col + 1 write(word) col = col + len(word) atbreak = 1 self.col = col self.atbreak = data[-1].isspace() def test(file = None): w = DumbWriter() f = AbstractFormatter(w) if file is not None: fp = open(file) elif sys.argv[1:]: fp = open(sys.argv[1]) else: fp = sys.stdin for line in fp: if line == '\n': f.end_paragraph(1) else: f.add_flowing_data(line) f.end_paragraph(0) if __name__ == '__main__': test()
bsd-2-clause
G-P-S/depot_tools
third_party/gsutil/gslib/command_runner.py
45
4281
#!/usr/bin/env python # coding=utf8 # Copyright 2011 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. """Class that runs a named gsutil command.""" import boto import os from boto.storage_uri import BucketStorageUri from gslib.command import Command from gslib.command import COMMAND_NAME from gslib.command import COMMAND_NAME_ALIASES from gslib.exception import CommandException class CommandRunner(object): def __init__(self, gsutil_bin_dir, boto_lib_dir, config_file_list, gsutil_ver, bucket_storage_uri_class=BucketStorageUri): """ Args: gsutil_bin_dir: Bin dir from which gsutil is running. boto_lib_dir: Lib dir where boto runs. config_file_list: Config file list returned by _GetBotoConfigFileList(). gsutil_ver: Version string of currently running gsutil command. bucket_storage_uri_class: Class to instantiate for cloud StorageUris. Settable for testing/mocking. """ self.gsutil_bin_dir = gsutil_bin_dir self.boto_lib_dir = boto_lib_dir self.config_file_list = config_file_list self.gsutil_ver = gsutil_ver self.bucket_storage_uri_class = bucket_storage_uri_class self.command_map = self._LoadCommandMap() def _LoadCommandMap(self): """Returns dict mapping each command_name to implementing class.""" # Walk gslib/commands and find all commands. commands_dir = os.path.join(self.gsutil_bin_dir, 'gslib', 'commands') for f in os.listdir(commands_dir): # Handles no-extension files, etc. (module_name, ext) = os.path.splitext(f) if ext == '.py': __import__('gslib.commands.%s' % module_name) command_map = {} # Only include Command subclasses in the dict. for command in Command.__subclasses__(): command_map[command.command_spec[COMMAND_NAME]] = command for command_name_aliases in command.command_spec[COMMAND_NAME_ALIASES]: command_map[command_name_aliases] = command return command_map def RunNamedCommand(self, command_name, args=None, headers=None, debug=0, parallel_operations=False, test_method=None, bypass_prodaccess=True): """Runs the named command. Used by gsutil main, commands built atop other commands, and tests . Args: command_name: The name of the command being run. args: Command-line args (arg0 = actual arg, not command name ala bash). headers: Dictionary containing optional HTTP headers to pass to boto. debug: Debug level to pass in to boto connection (range 0..3). parallel_operations: Should command operations be executed in parallel? test_method: Optional general purpose method for testing purposes. Application and semantics of this method will vary by command and test type. Raises: CommandException: if errors encountered. """ if not args: args = [] # Include api_version header in all commands. api_version = boto.config.get_value('GSUtil', 'default_api_version', '1') if not headers: headers = {} headers['x-goog-api-version'] = api_version if command_name not in self.command_map: raise CommandException('Invalid command "%s".' % command_name) command_class = self.command_map[command_name] command_inst = command_class(self, args, headers, debug, parallel_operations, self.gsutil_bin_dir, self.boto_lib_dir, self.config_file_list, self.gsutil_ver, self.bucket_storage_uri_class, test_method, bypass_prodaccess) return command_inst.RunCommand()
bsd-3-clause
sysalexis/kbengine
kbe/src/lib/python/Lib/idlelib/GrepDialog.py
61
5143
import os import fnmatch import re # for htest import sys from tkinter import StringVar, BooleanVar, Checkbutton # for GrepDialog from tkinter import Tk, Text, Button, SEL, END # for htest from idlelib import SearchEngine import itertools from idlelib.SearchDialogBase import SearchDialogBase # Importing OutputWindow fails due to import loop # EditorWindow -> GrepDialop -> OutputWindow -> EditorWindow def grep(text, io=None, flist=None): root = text._root() engine = SearchEngine.get(root) if not hasattr(engine, "_grepdialog"): engine._grepdialog = GrepDialog(root, engine, flist) dialog = engine._grepdialog searchphrase = text.get("sel.first", "sel.last") dialog.open(text, searchphrase, io) class GrepDialog(SearchDialogBase): title = "Find in Files Dialog" icon = "Grep" needwrapbutton = 0 def __init__(self, root, engine, flist): SearchDialogBase.__init__(self, root, engine) self.flist = flist self.globvar = StringVar(root) self.recvar = BooleanVar(root) def open(self, text, searchphrase, io=None): SearchDialogBase.open(self, text, searchphrase) if io: path = io.filename or "" else: path = "" dir, base = os.path.split(path) head, tail = os.path.splitext(base) if not tail: tail = ".py" self.globvar.set(os.path.join(dir, "*" + tail)) def create_entries(self): SearchDialogBase.create_entries(self) self.globent = self.make_entry("In files:", self.globvar)[0] def create_other_buttons(self): f = self.make_frame()[0] btn = Checkbutton(f, anchor="w", variable=self.recvar, text="Recurse down subdirectories") btn.pack(side="top", fill="both") btn.select() def create_command_buttons(self): SearchDialogBase.create_command_buttons(self) self.make_button("Search Files", self.default_command, 1) def default_command(self, event=None): prog = self.engine.getprog() if not prog: return path = self.globvar.get() if not path: self.top.bell() return from idlelib.OutputWindow import OutputWindow # leave here! save = sys.stdout try: sys.stdout = OutputWindow(self.flist) self.grep_it(prog, path) finally: sys.stdout = save def grep_it(self, prog, path): dir, base = os.path.split(path) list = self.findfiles(dir, base, self.recvar.get()) list.sort() self.close() pat = self.engine.getpat() print("Searching %r in %s ..." % (pat, path)) hits = 0 try: for fn in list: try: with open(fn, errors='replace') as f: for lineno, line in enumerate(f, 1): if line[-1:] == '\n': line = line[:-1] if prog.search(line): sys.stdout.write("%s: %s: %s\n" % (fn, lineno, line)) hits += 1 except OSError as msg: print(msg) print(("Hits found: %s\n" "(Hint: right-click to open locations.)" % hits) if hits else "No hits.") except AttributeError: # Tk window has been closed, OutputWindow.text = None, # so in OW.write, OW.text.insert fails. pass def findfiles(self, dir, base, rec): try: names = os.listdir(dir or os.curdir) except OSError as msg: print(msg) return [] list = [] subdirs = [] for name in names: fn = os.path.join(dir, name) if os.path.isdir(fn): subdirs.append(fn) else: if fnmatch.fnmatch(name, base): list.append(fn) if rec: for subdir in subdirs: list.extend(self.findfiles(subdir, base, rec)) return list def close(self, event=None): if self.top: self.top.grab_release() self.top.withdraw() def _grep_dialog(parent): # for htest from idlelib.PyShell import PyShellFileList root = Tk() root.title("Test GrepDialog") width, height, x, y = list(map(int, re.split('[x+]', parent.geometry()))) root.geometry("+%d+%d"%(x, y + 150)) flist = PyShellFileList(root) text = Text(root, height=5) text.pack() def show_grep_dialog(): text.tag_add(SEL, "1.0", END) grep(text, flist=flist) text.tag_remove(SEL, "1.0", END) button = Button(root, text="Show GrepDialog", command=show_grep_dialog) button.pack() root.mainloop() if __name__ == "__main__": import unittest unittest.main('idlelib.idle_test.test_grep', verbosity=2, exit=False) from idlelib.idle_test.htest import run run(_grep_dialog)
lgpl-3.0
stefanv/aandete
app/lib/pygments/styles/autumn.py
31
2144
# -*- coding: utf-8 -*- """ pygments.styles.autumn ~~~~~~~~~~~~~~~~~~~~~~ A colorful style, inspired by the terminal highlighting style. :copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace class AutumnStyle(Style): """ A colorful style, inspired by the terminal highlighting style. """ default_style = "" styles = { Whitespace: '#bbbbbb', Comment: 'italic #aaaaaa', Comment.Preproc: 'noitalic #4c8317', Comment.Special: 'italic #0000aa', Keyword: '#0000aa', Keyword.Type: '#00aaaa', Operator.Word: '#0000aa', Name.Builtin: '#00aaaa', Name.Function: '#00aa00', Name.Class: 'underline #00aa00', Name.Namespace: 'underline #00aaaa', Name.Variable: '#aa0000', Name.Constant: '#aa0000', Name.Entity: 'bold #800', Name.Attribute: '#1e90ff', Name.Tag: 'bold #1e90ff', Name.Decorator: '#888888', String: '#aa5500', String.Symbol: '#0000aa', String.Regex: '#009999', Number: '#009999', Generic.Heading: 'bold #000080', Generic.Subheading: 'bold #800080', Generic.Deleted: '#aa0000', Generic.Inserted: '#00aa00', Generic.Error: '#aa0000', Generic.Emph: 'italic', Generic.Strong: 'bold', Generic.Prompt: '#555555', Generic.Output: '#888888', Generic.Traceback: '#aa0000', Error: '#F00 bg:#FAA' }
bsd-3-clause
ApuliaSoftware/odoo
addons/account_asset/__openerp__.py
314
2182
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Assets Management', 'version': '1.0', 'depends': ['account'], 'author': 'OpenERP S.A.', 'description': """ Financial and accounting asset management. ========================================== This Module manages the assets owned by a company or an individual. It will keep track of depreciation's occurred on those assets. And it allows to create Move's of the depreciation lines. """, 'website': 'https://www.odoo.com/page/accounting', 'category': 'Accounting & Finance', 'sequence': 32, 'demo': [ 'account_asset_demo.xml'], 'test': [ 'test/account_asset_demo.yml', 'test/account_asset.yml', 'test/account_asset_wizard.yml', ], 'data': [ 'security/account_asset_security.xml', 'security/ir.model.access.csv', 'wizard/account_asset_change_duration_view.xml', 'wizard/wizard_asset_compute_view.xml', 'account_asset_view.xml', 'account_asset_invoice_view.xml', 'report/account_asset_report_view.xml', ], 'auto_install': False, 'installable': True, 'application': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
takeshineshiro/nova
nova/cells/scheduler.py
46
11483
# Copyright (c) 2012 Rackspace Hosting # 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. """ Cells Scheduler """ import copy import time from oslo_config import cfg from oslo_log import log as logging from six.moves import range from nova.cells import filters from nova.cells import weights from nova import compute from nova.compute import instance_actions from nova.compute import vm_states from nova import conductor from nova.db import base from nova import exception from nova.i18n import _LE, _LI from nova import objects from nova.objects import base as obj_base from nova.scheduler import utils as scheduler_utils from nova import utils cell_scheduler_opts = [ cfg.ListOpt('scheduler_filter_classes', default=['nova.cells.filters.all_filters'], help='Filter classes the cells scheduler should use. ' 'An entry of "nova.cells.filters.all_filters" ' 'maps to all cells filters included with nova.'), cfg.ListOpt('scheduler_weight_classes', default=['nova.cells.weights.all_weighers'], help='Weigher classes the cells scheduler should use. ' 'An entry of "nova.cells.weights.all_weighers" ' 'maps to all cell weighers included with nova.'), cfg.IntOpt('scheduler_retries', default=10, help='How many retries when no cells are available.'), cfg.IntOpt('scheduler_retry_delay', default=2, help='How often to retry in seconds when no cells are ' 'available.') ] LOG = logging.getLogger(__name__) CONF = cfg.CONF CONF.register_opts(cell_scheduler_opts, group='cells') class CellsScheduler(base.Base): """The cells scheduler.""" def __init__(self, msg_runner): super(CellsScheduler, self).__init__() self.msg_runner = msg_runner self.state_manager = msg_runner.state_manager self.compute_api = compute.API() self.compute_task_api = conductor.ComputeTaskAPI() self.filter_handler = filters.CellFilterHandler() filter_classes = self.filter_handler.get_matching_classes( CONF.cells.scheduler_filter_classes) self.filters = [cls() for cls in filter_classes] self.weight_handler = weights.CellWeightHandler() weigher_classes = self.weight_handler.get_matching_classes( CONF.cells.scheduler_weight_classes) self.weighers = [cls() for cls in weigher_classes] def _create_instances_here(self, ctxt, instance_uuids, instance_properties, instance_type, image, security_groups, block_device_mapping): instance_values = copy.copy(instance_properties) # The parent may pass these metadata values as lists, and the # create call expects it to be a dict. instance_values['metadata'] = utils.instance_meta(instance_values) # Pop out things that will get set properly when re-creating the # instance record. instance_values.pop('id') instance_values.pop('name') instance_values.pop('info_cache') instance_values.pop('security_groups') instance_values.pop('flavor') # FIXME(danms): The instance was brutally serialized before being # sent over RPC to us. Thus, the pci_requests value wasn't really # sent in a useful form. Since it was getting ignored for cells # before it was part of the Instance, skip it now until cells RPC # is sending proper instance objects. instance_values.pop('pci_requests', None) instances = [] num_instances = len(instance_uuids) for i, instance_uuid in enumerate(instance_uuids): instance = objects.Instance(context=ctxt) instance.update(instance_values) instance.uuid = instance_uuid instance.flavor = instance_type instance.old_flavor = None instance.new_flavor = None instance = self.compute_api.create_db_entry_for_new_instance( ctxt, instance_type, image, instance, security_groups, block_device_mapping, num_instances, i) instances.append(instance) self.msg_runner.instance_update_at_top(ctxt, instance) return instances def _create_action_here(self, ctxt, instance_uuids): for instance_uuid in instance_uuids: objects.InstanceAction.action_start( ctxt, instance_uuid, instance_actions.CREATE, want_result=False) def _get_possible_cells(self): cells = self.state_manager.get_child_cells() our_cell = self.state_manager.get_my_state() # Include our cell in the list, if we have any capacity info if not cells or our_cell.capacities: cells.append(our_cell) return cells def _grab_target_cells(self, filter_properties): cells = self._get_possible_cells() cells = self.filter_handler.get_filtered_objects(self.filters, cells, filter_properties) # NOTE(comstud): I know this reads weird, but the 'if's are nested # this way to optimize for the common case where 'cells' is a list # containing at least 1 entry. if not cells: if cells is None: # None means to bypass further scheduling as a filter # took care of everything. return raise exception.NoCellsAvailable() weighted_cells = self.weight_handler.get_weighed_objects( self.weighers, cells, filter_properties) LOG.debug("Weighted cells: %(weighted_cells)s", {'weighted_cells': weighted_cells}) target_cells = [cell.obj for cell in weighted_cells] return target_cells def _build_instances(self, message, target_cells, instance_uuids, build_inst_kwargs): """Attempt to build instance(s) or send msg to child cell.""" ctxt = message.ctxt instance_properties = obj_base.obj_to_primitive( build_inst_kwargs['instances'][0]) filter_properties = build_inst_kwargs['filter_properties'] instance_type = filter_properties['instance_type'] image = build_inst_kwargs['image'] security_groups = build_inst_kwargs['security_groups'] block_device_mapping = build_inst_kwargs['block_device_mapping'] LOG.debug("Building instances with routing_path=%(routing_path)s", {'routing_path': message.routing_path}) for target_cell in target_cells: try: if target_cell.is_me: # Need to create instance DB entries as the conductor # expects that the instance(s) already exists. instances = self._create_instances_here(ctxt, instance_uuids, instance_properties, instance_type, image, security_groups, block_device_mapping) build_inst_kwargs['instances'] = instances # Need to record the create action in the db as the # conductor expects it to already exist. self._create_action_here(ctxt, instance_uuids) self.compute_task_api.build_instances(ctxt, **build_inst_kwargs) return self.msg_runner.build_instances(ctxt, target_cell, build_inst_kwargs) return except Exception: LOG.exception(_LE("Couldn't communicate with cell '%s'"), target_cell.name) # FIXME(comstud): Would be nice to kick this back up so that # the parent cell could retry, if we had a parent. LOG.error(_LE("Couldn't communicate with any cells")) raise exception.NoCellsAvailable() def build_instances(self, message, build_inst_kwargs): image = build_inst_kwargs['image'] instance_uuids = [inst['uuid'] for inst in build_inst_kwargs['instances']] instances = build_inst_kwargs['instances'] request_spec = scheduler_utils.build_request_spec(message.ctxt, image, instances) filter_properties = copy.copy(build_inst_kwargs['filter_properties']) filter_properties.update({'context': message.ctxt, 'scheduler': self, 'routing_path': message.routing_path, 'host_sched_kwargs': build_inst_kwargs, 'request_spec': request_spec}) self._schedule_build_to_cells(message, instance_uuids, filter_properties, self._build_instances, build_inst_kwargs) def _schedule_build_to_cells(self, message, instance_uuids, filter_properties, method, method_kwargs): """Pick a cell where we should create a new instance(s).""" try: for i in range(max(0, CONF.cells.scheduler_retries) + 1): try: target_cells = self._grab_target_cells(filter_properties) if target_cells is None: # a filter took care of scheduling. skip. return return method(message, target_cells, instance_uuids, method_kwargs) except exception.NoCellsAvailable: if i == max(0, CONF.cells.scheduler_retries): raise sleep_time = max(1, CONF.cells.scheduler_retry_delay) LOG.info(_LI("No cells available when scheduling. Will " "retry in %(sleep_time)s second(s)"), {'sleep_time': sleep_time}) time.sleep(sleep_time) continue except Exception: LOG.exception(_LE("Error scheduling instances %(instance_uuids)s"), {'instance_uuids': instance_uuids}) ctxt = message.ctxt for instance_uuid in instance_uuids: instance = objects.Instance(context=ctxt, uuid=instance_uuid, vm_state=vm_states.ERROR) self.msg_runner.instance_update_at_top(ctxt, instance) try: instance.vm_state = vm_states.ERROR instance.save() except Exception: pass
apache-2.0
redbo/swift
swift/proxy/controllers/account.py
4
8385
# Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from six.moves.urllib.parse import unquote from swift import gettext_ as _ from swift.account.utils import account_listing_response from swift.common.request_helpers import get_listing_content_type from swift.common.middleware.acl import parse_acl, format_acl from swift.common.utils import public from swift.common.constraints import check_metadata from swift.common import constraints from swift.common.http import HTTP_NOT_FOUND, HTTP_GONE from swift.proxy.controllers.base import Controller, clear_info_cache, \ set_info_cache from swift.common.swob import HTTPBadRequest, HTTPMethodNotAllowed from swift.common.request_helpers import get_sys_meta_prefix class AccountController(Controller): """WSGI controller for account requests""" server_type = 'Account' def __init__(self, app, account_name, **kwargs): super(AccountController, self).__init__(app) self.account_name = unquote(account_name) if not self.app.allow_account_management: self.allowed_methods.remove('PUT') self.allowed_methods.remove('DELETE') def add_acls_from_sys_metadata(self, resp): if resp.environ['REQUEST_METHOD'] in ('HEAD', 'GET', 'PUT', 'POST'): prefix = get_sys_meta_prefix('account') + 'core-' name = 'access-control' (extname, intname) = ('x-account-' + name, prefix + name) acl_dict = parse_acl(version=2, data=resp.headers.pop(intname)) if acl_dict: # treat empty dict as empty header resp.headers[extname] = format_acl( version=2, acl_dict=acl_dict) def GETorHEAD(self, req): """Handler for HTTP GET/HEAD requests.""" if len(self.account_name) > constraints.MAX_ACCOUNT_NAME_LENGTH: resp = HTTPBadRequest(request=req) resp.body = 'Account name length of %d longer than %d' % \ (len(self.account_name), constraints.MAX_ACCOUNT_NAME_LENGTH) # Don't cache this. We know the account doesn't exist because # the name is bad; we don't need to cache that because it's # really cheap to recompute. return resp partition = self.app.account_ring.get_part(self.account_name) concurrency = self.app.account_ring.replica_count \ if self.app.concurrent_gets else 1 node_iter = self.app.iter_nodes(self.app.account_ring, partition) resp = self.GETorHEAD_base( req, _('Account'), node_iter, partition, req.swift_entity_path.rstrip('/'), concurrency) if resp.status_int == HTTP_NOT_FOUND: if resp.headers.get('X-Account-Status', '').lower() == 'deleted': resp.status = HTTP_GONE elif self.app.account_autocreate: # This is kind of a lie; we pretend like the account is # there, but it's not. We'll create it as soon as something # tries to write to it, but we don't need databases on disk # to tell us that nothing's there. # # We set a header so that certain consumers can tell it's a # fake listing. The important one is the PUT of a container # to an autocreate account; the proxy checks to see if the # account exists before actually performing the PUT and # creates the account if necessary. If we feed it a perfect # lie, it'll just try to create the container without # creating the account, and that'll fail. resp = account_listing_response(self.account_name, req, get_listing_content_type(req)) resp.headers['X-Backend-Fake-Account-Listing'] = 'yes' # Cache this. We just made a request to a storage node and got # up-to-date information for the account. resp.headers['X-Backend-Recheck-Account-Existence'] = str( self.app.recheck_account_existence) set_info_cache(self.app, req.environ, self.account_name, None, resp) if req.environ.get('swift_owner'): self.add_acls_from_sys_metadata(resp) else: for header in self.app.swift_owner_headers: resp.headers.pop(header, None) return resp @public def PUT(self, req): """HTTP PUT request handler.""" if not self.app.allow_account_management: return HTTPMethodNotAllowed( request=req, headers={'Allow': ', '.join(self.allowed_methods)}) error_response = check_metadata(req, 'account') if error_response: return error_response if len(self.account_name) > constraints.MAX_ACCOUNT_NAME_LENGTH: resp = HTTPBadRequest(request=req) resp.body = 'Account name length of %d longer than %d' % \ (len(self.account_name), constraints.MAX_ACCOUNT_NAME_LENGTH) return resp account_partition, accounts = \ self.app.account_ring.get_nodes(self.account_name) headers = self.generate_request_headers(req, transfer=True) clear_info_cache(self.app, req.environ, self.account_name) resp = self.make_requests( req, self.app.account_ring, account_partition, 'PUT', req.swift_entity_path, [headers] * len(accounts)) self.add_acls_from_sys_metadata(resp) return resp @public def POST(self, req): """HTTP POST request handler.""" if len(self.account_name) > constraints.MAX_ACCOUNT_NAME_LENGTH: resp = HTTPBadRequest(request=req) resp.body = 'Account name length of %d longer than %d' % \ (len(self.account_name), constraints.MAX_ACCOUNT_NAME_LENGTH) return resp error_response = check_metadata(req, 'account') if error_response: return error_response account_partition, accounts = \ self.app.account_ring.get_nodes(self.account_name) headers = self.generate_request_headers(req, transfer=True) clear_info_cache(self.app, req.environ, self.account_name) resp = self.make_requests( req, self.app.account_ring, account_partition, 'POST', req.swift_entity_path, [headers] * len(accounts)) if resp.status_int == HTTP_NOT_FOUND and self.app.account_autocreate: self.autocreate_account(req, self.account_name) resp = self.make_requests( req, self.app.account_ring, account_partition, 'POST', req.swift_entity_path, [headers] * len(accounts)) self.add_acls_from_sys_metadata(resp) return resp @public def DELETE(self, req): """HTTP DELETE request handler.""" # Extra safety in case someone typos a query string for an # account-level DELETE request that was really meant to be caught by # some middleware. if req.query_string: return HTTPBadRequest(request=req) if not self.app.allow_account_management: return HTTPMethodNotAllowed( request=req, headers={'Allow': ', '.join(self.allowed_methods)}) account_partition, accounts = \ self.app.account_ring.get_nodes(self.account_name) headers = self.generate_request_headers(req) clear_info_cache(self.app, req.environ, self.account_name) resp = self.make_requests( req, self.app.account_ring, account_partition, 'DELETE', req.swift_entity_path, [headers] * len(accounts)) return resp
apache-2.0
zentyal/sogo
Tests/Integration/test-davacl.py
2
47735
#!/usr/bin/python from config import hostname, port, username, password, subscriber_username, subscriber_password, \ superuser, superuser_password import sys import unittest import webdavlib import time import sogotests import utilities # TODO: # - cal: complete test for "modify": "respond to" causes a 204 but no actual # modification should occur # - ab: testcase for addressbook-query, webdav-sync (no "calendar-data" # equivalent) # - cal: testcase for "calendar-query" # - test rights validity: # - send invalid rights to SOGo and expect failures # - refetch the set of rights and make sure it matches what was set # originally # - test "current-user-acl-set" class DAVCalendarSuperUserAclTest(unittest.TestCase): def __init__(self, arg): self.client = webdavlib.WebDAVClient(hostname, port, superuser, superuser_password) self.resource = "/SOGo/dav/%s/Calendar/test-dav-superuser-acl/" % subscriber_username self.filename = "suevent.ics" self.url = "%s%s" % (self.resource, self.filename) unittest.TestCase.__init__(self, arg) def setUp(self): delete = webdavlib.WebDAVDELETE(self.resource) self.client.execute(delete) mkcol = webdavlib.WebDAVMKCOL(self.resource) self.client.execute(mkcol) self.assertEquals(mkcol.response["status"], 201, "preparation: failure creating collection" "(code = %d)" % mkcol.response["status"]) def tearDown(self): delete = webdavlib.WebDAVDELETE(self.resource) self.client.execute(delete) def _getEvent(self): get = webdavlib.HTTPGET(self.url) self.client.execute(get) if get.response["status"] == 200: event = get.response["body"].replace("\r", "") else: event = None return event def _calendarDataInMultistatus(self, query, response_tag = "{DAV:}response"): event = None # print "\n\n\n%s\n\n" % query.response["body"] # print "\n\n" response_nodes = query.response["document"].findall(response_tag) for response_node in response_nodes: href_node = response_node.find("{DAV:}href") href = href_node.text if href.endswith(self.filename): propstat_node = response_node.find("{DAV:}propstat") if propstat_node is not None: status_node = propstat_node.find("{DAV:}status") status = status_node.text if status.endswith("200 OK"): data_node = propstat_node.find("{DAV:}prop/{urn:ietf:params:xml:ns:caldav}calendar-data") event = data_node.text elif not (status.endswith("404 Resource Not Found") or status.endswith("404 Not Found")): self.fail("%s: unexpected status code: '%s'" % (self.filename, status)) return event def _propfindEvent(self): propfind = webdavlib.WebDAVPROPFIND(self.resource, ["{urn:ietf:params:xml:ns:caldav}calendar-data"], 1) self.client.execute(propfind) if propfind.response["status"] != 404: event = self._calendarDataInMultistatus(propfind) return event def _multigetEvent(self): event = None multiget = webdavlib.CalDAVCalendarMultiget(self.resource, ["{urn:ietf:params:xml:ns:caldav}calendar-data"], [ self.url ]) self.client.execute(multiget) if multiget.response["status"] != 404: event = self._calendarDataInMultistatus(multiget) return event def _webdavSyncEvent(self): event = None sync_query = webdavlib.WebDAVSyncQuery(self.resource, None, ["{urn:ietf:params:xml:ns:caldav}calendar-data"]) self.client.execute(sync_query) if sync_query.response["status"] != 404: event = self._calendarDataInMultistatus(sync_query, "{DAV:}response") return event def testSUAccess(self): """create, read, modify, delete for superuser""" event = event_template % { "class": "PUBLIC", "filename": self.filename, "organizer_line": "", "attendee_line": "" } # 1. Create put = webdavlib.HTTPPUT(self.url, event) put.content_type = "text/calendar; charset=utf-8" self.client.execute(put) self.assertEquals(put.response["status"], 201, "%s: event creation/modification:" " expected status code '201' (received '%d')" % (self.filename, put.response["status"])) # 2. Read readEvent = self._getEvent() self.assertEquals(readEvent, event, "GET: returned event does not match") readEvent = self._propfindEvent() self.assertEquals(readEvent, event, "PROPFIND: returned event does not match") readEvent = self._multigetEvent() self.assertEquals(readEvent, event, "MULTIGET: returned event does not match") readEvent = self._webdavSyncEvent() self.assertEquals(readEvent, event, "WEBDAV-SYNC: returned event does not match") # 3. Modify for eventClass in [ "CONFIDENTIAL", "PRIVATE", "PUBLIC" ]: event = event_template % { "class": eventClass, "filename": self.filename, "organizer_line": "", "attendee_line": "" } put = webdavlib.HTTPPUT(self.url, event) put.content_type = "text/calendar; charset=utf-8" self.client.execute(put) self.assertEquals(put.response["status"], 204, "%s: event modification failed" " expected status code '204' (received '%d')" % (self.filename, put.response["status"])) # 4. Delete delete = webdavlib.WebDAVDELETE(self.url) self.client.execute(delete) self.assertEquals(delete.response["status"], 204, "%s: event deletion failed" " expected status code '204' (received '%d')" % (self.filename, put.response["status"])) class DAVAclTest(unittest.TestCase): resource = None def __init__(self, arg): self.client = webdavlib.WebDAVClient(hostname, port, username, password) unittest.TestCase.__init__(self, arg) def setUp(self): delete = webdavlib.WebDAVDELETE(self.resource) self.client.execute(delete) mkcol = webdavlib.WebDAVMKCOL(self.resource) self.client.execute(mkcol) self.assertEquals(mkcol.response["status"], 201, "preparation: failure creating collection" "(code = %d)" % mkcol.response["status"]) self.subscriber_client = webdavlib.WebDAVClient(hostname, port, subscriber_username, subscriber_password) def tearDown(self): delete = webdavlib.WebDAVDELETE(self.resource) self.client.execute(delete) def _versitLine(self, line): key, value = line.split(":") semicolon = key.find(";") if semicolon > -1: key = key[:semicolon] return (key, value) def versitDict(self, event): versitStruct = {} for line in event.splitlines(): (key, value) = self._versitLine(line) if not (key == "BEGIN" or key == "END"): versitStruct[key] = value return versitStruct event_template = """BEGIN:VCALENDAR PRODID:-//Inverse//Event Generator//EN VERSION:2.0 BEGIN:VEVENT SEQUENCE:0 TRANSP:OPAQUE UID:12345-%(class)s-%(filename)s SUMMARY:%(class)s event (orig. title) DTSTART:20090805T100000Z DTEND:20090805T140000Z CLASS:%(class)s DESCRIPTION:%(class)s description LOCATION:location %(organizer_line)s%(attendee_line)sCREATED:20090805T100000Z DTSTAMP:20090805T100000Z END:VEVENT END:VCALENDAR""" task_template = """BEGIN:VCALENDAR PRODID:-//Inverse//Event Generator//EN VERSION:2.0 BEGIN:VTODO CREATED:20100122T201440Z LAST-MODIFIED:20100201T175246Z DTSTAMP:20100201T175246Z UID:12345-%(class)s-%(filename)s SUMMARY:%(class)s event (orig. title) CLASS:%(class)s DESCRIPTION:%(class)s description STATUS:IN-PROCESS PERCENT-COMPLETE:0 END:VTODO END:VCALENDAR""" class DAVCalendarAclTest(DAVAclTest): resource = '/SOGo/dav/%s/Calendar/test-dav-acl/' % username user_email = None def __init__(self, arg): DAVAclTest.__init__(self, arg) self.acl_utility = utilities.TestCalendarACLUtility(self, self.client, self.resource) def setUp(self): DAVAclTest.setUp(self) self.user_email = self.acl_utility.fetchUserInfo(username)[1] self.classToICSClass = { "pu": "PUBLIC", "pr": "PRIVATE", "co": "CONFIDENTIAL" } self._putEvent(self.client, "public-event.ics", "PUBLIC") self._putEvent(self.client, "private-event.ics", "PRIVATE") self._putEvent(self.client, "confidential-event.ics", "CONFIDENTIAL") self._putTask(self.client, "public-task.ics", "PUBLIC") self._putTask(self.client, "private-task.ics", "PRIVATE") self._putTask(self.client, "confidential-task.ics", "CONFIDENTIAL") def testViewAllPublic(self): """'view all' on a specific class (PUBLIC)""" self._testRights({ "pu": "v" }) def testModifyPublicViewAllPrivateViewDConfidential(self): """'modify' PUBLIC, 'view all' PRIVATE, 'view d&t' confidential""" self._testRights({ "pu": "m", "pr": "v", "co": "d" }) def testCreateOnly(self): """'create' only""" self._testRights({ "c": True }) def testDeleteOnly(self): """'delete' only""" self._testRights({ "d": True }) def testCreateDeleteModifyPublicViewAllPrivateViewDConfidential(self): """'create', 'delete', 'view d&t' PUBLIC, 'modify' PRIVATE""" self._testRights({ "c": True, "d": True, "pu": "d", "pr": "m" }) def testCreateRespondToPublic(self): """'create', 'respond to' PUBLIC""" self._testRights({ "c": True, "pu": "r" }) def testNothing(self): """no right given""" self._testRights({}) def _putEvent(self, client, filename, event_class = "PUBLIC", exp_status = 201, organizer = None, attendee = None, partstat = "NEEDS-ACTION"): url = "%s%s" % (self.resource, filename) if organizer is not None: organizer_line = "ORGANIZER:%s\n" % organizer else: organizer_line = "" if attendee is not None: attendee_line = "ATTENDEE;PARTSTAT=%s:%s\n" % (partstat, attendee) else: attendee_line = "" event = event_template % { "class": event_class, "filename": filename, "organizer_line": organizer_line, "attendee_line": attendee_line } put = webdavlib.HTTPPUT(url, event) put.content_type = "text/calendar; charset=utf-8" client.execute(put) self.assertEquals(put.response["status"], exp_status, "%s: event creation/modification:" " expected status code '%d' (received '%d')" % (filename, exp_status, put.response["status"])) def _putTask(self, client, filename, task_class = "PUBLIC", exp_status = 201): url = "%s%s" % (self.resource, filename) task = task_template % { "class": task_class, "filename": filename } put = webdavlib.HTTPPUT(url, task) put.content_type = "text/calendar; charset=utf-8" client.execute(put) self.assertEquals(put.response["status"], exp_status, "%s: task creation/modification:" " expected status code '%d' (received '%d')" % (filename, exp_status, put.response["status"])) def _deleteEvent(self, client, filename, exp_status = 204): url = "%s%s" % (self.resource, filename) delete = webdavlib.WebDAVDELETE(url) client.execute(delete) self.assertEquals(delete.response["status"], exp_status, "%s: event deletion: expected status code '%d'" " (received '%d')" % (filename, exp_status, delete.response["status"])) def _currentUserPrivilegeSet(self, resource, expStatus = 207): propfind = webdavlib.WebDAVPROPFIND(resource, ["{DAV:}current-user-privilege-set"], 0) self.subscriber_client.execute(propfind) self.assertEquals(propfind.response["status"], expStatus, "unexected status code when reading privileges:" + " %s instead of %d" % (propfind.response["status"], expStatus)) privileges = [] if expStatus < 300: response_nodes = propfind.response["document"].findall("{DAV:}response/{DAV:}propstat/{DAV:}prop/{DAV:}current-user-privilege-set/{DAV:}privilege") for node in response_nodes: privileges.extend([x.tag for x in node.getchildren()]) return privileges def _comparePrivilegeSets(self, expectedPrivileges, privileges): testHash = dict(map(lambda x: (x, True), privileges)) for privilege in expectedPrivileges: self.assertTrue(testHash.has_key(privilege), "expected privilege '%s' not found" % privilege) testHash = dict(map(lambda x: (x, True), expectedPrivileges)) for privilege in privileges: self.assertTrue(testHash.has_key(privilege), "excessive privilege '%s' found" % privilege) def _testCollectionDAVAcl(self, rights): if len(rights) > 0: expectedPrivileges = ['{DAV:}read', '{DAV:}read-current-user-privilege-set', '{urn:ietf:params:xml:ns:caldav}read-free-busy'] else: expectedPrivileges = [] if rights.has_key("c"): extraPrivileges = ["{DAV:}bind", "{DAV:}write-content", '{urn:ietf:params:xml:ns:caldav}schedule', '{urn:ietf:params:xml:ns:caldav}schedule-post', '{urn:ietf:params:xml:ns:caldav}schedule-post-vevent', '{urn:ietf:params:xml:ns:caldav}schedule-post-vtodo', '{urn:ietf:params:xml:ns:caldav}schedule-post-vjournal', '{urn:ietf:params:xml:ns:caldav}schedule-post-vfreebusy', '{urn:ietf:params:xml:ns:caldav}schedule-deliver', '{urn:ietf:params:xml:ns:caldav}schedule-deliver-vevent', '{urn:ietf:params:xml:ns:caldav}schedule-deliver-vtodo', '{urn:ietf:params:xml:ns:caldav}schedule-deliver-vjournal', '{urn:ietf:params:xml:ns:caldav}schedule-deliver-vfreebusy', '{urn:ietf:params:xml:ns:caldav}schedule-respond', '{urn:ietf:params:xml:ns:caldav}schedule-respond-vevent', '{urn:ietf:params:xml:ns:caldav}schedule-respond-vtodo'] expectedPrivileges.extend(extraPrivileges) if rights.has_key("d"): expectedPrivileges.append("{DAV:}unbind") if len(expectedPrivileges) == 0: expStatus = 404 else: expStatus = 207 privileges = self._currentUserPrivilegeSet(self.resource, expStatus) # When comparing privileges on DAV collection, we remove all 'default' # privileges on the collection. privileges_set = set(privileges); for x in ("public", "private", "confidential"): privileges_set.discard("{urn:inverse:params:xml:ns:inverse-dav}viewwhole-%s-records" % x) privileges_set.discard("{urn:inverse:params:xml:ns:inverse-dav}viewdant-%s-records" % x) privileges_set.discard("{urn:inverse:params:xml:ns:inverse-dav}modify-%s-records" % x) privileges_set.discard("{urn:inverse:params:xml:ns:inverse-dav}respondto-%s-records" %x) self._comparePrivilegeSets(expectedPrivileges, list(privileges_set)) def _testEventDAVAcl(self, event_class, right, error_code): icsClass = self.classToICSClass[event_class].lower() for suffix in [ "event", "task" ]: url = "%s%s-%s.ics" % (self.resource, icsClass, suffix) if right is None: expStatus = error_code expectedPrivileges = None else: expStatus = 207 expectedPrivileges = ['{DAV:}read-current-user-privilege-set', '{urn:inverse:params:xml:ns:inverse-dav}view-date-and-time', '{DAV:}read'] if right != "d": extraPrivilege = '{urn:inverse:params:xml:ns:inverse-dav}view-whole-component' expectedPrivileges.append(extraPrivilege) if right != "v": extraPrivileges = ['{urn:inverse:params:xml:ns:inverse-dav}respond-to-component', '{DAV:}write-content'] expectedPrivileges.extend(extraPrivileges) if right != "r": extraPrivileges = ['{DAV:}write-properties', '{DAV:}write'] expectedPrivileges.extend(extraPrivileges) privileges = self._currentUserPrivilegeSet(url, expStatus) if expStatus != error_code: self._comparePrivilegeSets(expectedPrivileges, privileges) def _testRights(self, rights): self.acl_utility.setupRights(subscriber_username, rights) self._testCreate(rights) self._testCollectionDAVAcl(rights) self._testEventRight("pu", rights) self._testEventRight("pr", rights) self._testEventRight("co", rights) self._testDelete(rights) def _testCreate(self, rights): if rights.has_key("c") and rights["c"]: exp_code = 201 elif len(rights) == 0: exp_code = 404 else: exp_code = 403 self._putEvent(self.subscriber_client, "creation-test.ics", "PUBLIC", exp_code) def _testDelete(self, rights): if rights.has_key("d") and rights["d"]: exp_code = 204 elif len(rights) == 0: exp_code = 404 else: exp_code = 403 self._deleteEvent(self.subscriber_client, "public-event.ics", exp_code) self._deleteEvent(self.subscriber_client, "private-event.ics", exp_code) self._deleteEvent(self.subscriber_client, "confidential-event.ics", exp_code) def _testEventRight(self, event_class, rights): if rights.has_key(event_class): right = rights[event_class] else: right = None event = self._getEvent(event_class) self._checkViewEventRight("GET", event, event_class, right) event = self._propfindEvent(event_class) self._checkViewEventRight("PROPFIND", event, event_class, right) event = self._multigetEvent(event_class) self._checkViewEventRight("multiget", event, event_class, right) event = self._webdavSyncEvent(event_class) self._checkViewEventRight("webdav-sync", event, event_class, right) if len(rights) > 0: error_code = 403 else: error_code = 404 self._testModify(event_class, right, error_code) self._testRespondTo(event_class, right, error_code) self._testEventDAVAcl(event_class, right, error_code) def _getEvent(self, event_class, is_invitation = False): icsClass = self.classToICSClass[event_class] if is_invitation: filename = "invitation-%s" % icsClass.lower() else: filename = "%s" % icsClass.lower() url = "%s%s-event.ics" % (self.resource, filename) get = webdavlib.HTTPGET(url) self.subscriber_client.execute(get) if get.response["status"] == 200: event = get.response["body"].replace("\r", "") else: event = None return event def _getTask(self, task_class): filename = "%s" % self.classToICSClass[task_class].lower() url = "%s%s-task.ics" % (self.resource, filename) get = webdavlib.HTTPGET(url) self.subscriber_client.execute(get) if get.response["status"] == 200: task = get.response["body"] else: task = None return task def _calendarDataInMultistatus(self, query, filename, response_tag = "{DAV:}response"): event = None # print "\n\n\n%s\n\n" % query.response["body"] # print "\n\n" response_nodes = query.response["document"].findall("%s" % response_tag) for response_node in response_nodes: href_node = response_node.find("{DAV:}href") href = href_node.text if href.endswith(filename): propstat_node = response_node.find("{DAV:}propstat") if propstat_node is not None: status_node = propstat_node.find("{DAV:}status") status = status_node.text if status.endswith("200 OK"): data_node = propstat_node.find("{DAV:}prop/{urn:ietf:params:xml:ns:caldav}calendar-data") event = data_node.text elif not (status.endswith("404 Resource Not Found") or status.endswith("404 Not Found")): self.fail("%s: unexpected status code: '%s'" % (filename, status)) return event def _propfindEvent(self, event_class): event = None icsClass = self.classToICSClass[event_class] filename = "%s-event.ics" % icsClass.lower() propfind = webdavlib.WebDAVPROPFIND(self.resource, ["{urn:ietf:params:xml:ns:caldav}calendar-data"], 1) self.subscriber_client.execute(propfind) if propfind.response["status"] != 404: event = self._calendarDataInMultistatus(propfind, filename) return event def _multigetEvent(self, event_class): event = None icsClass = self.classToICSClass[event_class] url = "%s%s-event.ics" % (self.resource, icsClass.lower()) multiget = webdavlib.CalDAVCalendarMultiget(self.resource, ["{urn:ietf:params:xml:ns:caldav}calendar-data"], [ url ]) self.subscriber_client.execute(multiget) if multiget.response["status"] != 404: event = self._calendarDataInMultistatus(multiget, url) return event def _webdavSyncEvent(self, event_class): event = None icsClass = self.classToICSClass[event_class] url = "%s%s-event.ics" % (self.resource, icsClass.lower()) sync_query = webdavlib.WebDAVSyncQuery(self.resource, None, ["{urn:ietf:params:xml:ns:caldav}calendar-data"]) self.subscriber_client.execute(sync_query) if sync_query.response["status"] != 404: event = self._calendarDataInMultistatus(sync_query, url, "{DAV:}response") return event def _checkViewEventRight(self, operation, event, event_class, right): if right is None: self.assertEquals(event, None, "None right expecting event invisibility for" " operation '%s'" % operation) else: self.assertTrue(event is not None, "no event returned during operation '%s'" " (right: %s)" % (operation, right)) if right == "v" or right == "r" or right == "m": icsClass = self.classToICSClass[event_class] complete_event = (event_template % {"class": icsClass, "filename": "%s-event.ics" % icsClass.lower(), "organizer_line": "", "attendee_line": ""}) self.assertTrue(event.strip() == complete_event.strip(), "Right '%s' should return complete event" " during operation '%s'" % (right, operation)) elif right == "d": self._testEventIsSecureVersion(event_class, event) else: self.fail("Right '%s' is not supported" % right) def _testEventIsSecureVersion(self, event_class, event): icsClass = self.classToICSClass[event_class] expected_dict = { "VERSION": "2.0", "PRODID": "-//Inverse//Event Generator//EN", "SEQUENCE": "0", "TRANSP": "OPAQUE", "UID": "12345-%s-%s-event.ics" % (icsClass, icsClass.lower()), "SUMMARY": "(%s event)" % icsClass.capitalize(), "DTSTART": "20090805T100000Z", "DTEND": "20090805T140000Z", "CLASS": icsClass, "CREATED": "20090805T100000Z", "DTSTAMP": "20090805T100000Z", "X-SOGO-SECURE": "YES" } event_dict = self.versitDict(event) for key in event_dict.keys(): self.assertTrue(expected_dict.has_key(key), "key '%s' of secure event not expected" % key) self.assertTrue(expected_dict[key] == event_dict[key] or key == "SUMMARY", "value for key '%s' of secure does not match" " (exp: '%s', obtained: '%s'" % (key, expected_dict[key], event_dict[key] )) for key in expected_dict.keys(): self.assertTrue(event_dict.has_key(key), "expected key '%s' not found in secure event" % key) def _testModify(self, event_class, right, error_code): if right == "m" or right == "r": exp_code = 204 else: exp_code = error_code icsClass = self.classToICSClass[event_class] filename = "%s-event.ics" % icsClass.lower() self._putEvent(self.subscriber_client, filename, icsClass, exp_code) def _testRespondTo(self, event_class, right, error_code): icsClass = self.classToICSClass[event_class] filename = "invitation-%s-event.ics" % icsClass.lower() self._putEvent(self.client, filename, icsClass, 201, "mailto:[email protected]", self.user_email, "NEEDS-ACTION") if right == "m" or right == "r": exp_code = 204 else: exp_code = error_code # here we only do 'passive' validation: if a user has a "respond to" # right, only the attendee entry will me modified. The change of # organizer must thus be silently ignored below. self._putEvent(self.subscriber_client, filename, icsClass, exp_code, "mailto:[email protected]", self.user_email, "ACCEPTED") if exp_code == 204: att_line = "ATTENDEE;PARTSTAT=ACCEPTED:%s\n" % self.user_email if right == "r": exp_event = event_template % {"class": icsClass, "filename": filename, "organizer_line": "ORGANIZER;[email protected]:mailto:[email protected]\n", "attendee_line": att_line} else: exp_event = event_template % {"class": icsClass, "filename": filename, "organizer_line": "ORGANIZER;[email protected]:mailto:[email protected]\n", "attendee_line": att_line} event = self._getEvent(event_class, True) ics_diff = utilities.ics_compare(exp_event, event) self.assertTrue(ics_diff.areEqual(), "'respond to' event does not match:\n" "Diff(expected, got):\n %s" % ics_diff.textDiff()) class DAVAddressBookAclTest(DAVAclTest): resource = '/SOGo/dav/%s/Contacts/test-dav-acl/' % username cards = { "new.vcf": """BEGIN:VCARD VERSION:3.0 PRODID:-//Inverse//Card Generator//EN UID:NEWTESTCARD N:New;Carte FN:Carte 'new' ORG:societe;service NICKNAME:surnom ADR;TYPE=work:adr2 societe;;adr societe;ville societe;etat soc;code soc;pays soc ADR;TYPE=home:rue perso 2;;rue perso;ville perso;etat perso;code post perso;pays perso TEL;TYPE=work:+1 514 123-3372 TEL;TYPE=home:tel dom TEL;TYPE=cell:portable TEL;TYPE=fax:fax TEL;TYPE=pager:pager X-MOZILLA-HTML:FALSE EMAIL;TYPE=work:[email protected] EMAIL;TYPE=home:[email protected] URL;TYPE=home:web perso TITLE:fonction URL;TYPE=work:page soc CUSTOM1:divers1 CUSTOM2:divers2 CUSTOM3:divers3 CUSTOM4:divers4 NOTE:Remarque X-AIM:pseudo aim END:VCARD""", "old.vcf": """BEGIN:VCARD VERSION:3.0 PRODID:-//Inverse//Card Generator//EN UID:NEWTESTCARD N:Old;Carte FN:Carte 'old' ORG:societe;service NICKNAME:surnom ADR;TYPE=work:adr2 societe;;adr societe;ville societe;etat soc;code soc;pays soc ADR;TYPE=home:rue perso 2;;rue perso;ville perso;etat perso;code post perso;pays perso TEL;TYPE=work:+1 514 123-3372 TEL;TYPE=home:tel dom TEL;TYPE=cell:portable TEL;TYPE=fax:fax TEL;TYPE=pager:pager X-MOZILLA-HTML:FALSE EMAIL;TYPE=work:[email protected] EMAIL;TYPE=home:[email protected] URL;TYPE=home:web perso TITLE:fonction URL;TYPE=work:page soc CUSTOM1:divers1 CUSTOM2:divers2 CUSTOM3:divers3 CUSTOM4:divers4 NOTE:Remarque X-AIM:pseudo aim END:VCARD""", "new-modified.vcf": """BEGIN:VCARD VERSION:3.0 PRODID:-//Inverse//Card Generator//EN UID:NEWTESTCARD N:New;Carte modifiee FN:Carte modifiee 'new' ORG:societe;service NICKNAME:surnom ADR;TYPE=work:adr2 societe;;adr societe;ville societe;etat soc;code soc;pays soc ADR;TYPE=home:rue perso 2;;rue perso;ville perso;etat perso;code post perso;pays perso TEL;TYPE=work:+1 514 123-3372 TEL;TYPE=home:tel dom TEL;TYPE=cell:portable TEL;TYPE=fax:fax TEL;TYPE=pager:pager X-MOZILLA-HTML:FALSE EMAIL;TYPE=work:[email protected] EMAIL;TYPE=home:[email protected] URL;TYPE=home:web perso TITLE:fonction URL;TYPE=work:page soc CUSTOM1:divers1 CUSTOM2:divers2 CUSTOM3:divers3 CUSTOM4:divers4 NOTE:Remarque X-AIM:pseudo aim END:VCARD""", "old-modified.vcf": """BEGIN:VCARD VERSION:3.0 PRODID:-//Inverse//Card Generator//EN UID:NEWTESTCARD N:Old;Carte modifiee FN:Carte modifiee 'old' ORG:societe;service NICKNAME:surnom ADR;TYPE=work:adr2 societe;;adr societe;ville societe;etat soc;code soc;pays soc ADR;TYPE=home:rue perso 2;;rue perso;ville perso;etat perso;code post perso;pays perso TEL;TYPE=work:+1 514 123-3372 TEL;TYPE=home:tel dom TEL;TYPE=cell:portable TEL;TYPE=fax:fax TEL;TYPE=pager:pager X-MOZILLA-HTML:FALSE EMAIL;TYPE=work:[email protected] EMAIL;TYPE=home:[email protected] URL;TYPE=home:web perso TITLE:fonction URL;TYPE=work:page soc CUSTOM1:divers1 CUSTOM2:divers2 CUSTOM3:divers3 CUSTOM4:divers4 NOTE:Remarque X-AIM:pseudo aim END:VCARD""" } def __init__(self, arg): DAVAclTest.__init__(self, arg) self.acl_utility = utilities.TestAddressBookACLUtility(self, self.client, self.resource) def setUp(self): DAVAclTest.setUp(self) self._putCard(self.client, "old.vcf", 201) def testView(self): """'view' only""" self._testRights({ "v": True }) def testEdit(self): """'edit' only""" self._testRights({ "e": True }) def testCreateOnly(self): """'create' only""" self._testRights({ "c": True }) def testDeleteOnly(self): """'delete' only""" self._testRights({ "d": True }) def testCreateDelete(self): """'create', 'delete'""" self._testRights({ "c": True, "d": True }) def testViewCreate(self): """'view' and 'create'""" self._testRights({ "c": True, "v": True }) def testViewDelete(self): """'view' and 'delete'""" self._testRights({ "d": True, "v": True }) def testEditCreate(self): """'edit' and 'create'""" self._testRights({ "c": True, "e": True }) def testEditDelete(self): """'edit' and 'delete'""" self._testRights({ "d": True, "e": True }) def _testRights(self, rights): self.acl_utility.setupRights(subscriber_username, rights) self._testCreate(rights) self._testView(rights) self._testEdit(rights) self._testDelete(rights) def _putCard(self, client, filename, exp_status, real_card = None): url = "%s%s" % (self.resource, filename) if real_card is None: real_card = filename card = self.cards[real_card] put = webdavlib.HTTPPUT(url, card) put.content_type = "text/x-vcard; charset=utf-8" client.execute(put) self.assertEquals(put.response["status"], exp_status, "%s: card creation/modification:" " expected status code '%d' (received '%d')" % (filename, exp_status, put.response["status"])) def _getCard(self, client, filename, exp_status): url = "%s%s" % (self.resource, filename) get = webdavlib.HTTPGET(url) client.execute(get) self.assertEquals(get.response["status"], exp_status, "%s: card get:" " expected status code '%d' (received '%d')" % (filename, exp_status, get.response["status"])) def _deleteCard(self, client, filename, exp_status): url = "%s%s" % (self.resource, filename) delete = webdavlib.WebDAVDELETE(url) client.execute(delete) self.assertEquals(delete.response["status"], exp_status, "%s: card deletion:" " expected status code '%d' (received '%d')" % (filename, exp_status, delete.response["status"])) def _testCreate(self, rights): if rights.has_key("c") and rights["c"]: exp_code = 201 else: exp_code = 403 self._putCard(self.subscriber_client, "new.vcf", exp_code) def _testView(self, rights): if ((rights.has_key("v") and rights["v"]) or (rights.has_key("e") and rights["e"])): exp_code = 200 else: exp_code = 403 self._getCard(self.subscriber_client, "old.vcf", exp_code) def _testEdit(self, rights): if rights.has_key("e") and rights["e"]: exp_code = 204 else: exp_code = 403 self._putCard(self.subscriber_client, "old.vcf", exp_code, "old-modified.vcf") def _testDelete(self, rights): if rights.has_key("d") and rights["d"]: exp_code = 204 else: exp_code = 403 self._deleteCard(self.subscriber_client, "old.vcf", exp_code) class DAVPublicAccessTest(unittest.TestCase): def setUp(self): self.client = webdavlib.WebDAVClient(hostname, port) self.anon_client = webdavlib.WebDAVClient(hostname, port) self.dav_utility = utilities.TestUtility(self, self.client) def testPublicAccess(self): resource = '/SOGo/so/public' options = webdavlib.HTTPOPTIONS(resource) self.anon_client.execute(options) self.assertEquals(options.response["status"], 404, "/SOGo/so/public is unexpectedly available") resource = '/SOGo/public' options = webdavlib.HTTPOPTIONS(resource) self.anon_client.execute(options) self.assertEquals(options.response["status"], 404, "/SOGo/public is unexpectedly available") resource = '/SOGo/dav/%s' % username options = webdavlib.HTTPOPTIONS(resource) self.anon_client.execute(options) self.assertEquals(options.response["status"], 401, "Non-public resources should request authentication") resource = '/SOGo/dav/public' options = webdavlib.HTTPOPTIONS(resource) self.anon_client.execute(options) self.assertNotEquals(options.response["status"], 401, "Non-public resources must NOT request authentication") self.assertEquals(options.response["status"], 200, "/SOGo/dav/public is not available, check user defaults") class DAVCalendarPublicAclTest(unittest.TestCase): def setUp(self): self.createdRsrc = None self.superuser_client = webdavlib.WebDAVClient(hostname, port, superuser, superuser_password) self.client = webdavlib.WebDAVClient(hostname, port, username, password) self.subscriber_client = webdavlib.WebDAVClient(hostname, port, subscriber_username, subscriber_password) self.anon_client = webdavlib.WebDAVClient(hostname, port) def tearDown(self): if self.createdRsrc is not None: delete = webdavlib.WebDAVDELETE(self.createdRsrc) self.superuser_client.execute(delete) def testCollectionAccessNormalUser(self): """normal user access to (non-)shared resource from su""" # 1. all rights removed parentColl = '/SOGo/dav/%s/Calendar/' % username self.createdRsrc = '%stest-dav-acl/' % parentColl for rsrc in [ 'personal', 'test-dav-acl' ]: resource = '%s%s/' % (parentColl, rsrc) mkcol = webdavlib.WebDAVMKCOL(resource) self.client.execute(mkcol) acl_utility = utilities.TestCalendarACLUtility(self, self.client, resource) acl_utility.setupRights("anonymous", {}) acl_utility.setupRights(subscriber_username, {}) acl_utility.setupRights("<default>", {}) propfind = webdavlib.WebDAVPROPFIND(parentColl, [ "displayname" ], 1) self.subscriber_client.execute(propfind) hrefs = propfind.response["document"] \ .findall("{DAV:}response/{DAV:}href") self.assertEquals(len(hrefs), 1, "expected 1 href in response instead of %d" % len(hrefs)) self.assertEquals(hrefs[0].text, parentColl, "the href must be the 'Calendar' parent coll.") acl_utility = utilities.TestCalendarACLUtility(self, self.client, self.createdRsrc) # 2. creation right added acl_utility.setupRights(subscriber_username, { "c": True }) self.subscriber_client.execute(propfind) hrefs = propfind.response["document"].findall("{DAV:}response/{DAV:}href") self.assertEquals(len(hrefs), 4, "expected 4 hrefs in response, got %d: %s" % (len(hrefs), ", ".join([ x.text for x in hrefs ]))) self.assertEquals(hrefs[0].text, parentColl, "the first href is not a 'Calendar' parent coll.") resourceHrefs = { resource: False, "%s.xml" % resource[:-1]: False, "%s.ics" % resource[:-1]: False } for href in hrefs[1:]: self.assertTrue(resourceHrefs.has_key(href.text), "received unexpected href: %s" % href.text) self.assertFalse(resourceHrefs[href.text], "href was returned more than once: %s" % href.text) resourceHrefs[href.text] = True acl_utility.setupRights(subscriber_username) # 3. creation right added for "default user" # subscriber_username expected to have access, but not "anonymous" acl_utility.setupRights("<default>", { "c": True }) self.subscriber_client.execute(propfind) hrefs = propfind.response["document"] \ .findall("{DAV:}response/{DAV:}href") self.assertEquals(len(hrefs), 4, "expected 4 hrefs in response, got %d: %s" % (len(hrefs), ", ".join([ x.text for x in hrefs ]))) self.assertEquals(hrefs[0].text, parentColl, "the first href is not a 'Calendar' parent coll.") resourceHrefs = { resource: False, "%s.xml" % resource[:-1]: False, "%s.ics" % resource[:-1]: False } for href in hrefs[1:]: self.assertTrue(resourceHrefs.has_key(href.text), "received unexpected href: %s" % href.text) self.assertFalse(resourceHrefs[href.text], "href was returned more than once: %s" % href.text) resourceHrefs[href.text] = True anonParentColl = '/SOGo/dav/public/%s/Calendar/' % username anon_propfind = webdavlib.WebDAVPROPFIND(anonParentColl, [ "displayname" ], 1) self.anon_client.execute(anon_propfind) hrefs = anon_propfind.response["document"] \ .findall("{DAV:}response/{DAV:}href") self.assertEquals(len(hrefs), 1, "expected only 1 href in response") self.assertEquals(hrefs[0].text, anonParentColl, "the first href is not a 'Calendar' parent coll.") acl_utility.setupRights("<default>", {}) # 4. creation right added for "anonymous" # "anonymous" expected to have access, but not subscriber_username acl_utility.setupRights("anonymous", { "c": True }) self.anon_client.execute(anon_propfind) hrefs = anon_propfind.response["document"] \ .findall("{DAV:}response/{DAV:}href") self.assertEquals(len(hrefs), 4, "expected 4 hrefs in response, got %d: %s" % (len(hrefs), ", ".join([ x.text for x in hrefs ]))) self.assertEquals(hrefs[0].text, anonParentColl, "the first href is not a 'Calendar' parent coll.") anonResource = '%stest-dav-acl/' % anonParentColl resourceHrefs = { anonResource: False, "%s.xml" % anonResource[:-1]: False, "%s.ics" % anonResource[:-1]: False } for href in hrefs[1:]: self.assertTrue(resourceHrefs.has_key(href.text), "received unexpected href: %s" % href.text) self.assertFalse(resourceHrefs[href.text], "href was returned more than once: %s" % href.text) resourceHrefs[href.text] = True self.subscriber_client.execute(propfind) hrefs = propfind.response["document"] \ .findall("{DAV:}response/{DAV:}href") self.assertEquals(len(hrefs), 1, "expected only 1 href in response") self.assertEquals(hrefs[0].text, parentColl, "the first href is not a 'Calendar' parent coll.") def testCollectionAccessSuperUser(self): # super user accessing (non-)shared res from nu parentColl = '/SOGo/dav/%s/Calendar/' % subscriber_username self.createdRsrc = '%stest-dav-acl/' % parentColl for rsrc in [ 'personal', 'test-dav-acl' ]: resource = '%s%s/' % (parentColl, rsrc) mkcol = webdavlib.WebDAVMKCOL(resource) self.superuser_client.execute(mkcol) acl_utility = utilities.TestCalendarACLUtility(self, self.subscriber_client, resource) acl_utility.setupRights(username, {}) propfind = webdavlib.WebDAVPROPFIND(parentColl, [ "displayname" ], 1) self.subscriber_client.execute(propfind) hrefs = [x.text \ for x in propfind.response["document"] \ .findall("{DAV:}response/{DAV:}href")] self.assertTrue(len(hrefs) > 2, "expected at least 3 hrefs in response") self.assertEquals(hrefs[0], parentColl, "the href must be the 'Calendar' parent coll.") for rsrc in [ 'personal', 'test-dav-acl' ]: resource = '%s%s/' % (parentColl, rsrc) self.assertTrue(hrefs.index(resource) > -1, "resource '%s' not returned" % resource) if __name__ == "__main__": sogotests.runTests()
gpl-2.0
jeroendierckx/Camelot
camelot/core/utils.py
1
9051
# ============================================================================ # # Copyright (C) 2007-2012 Conceptive Engineering bvba. All rights reserved. # www.conceptive.be / [email protected] # # This file is part of the Camelot Library. # # This file may be used under the terms of the GNU General Public # License version 2.0 as published by the Free Software Foundation # and appearing in the file license.txt included in the packaging of # this file. Please review this information to ensure GNU # General Public Licensing requirements will be met. # # If you are unsure which license is appropriate for your use, please # visit www.python-camelot.com or contact [email protected] # # This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE # WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # # For use of this library in commercial applications, please contact # [email protected] # # ============================================================================ """Utility functions""" from PyQt4 import QtGui from PyQt4 import QtCore import logging logger = logging.getLogger('camelot.core.utils') def is_deleted_pyqt( qobj ): """ :param qobj: a :class:`QtCore.QObject` :return: :keyword:`True` if the qobj was deleted, :keyword:`False` otherwise """ import sip return sip.isdeleted( qobj ) def is_deleted_pyside( qobj ): """ :param qobj: a :class:`QtCore.QObject` :return: :keyword:`True` if the qobj was deleted, :keyword:`False` otherwise """ return False if hasattr(QtCore, 'PYQT_VERSION_STR'): pyqt = True is_deleted = is_deleted_pyqt else: pyqt = False is_deleted = is_deleted_pyside # try to activate the PySide backend of matplotlib # http://www.scipy.org/Cookbook/Matplotlib/PySide try: import matplotlib matplotlib.rcParams['backend.qt4'] = 'PySide' except: pass def create_constant_function(constant): return lambda:constant class CollectionGetterFromObjectGetter(object): """Convert an object getter to a collection getter. The resulting class is callable and will make sure object_getter is only called once, even if collection getter is called multiple times. """ def __init__(self, object_getter): """:param object_getter: a function that returns the object to be put in the collection. """ self._object_getter = object_getter self._collection = None def __call__(self): if not self._collection: self._collection = [self._object_getter()] return self._collection """ A Note on GUI Types Because QVariant is part of the QtCore library, it cannot provide conversion functions to data types defined in QtGui, such as QColor, QImage, and QPixmap. In other words, there is no toColor() function. Instead, you can use the QVariant.value() or the qVariantValue() template function. For example: QVariant variant; ... QColor color = variant.value<QColor>(); The inverse conversion (e.g., from QColor to QVariant) is automatic for all data types supported by QVariant, including GUI-related types: QColor color = palette().background().color(); QVariant variant = color; """ def variant_to_pyobject(qvariant=None): """Try to convert a QVariant to a python object as good as possible""" if not pyqt: return qvariant import datetime if not qvariant: return None if qvariant.isNull(): return None type = qvariant.type() if type == QtCore.QVariant.String: value = unicode(qvariant.toString()) elif type == QtCore.QVariant.Date: value = qvariant.toDate() value = datetime.date(year=value.year(), month=value.month(), day=value.day()) elif type == QtCore.QVariant.Int: value = int(qvariant.toInt()[0]) elif type == QtCore.QVariant.LongLong: value = int(qvariant.toLongLong()[0]) elif type == QtCore.QVariant.Double: value = float(qvariant.toDouble()[0]) elif type == QtCore.QVariant.Bool: value = bool(qvariant.toBool()) elif type == QtCore.QVariant.Time: value = qvariant.toTime() value = datetime.time(hour = value.hour(), minute = value.minute(), second = value.second()) elif type == QtCore.QVariant.DateTime: value = qvariant.toDateTime() value = value.toPyDateTime () elif type == QtCore.QVariant.Color: value = QtGui.QColor(qvariant) else: value = qvariant.toPyObject() return value # # Global dictionary containing all user defined translations in the # current locale # _translations_ = {} # # Encoding used when transferring translation strings from # python to qt # _encoding=QtCore.QCoreApplication.UnicodeUTF8 def set_translation(source, value): """Store a tranlation in the global translation dictionary""" _translations_[source] = value def load_translations(): """Fill the global dictionary of translations with all data from the database, to be able to do fast gui thread lookups of translations""" language = unicode(QtCore.QLocale().name()) from sqlalchemy import sql from camelot.model.i18n import Translation # only load translations when the camelot model is active if not hasattr(Translation, 'query'): return query = sql.select( [Translation.source, Translation.value], whereclause = sql.and_(Translation.language==language, Translation.value!=None, Translation.value!=u'') ) for source, value in Translation.query.session.execute(query): _translations_[source] = value def _qtranslate(string_to_translate): """Translate a string using the QCoreApplication translation framework :param string_to_translate: a unicode string :return: the translated unicode string if it was possible to translate """ return unicode(QtCore.QCoreApplication.translate('', string_to_translate.encode('utf-8'), encoding=_encoding)) def ugettext(string_to_translate): """Translate the string_to_translate to the language of the current locale. This is a two step process. First the function will try to get the translation out of the Translation entity, if this is not successfull, the function will ask QCoreApplication to translate string_to_translate (which tries to get the translation from the .qm files)""" assert isinstance(string_to_translate, basestring) result = _translations_.get(string_to_translate, None) if not result: result = _qtranslate( string_to_translate ) #print string_to_translate, result # try one more time with string_to_translate capitalized if result is string_to_translate: result2 = _qtranslate( string_to_translate.capitalize() ) if result2 is not string_to_translate.capitalize(): result = result2 return result def dgettext(domain, message): """Like ugettext but look the message up in the specified domain. This uses the Translation table. """ assert isinstance(message, basestring) from camelot.model.i18n import Translation from sqlalchemy import sql query = sql.select( [Translation.value], whereclause = sql.and_(Translation.language.like('%s%%'%domain), Translation.source==message) ).limit(1) for translation in Translation.query.session.execute(query): return translation[0] return message class ugettext_lazy(object): """Like :function:`ugettext`, but delays the translation until the string is shown to the user. This makes it possible for the user to translate the string. """ def __init__(self, string_to_translate): assert isinstance(string_to_translate, basestring) self._string_to_translate = string_to_translate def __str__(self): return ugettext(self._string_to_translate) def __unicode__(self): return ugettext(self._string_to_translate) def __eq__(self, other_string): if isinstance(other_string, basestring): return other_string == self._string_to_translate if isinstance(other_string, ugettext_lazy): return other_string._string_to_translate == self._string_to_translate return False def __ne__(self, other_string): return not self.__eq__( other_string ) def __repr__(self): return u"_('%s')"%self._string_to_translate def format_float(value, precision=3): return QtCore.QString("%L1").arg(float(value), 0, 'f', precision)
gpl-2.0
triveous/LearnFlask
flask/lib/python2.7/site-packages/pip/_vendor/html5lib/treeadapters/sax.py
1835
1661
from __future__ import absolute_import, division, unicode_literals from xml.sax.xmlreader import AttributesNSImpl from ..constants import adjustForeignAttributes, unadjustForeignAttributes prefix_mapping = {} for prefix, localName, namespace in adjustForeignAttributes.values(): if prefix is not None: prefix_mapping[prefix] = namespace def to_sax(walker, handler): """Call SAX-like content handler based on treewalker walker""" handler.startDocument() for prefix, namespace in prefix_mapping.items(): handler.startPrefixMapping(prefix, namespace) for token in walker: type = token["type"] if type == "Doctype": continue elif type in ("StartTag", "EmptyTag"): attrs = AttributesNSImpl(token["data"], unadjustForeignAttributes) handler.startElementNS((token["namespace"], token["name"]), token["name"], attrs) if type == "EmptyTag": handler.endElementNS((token["namespace"], token["name"]), token["name"]) elif type == "EndTag": handler.endElementNS((token["namespace"], token["name"]), token["name"]) elif type in ("Characters", "SpaceCharacters"): handler.characters(token["data"]) elif type == "Comment": pass else: assert False, "Unknown token type" for prefix, namespace in prefix_mapping.items(): handler.endPrefixMapping(prefix) handler.endDocument()
apache-2.0
bjss/BJSS_liveobs_selenium
liveobs_ui/selectors/desktop/nursing_shift_change_selectors.py
2
1670
""" Selectors for Nursing Shift Change Wizard """ from selenium.webdriver.common.by import By WIZARD_STAGE_CONTAINER = ( By.CSS_SELECTOR, '.modal .oe_form_field_status' ) WIZARD_STAGE = ( By.CSS_SELECTOR, '.modal .oe_form_field_status .label' ) WIZARD_BUTTON = ( By.CSS_SELECTOR, '.modal .oe_form header .oe_form_button' ) WIZARD_START_BUTTON = ( By.XPATH, '//header/button/span[contains(text(), \'Start\')]' ) WIZARD_DEALLOCATE_BUTTON = ( By.XPATH, '//header/button/span[contains(text(), \'Deallocate\')]' ) WIZARD_ROLL_CALL_BUTTON = ( By.XPATH, '//header/button/span[contains(text(), \'Select\')]' ) WIZARD_ALLOCATION_BUTTON = ( By.XPATH, '//header/button/span[contains(text(), \'Confirm\')]' ) WIZARD_VISIBLE_BUTTON = ( By.CSS_SELECTOR, '.modal .oe_form header .oe_form_button:not(.oe_form_invisible)' ) MODAL_TABLE = ( By.CSS_SELECTOR, '.modal .oe_form_sheet .oe_form_field:not(.oe_form_invisible) ' '.oe_list_content' ) MODAL_TABLE_ROW = ( By.CSS_SELECTOR, '.modal .oe_form_sheet .oe_form_field:not(.oe_form_invisible) ' '.oe_list_content tbody tr' ) DEALLOCATION_TABLE_BED_COL = ( By.CSS_SELECTOR, 'td[data-field=name]' ) DEALLOCATION_TABLE_WM_COL = ( By.CSS_SELECTOR, 'td[data-field=assigned_wm_ids]' ) DEALLOCATION_TABLE_NURSE_COL = ( By.CSS_SELECTOR, 'td[data-field=assigned_nurse_ids]' ) DEALLOCATION_TABLE_HCA_COL = ( By.CSS_SELECTOR, 'td[data-field=assigned_hca_ids]' ) ALLOCATE_WIZARD_BUTTON = ( By.CSS_SELECTOR, 'td button[title=Allocate]' ) ALLOCATE_TABLE_BED_COL = ( By.CSS_SELECTOR, 'td[data-field=location_id]' )
gpl-3.0
ttsubo/ryu
ryu/contrib/ovs/reconnect.py
54
23121
# Copyright (c) 2010, 2011, 2012 Nicira, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import ovs.vlog import ovs.util # Values returned by Reconnect.run() CONNECT = 'connect' DISCONNECT = 'disconnect' PROBE = 'probe' EOF = ovs.util.EOF vlog = ovs.vlog.Vlog("reconnect") class Reconnect(object): """A finite-state machine for connecting and reconnecting to a network resource with exponential backoff. It also provides optional support for detecting a connection on which the peer is no longer responding. The library does not implement anything networking related, only an FSM for networking code to use. Many Reconnect methods take a "now" argument. This makes testing easier since there is no hidden state. When not testing, just pass the return value of ovs.time.msec(). (Perhaps this design should be revisited later.)""" class Void(object): name = "VOID" is_connected = False @staticmethod def deadline(fsm): return None @staticmethod def run(fsm, now): return None class Listening(object): name = "LISTENING" is_connected = False @staticmethod def deadline(fsm): return None @staticmethod def run(fsm, now): return None class Backoff(object): name = "BACKOFF" is_connected = False @staticmethod def deadline(fsm): return fsm.state_entered + fsm.backoff @staticmethod def run(fsm, now): return CONNECT class ConnectInProgress(object): name = "CONNECTING" is_connected = False @staticmethod def deadline(fsm): return fsm.state_entered + max(1000, fsm.backoff) @staticmethod def run(fsm, now): return DISCONNECT class Active(object): name = "ACTIVE" is_connected = True @staticmethod def deadline(fsm): if fsm.probe_interval: base = max(fsm.last_activity, fsm.state_entered) return base + fsm.probe_interval return None @staticmethod def run(fsm, now): vlog.dbg("%s: idle %d ms, sending inactivity probe" % (fsm.name, now - max(fsm.last_activity, fsm.state_entered))) fsm._transition(now, Reconnect.Idle) return PROBE class Idle(object): name = "IDLE" is_connected = True @staticmethod def deadline(fsm): if fsm.probe_interval: return fsm.state_entered + fsm.probe_interval return None @staticmethod def run(fsm, now): vlog.err("%s: no response to inactivity probe after %.3g " "seconds, disconnecting" % (fsm.name, (now - fsm.state_entered) / 1000.0)) return DISCONNECT class Reconnect(object): name = "RECONNECT" is_connected = False @staticmethod def deadline(fsm): return fsm.state_entered @staticmethod def run(fsm, now): return DISCONNECT def __init__(self, now): """Creates and returns a new reconnect FSM with default settings. The FSM is initially disabled. The caller will likely want to call self.enable() and self.set_name() on the returned object.""" self.name = "void" self.min_backoff = 1000 self.max_backoff = 8000 self.probe_interval = 5000 self.passive = False self.info_level = vlog.info self.state = Reconnect.Void self.state_entered = now self.backoff = 0 self.last_activity = now self.last_connected = None self.last_disconnected = None self.max_tries = None self.creation_time = now self.n_attempted_connections = 0 self.n_successful_connections = 0 self.total_connected_duration = 0 self.seqno = 0 def set_quiet(self, quiet): """If 'quiet' is true, this object will log informational messages at debug level, by default keeping them out of log files. This is appropriate if the connection is one that is expected to be short-lived, so that the log messages are merely distracting. If 'quiet' is false, this object logs informational messages at info level. This is the default. This setting has no effect on the log level of debugging, warning, or error messages.""" if quiet: self.info_level = vlog.dbg else: self.info_level = vlog.info def get_name(self): return self.name def set_name(self, name): """Sets this object's name to 'name'. If 'name' is None, then "void" is used instead. The name is used in log messages.""" if name is None: self.name = "void" else: self.name = name def get_min_backoff(self): """Return the minimum number of milliseconds to back off between consecutive connection attempts. The default is 1000 ms.""" return self.min_backoff def get_max_backoff(self): """Return the maximum number of milliseconds to back off between consecutive connection attempts. The default is 8000 ms.""" return self.max_backoff def get_probe_interval(self): """Returns the "probe interval" in milliseconds. If this is zero, it disables the connection keepalive feature. If it is nonzero, then if the interval passes while the FSM is connected and without self.activity() being called, self.run() returns ovs.reconnect.PROBE. If the interval passes again without self.activity() being called, self.run() returns ovs.reconnect.DISCONNECT.""" return self.probe_interval def set_max_tries(self, max_tries): """Limits the maximum number of times that this object will ask the client to try to reconnect to 'max_tries'. None (the default) means an unlimited number of tries. After the number of tries has expired, the FSM will disable itself instead of backing off and retrying.""" self.max_tries = max_tries def get_max_tries(self): """Returns the current remaining number of connection attempts, None if the number is unlimited.""" return self.max_tries def set_backoff(self, min_backoff, max_backoff): """Configures the backoff parameters for this FSM. 'min_backoff' is the minimum number of milliseconds, and 'max_backoff' is the maximum, between connection attempts. 'min_backoff' must be at least 1000, and 'max_backoff' must be greater than or equal to 'min_backoff'.""" self.min_backoff = max(min_backoff, 1000) if self.max_backoff: self.max_backoff = max(max_backoff, 1000) else: self.max_backoff = 8000 if self.min_backoff > self.max_backoff: self.max_backoff = self.min_backoff if (self.state == Reconnect.Backoff and self.backoff > self.max_backoff): self.backoff = self.max_backoff def set_probe_interval(self, probe_interval): """Sets the "probe interval" to 'probe_interval', in milliseconds. If this is zero, it disables the connection keepalive feature. If it is nonzero, then if the interval passes while this FSM is connected and without self.activity() being called, self.run() returns ovs.reconnect.PROBE. If the interval passes again without self.activity() being called, self.run() returns ovs.reconnect.DISCONNECT. If 'probe_interval' is nonzero, then it will be forced to a value of at least 1000 ms.""" if probe_interval: self.probe_interval = max(1000, probe_interval) else: self.probe_interval = 0 def is_passive(self): """Returns true if 'fsm' is in passive mode, false if 'fsm' is in active mode (the default).""" return self.passive def set_passive(self, passive, now): """Configures this FSM for active or passive mode. In active mode (the default), the FSM is attempting to connect to a remote host. In passive mode, the FSM is listening for connections from a remote host.""" if self.passive != passive: self.passive = passive if ((passive and self.state in (Reconnect.ConnectInProgress, Reconnect.Reconnect)) or (not passive and self.state == Reconnect.Listening and self.__may_retry())): self._transition(now, Reconnect.Backoff) self.backoff = 0 def is_enabled(self): """Returns true if this FSM has been enabled with self.enable(). Calling another function that indicates a change in connection state, such as self.disconnected() or self.force_reconnect(), will also enable a reconnect FSM.""" return self.state != Reconnect.Void def enable(self, now): """If this FSM is disabled (the default for newly created FSMs), enables it, so that the next call to reconnect_run() for 'fsm' will return ovs.reconnect.CONNECT. If this FSM is not disabled, this function has no effect.""" if self.state == Reconnect.Void and self.__may_retry(): self._transition(now, Reconnect.Backoff) self.backoff = 0 def disable(self, now): """Disables this FSM. Until 'fsm' is enabled again, self.run() will always return 0.""" if self.state != Reconnect.Void: self._transition(now, Reconnect.Void) def force_reconnect(self, now): """If this FSM is enabled and currently connected (or attempting to connect), forces self.run() to return ovs.reconnect.DISCONNECT the next time it is called, which should cause the client to drop the connection (or attempt), back off, and then reconnect.""" if self.state in (Reconnect.ConnectInProgress, Reconnect.Active, Reconnect.Idle): self._transition(now, Reconnect.Reconnect) def disconnected(self, now, error): """Tell this FSM that the connection dropped or that a connection attempt failed. 'error' specifies the reason: a positive value represents an errno value, EOF indicates that the connection was closed by the peer (e.g. read() returned 0), and 0 indicates no specific error. The FSM will back off, then reconnect.""" if self.state not in (Reconnect.Backoff, Reconnect.Void): # Report what happened if self.state in (Reconnect.Active, Reconnect.Idle): if error > 0: vlog.warn("%s: connection dropped (%s)" % (self.name, os.strerror(error))) elif error == EOF: self.info_level("%s: connection closed by peer" % self.name) else: self.info_level("%s: connection dropped" % self.name) elif self.state == Reconnect.Listening: if error > 0: vlog.warn("%s: error listening for connections (%s)" % (self.name, os.strerror(error))) else: self.info_level("%s: error listening for connections" % self.name) else: if self.passive: type_ = "listen" else: type_ = "connection" if error > 0: vlog.warn("%s: %s attempt failed (%s)" % (self.name, type_, os.strerror(error))) else: self.info_level("%s: %s attempt timed out" % (self.name, type_)) if (self.state in (Reconnect.Active, Reconnect.Idle)): self.last_disconnected = now # Back off if (self.state in (Reconnect.Active, Reconnect.Idle) and (self.last_activity - self.last_connected >= self.backoff or self.passive)): if self.passive: self.backoff = 0 else: self.backoff = self.min_backoff else: if self.backoff < self.min_backoff: self.backoff = self.min_backoff elif self.backoff >= self.max_backoff / 2: self.backoff = self.max_backoff else: self.backoff *= 2 if self.passive: self.info_level("%s: waiting %.3g seconds before trying " "to listen again" % (self.name, self.backoff / 1000.0)) else: self.info_level("%s: waiting %.3g seconds before reconnect" % (self.name, self.backoff / 1000.0)) if self.__may_retry(): self._transition(now, Reconnect.Backoff) else: self._transition(now, Reconnect.Void) def connecting(self, now): """Tell this FSM that a connection or listening attempt is in progress. The FSM will start a timer, after which the connection or listening attempt will be aborted (by returning ovs.reconnect.DISCONNECT from self.run()).""" if self.state != Reconnect.ConnectInProgress: if self.passive: self.info_level("%s: listening..." % self.name) else: self.info_level("%s: connecting..." % self.name) self._transition(now, Reconnect.ConnectInProgress) def listening(self, now): """Tell this FSM that the client is listening for connection attempts. This state last indefinitely until the client reports some change. The natural progression from this state is for the client to report that a connection has been accepted or is in progress of being accepted, by calling self.connecting() or self.connected(). The client may also report that listening failed (e.g. accept() returned an unexpected error such as ENOMEM) by calling self.listen_error(), in which case the FSM will back off and eventually return ovs.reconnect.CONNECT from self.run() to tell the client to try listening again.""" if self.state != Reconnect.Listening: self.info_level("%s: listening..." % self.name) self._transition(now, Reconnect.Listening) def listen_error(self, now, error): """Tell this FSM that the client's attempt to accept a connection failed (e.g. accept() returned an unexpected error such as ENOMEM). If the FSM is currently listening (self.listening() was called), it will back off and eventually return ovs.reconnect.CONNECT from self.run() to tell the client to try listening again. If there is an active connection, this will be delayed until that connection drops.""" if self.state == Reconnect.Listening: self.disconnected(now, error) def connected(self, now): """Tell this FSM that the connection was successful. The FSM will start the probe interval timer, which is reset by self.activity(). If the timer expires, a probe will be sent (by returning ovs.reconnect.PROBE from self.run(). If the timer expires again without being reset, the connection will be aborted (by returning ovs.reconnect.DISCONNECT from self.run().""" if not self.state.is_connected: self.connecting(now) self.info_level("%s: connected" % self.name) self._transition(now, Reconnect.Active) self.last_connected = now def connect_failed(self, now, error): """Tell this FSM that the connection attempt failed. The FSM will back off and attempt to reconnect.""" self.connecting(now) self.disconnected(now, error) def activity(self, now): """Tell this FSM that some activity occurred on the connection. This resets the probe interval timer, so that the connection is known not to be idle.""" if self.state != Reconnect.Active: self._transition(now, Reconnect.Active) self.last_activity = now def _transition(self, now, state): if self.state == Reconnect.ConnectInProgress: self.n_attempted_connections += 1 if state == Reconnect.Active: self.n_successful_connections += 1 connected_before = self.state.is_connected connected_now = state.is_connected if connected_before != connected_now: if connected_before: self.total_connected_duration += now - self.last_connected self.seqno += 1 vlog.dbg("%s: entering %s" % (self.name, state.name)) self.state = state self.state_entered = now def run(self, now): """Assesses whether any action should be taken on this FSM. The return value is one of: - None: The client need not take any action. - Active client, ovs.reconnect.CONNECT: The client should start a connection attempt and indicate this by calling self.connecting(). If the connection attempt has definitely succeeded, it should call self.connected(). If the connection attempt has definitely failed, it should call self.connect_failed(). The FSM is smart enough to back off correctly after successful connections that quickly abort, so it is OK to call self.connected() after a low-level successful connection (e.g. connect()) even if the connection might soon abort due to a failure at a high-level (e.g. SSL negotiation failure). - Passive client, ovs.reconnect.CONNECT: The client should try to listen for a connection, if it is not already listening. It should call self.listening() if successful, otherwise self.connecting() or reconnected_connect_failed() if the attempt is in progress or definitely failed, respectively. A listening passive client should constantly attempt to accept a new connection and report an accepted connection with self.connected(). - ovs.reconnect.DISCONNECT: The client should abort the current connection or connection attempt or listen attempt and call self.disconnected() or self.connect_failed() to indicate it. - ovs.reconnect.PROBE: The client should send some kind of request to the peer that will elicit a response, to ensure that the connection is indeed in working order. (This will only be returned if the "probe interval" is nonzero--see self.set_probe_interval()).""" deadline = self.state.deadline(self) if deadline is not None and now >= deadline: return self.state.run(self, now) else: return None def wait(self, poller, now): """Causes the next call to poller.block() to wake up when self.run() should be called.""" timeout = self.timeout(now) if timeout >= 0: poller.timer_wait(timeout) def timeout(self, now): """Returns the number of milliseconds after which self.run() should be called if nothing else notable happens in the meantime, or None if this is currently unnecessary.""" deadline = self.state.deadline(self) if deadline is not None: remaining = deadline - now return max(0, remaining) else: return None def is_connected(self): """Returns True if this FSM is currently believed to be connected, that is, if self.connected() was called more recently than any call to self.connect_failed() or self.disconnected() or self.disable(), and False otherwise.""" return self.state.is_connected def get_last_connect_elapsed(self, now): """Returns the number of milliseconds since 'fsm' was last connected to its peer. Returns None if never connected.""" if self.last_connected: return now - self.last_connected else: return None def get_last_disconnect_elapsed(self, now): """Returns the number of milliseconds since 'fsm' was last disconnected from its peer. Returns None if never disconnected.""" if self.last_disconnected: return now - self.last_disconnected else: return None def get_stats(self, now): class Stats(object): pass stats = Stats() stats.creation_time = self.creation_time stats.last_connected = self.last_connected stats.last_disconnected = self.last_disconnected stats.last_activity = self.last_activity stats.backoff = self.backoff stats.seqno = self.seqno stats.is_connected = self.is_connected() stats.msec_since_connect = self.get_last_connect_elapsed(now) stats.msec_since_disconnect = self.get_last_disconnect_elapsed(now) stats.total_connected_duration = self.total_connected_duration if self.is_connected(): stats.total_connected_duration += ( self.get_last_connect_elapsed(now)) stats.n_attempted_connections = self.n_attempted_connections stats.n_successful_connections = self.n_successful_connections stats.state = self.state.name stats.state_elapsed = now - self.state_entered return stats def __may_retry(self): if self.max_tries is None: return True elif self.max_tries > 0: self.max_tries -= 1 return True else: return False
apache-2.0
BartoszCichecki/onlinepython
onlinepython/pypy-2.4.0-win32/lib-python/2.7/lib2to3/tests/pytree_idempotency.py
129
2385
#!/usr/bin/env python # Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Main program for testing the infrastructure.""" __author__ = "Guido van Rossum <[email protected]>" # Support imports (need to be imported first) from . import support # Python imports import os import sys import logging # Local imports from .. import pytree import pgen2 from pgen2 import driver logging.basicConfig() def main(): gr = driver.load_grammar("Grammar.txt") dr = driver.Driver(gr, convert=pytree.convert) fn = "example.py" tree = dr.parse_file(fn, debug=True) if not diff(fn, tree): print "No diffs." if not sys.argv[1:]: return # Pass a dummy argument to run the complete test suite below problems = [] # Process every imported module for name in sys.modules: mod = sys.modules[name] if mod is None or not hasattr(mod, "__file__"): continue fn = mod.__file__ if fn.endswith(".pyc"): fn = fn[:-1] if not fn.endswith(".py"): continue print >>sys.stderr, "Parsing", fn tree = dr.parse_file(fn, debug=True) if diff(fn, tree): problems.append(fn) # Process every single module on sys.path (but not in packages) for dir in sys.path: try: names = os.listdir(dir) except os.error: continue print >>sys.stderr, "Scanning", dir, "..." for name in names: if not name.endswith(".py"): continue print >>sys.stderr, "Parsing", name fn = os.path.join(dir, name) try: tree = dr.parse_file(fn, debug=True) except pgen2.parse.ParseError, err: print "ParseError:", err else: if diff(fn, tree): problems.append(fn) # Show summary of problem files if not problems: print "No problems. Congratulations!" else: print "Problems in following files:" for fn in problems: print "***", fn def diff(fn, tree): f = open("@", "w") try: f.write(str(tree)) finally: f.close() try: return os.system("diff -u %s @" % fn) finally: os.remove("@") if __name__ == "__main__": main()
gpl-2.0
anakinsolo/backend
Lib/site-packages/pip/_vendor/progress/__init__.py
916
3023
# Copyright (c) 2012 Giorgos Verigakis <[email protected]> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. from __future__ import division from collections import deque from datetime import timedelta from math import ceil from sys import stderr from time import time __version__ = '1.2' class Infinite(object): file = stderr sma_window = 10 def __init__(self, *args, **kwargs): self.index = 0 self.start_ts = time() self._ts = self.start_ts self._dt = deque(maxlen=self.sma_window) for key, val in kwargs.items(): setattr(self, key, val) def __getitem__(self, key): if key.startswith('_'): return None return getattr(self, key, None) @property def avg(self): return sum(self._dt) / len(self._dt) if self._dt else 0 @property def elapsed(self): return int(time() - self.start_ts) @property def elapsed_td(self): return timedelta(seconds=self.elapsed) def update(self): pass def start(self): pass def finish(self): pass def next(self, n=1): if n > 0: now = time() dt = (now - self._ts) / n self._dt.append(dt) self._ts = now self.index = self.index + n self.update() def iter(self, it): for x in it: yield x self.next() self.finish() class Progress(Infinite): def __init__(self, *args, **kwargs): super(Progress, self).__init__(*args, **kwargs) self.max = kwargs.get('max', 100) @property def eta(self): return int(ceil(self.avg * self.remaining)) @property def eta_td(self): return timedelta(seconds=self.eta) @property def percent(self): return self.progress * 100 @property def progress(self): return min(1, self.index / self.max) @property def remaining(self): return max(self.max - self.index, 0) def start(self): self.update() def goto(self, index): incr = index - self.index self.next(incr) def iter(self, it): try: self.max = len(it) except TypeError: pass for x in it: yield x self.next() self.finish()
mit
luci/luci-py
client/third_party/oauth2client/_pycrypto_crypt.py
6
4295
# Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """pyCrypto Crypto-related routines for oauth2client.""" from Crypto.PublicKey import RSA from Crypto.Hash import SHA256 from Crypto.Signature import PKCS1_v1_5 from Crypto.Util.asn1 import DerSequence from oauth2client._helpers import _parse_pem_key from oauth2client._helpers import _to_bytes from oauth2client._helpers import _urlsafe_b64decode class PyCryptoVerifier(object): """Verifies the signature on a message.""" def __init__(self, pubkey): """Constructor. Args: pubkey: OpenSSL.crypto.PKey (or equiv), The public key to verify with. """ self._pubkey = pubkey def verify(self, message, signature): """Verifies a message against a signature. Args: message: string or bytes, The message to verify. If string, will be encoded to bytes as utf-8. signature: string or bytes, The signature on the message. Returns: True if message was signed by the private key associated with the public key that this object was constructed with. """ message = _to_bytes(message, encoding='utf-8') return PKCS1_v1_5.new(self._pubkey).verify( SHA256.new(message), signature) @staticmethod def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. """ if is_x509_cert: key_pem = _to_bytes(key_pem) pemLines = key_pem.replace(b' ', b'').split() certDer = _urlsafe_b64decode(b''.join(pemLines[1:-1])) certSeq = DerSequence() certSeq.decode(certDer) tbsSeq = DerSequence() tbsSeq.decode(certSeq[0]) pubkey = RSA.importKey(tbsSeq[6]) else: pubkey = RSA.importKey(key_pem) return PyCryptoVerifier(pubkey) class PyCryptoSigner(object): """Signs messages with a private key.""" def __init__(self, pkey): """Constructor. Args: pkey, OpenSSL.crypto.PKey (or equiv), The private key to sign with. """ self._key = pkey def sign(self, message): """Signs a message. Args: message: string, Message to be signed. Returns: string, The signature of the message for the given key. """ message = _to_bytes(message, encoding='utf-8') return PKCS1_v1_5.new(self._key).sign(SHA256.new(message)) @staticmethod def from_string(key, password='notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in PEM format. password: string, password for private key file. Unused for PEM files. Returns: Signer instance. Raises: NotImplementedError if the key isn't in PEM format. """ parsed_pem_key = _parse_pem_key(_to_bytes(key)) if parsed_pem_key: pkey = RSA.importKey(parsed_pem_key) else: raise NotImplementedError( 'PKCS12 format is not supported by the PyCrypto library. ' 'Try converting to a "PEM" ' '(openssl pkcs12 -in xxxxx.p12 -nodes -nocerts > ' 'privatekey.pem) ' 'or using PyOpenSSL if native code is an option.') return PyCryptoSigner(pkey)
apache-2.0
hhru/ansible
lib/ansible/module_utils/a10.py
322
4194
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete work. # # Copyright (c), Michael DeHaan <[email protected]>, 2012-2013 # 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. # # 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. AXAPI_PORT_PROTOCOLS = { 'tcp': 2, 'udp': 3, } AXAPI_VPORT_PROTOCOLS = { 'tcp': 2, 'udp': 3, 'fast-http': 9, 'http': 11, 'https': 12, } def a10_argument_spec(): return dict( host=dict(type='str', required=True), username=dict(type='str', aliases=['user', 'admin'], required=True), password=dict(type='str', aliases=['pass', 'pwd'], required=True, no_log=True), write_config=dict(type='bool', default=False) ) def axapi_failure(result): if 'response' in result and result['response'].get('status') == 'fail': return True return False def axapi_call(module, url, post=None): ''' Returns a datastructure based on the result of the API call ''' rsp, info = fetch_url(module, url, data=post) if not rsp or info['status'] >= 400: module.fail_json(msg="failed to connect (status code %s), error was %s" % (info['status'], info.get('msg', 'no error given'))) try: raw_data = rsp.read() data = json.loads(raw_data) except ValueError: # at least one API call (system.action.write_config) returns # XML even when JSON is requested, so do some minimal handling # here to prevent failing even when the call succeeded if 'status="ok"' in raw_data.lower(): data = {"response": {"status": "OK"}} else: data = {"response": {"status": "fail", "err": {"msg": raw_data}}} except: module.fail_json(msg="could not read the result from the host") finally: rsp.close() return data def axapi_authenticate(module, base_url, username, password): url = '%s&method=authenticate&username=%s&password=%s' % (base_url, username, password) result = axapi_call(module, url) if axapi_failure(result): return module.fail_json(msg=result['response']['err']['msg']) sessid = result['session_id'] return base_url + '&session_id=' + sessid def axapi_enabled_disabled(flag): ''' The axapi uses 0/1 integer values for flags, rather than strings or booleans, so convert the given flag to a 0 or 1. For now, params are specified as strings only so thats what we check. ''' if flag == 'enabled': return 1 else: return 0 def axapi_get_port_protocol(protocol): return AXAPI_PORT_PROTOCOLS.get(protocol.lower(), None) def axapi_get_vport_protocol(protocol): return AXAPI_VPORT_PROTOCOLS.get(protocol.lower(), None)
gpl-3.0
lancezlin/pylearn2
pylearn2/costs/gated_autoencoder.py
39
5793
""" Definitions of the cost for the gated-autoencoder. """ from pylearn2.costs.cost import Cost, DefaultDataSpecsMixin from pylearn2.space import VectorSpace class SymmetricCost(DefaultDataSpecsMixin, Cost): """ Summary (Class representing the symmetric cost). Subclasses can define the type of data they will use. Mean reconstruction error is used for real valued data and cross-Entropy loss is used for binary. See Also -------- "Gradient-based learning of higher-order image features" """ @staticmethod def cost(x, y, rx, ry): """ Symmetric reconstruction cost. Parameters ---------- x : tensor_like Theano symbolic representing the first input minibatch. Assumed to be 2-tensors, with the first dimension indexing training examples and the second indexing data dimensions. y : tensor_like Theano symbolic representing the seconde input minibatch. Assumed to be 2-tensors, with the first dimension indexing training examples and the second indexing data dimensions. rx : tensor_like Reconstruction of the first minibatch by the model. ry: tensor_like Reconstruction of the second minibatch by the model. Returns ------- Cost: theano_like expression Representation of the cost """ raise NotImplementedError def expr(self, model, data, *args, **kwargs): """ Returns a theano expression for the cost function. Returns a symbolic expression for a cost function applied to the minibatch of data. Optionally, may return None. This represents that the cost function is intractable but may be optimized via the get_gradients method. Parameters ---------- model : a pylearn2 Model instance data : a batch in cost.get_data_specs() form kwargs : dict Optional extra arguments. Not used by the base class. """ self.get_data_specs(model)[0].validate(data) x, y = data input_space = model.get_input_space() if not isinstance(input_space.components[0], VectorSpace): conv = input_space.components[0] vec = VectorSpace(conv.get_total_dimension()) x = conv.format_as(x, vec) if not isinstance(input_space.components[1], VectorSpace): conv = input_space.components[1] vec = VectorSpace(conv.get_total_dimension()) y = conv.format_as(y, vec) rx, ry = model.reconstructXY((x, y)) return self.cost(x, y, rx, ry) class SymmetricMSRE(SymmetricCost): """ Summary (Symmetric cost for real valued data). See Also -------- "Gradient-based learning of higher-order image features" """ @staticmethod def cost(x, y, rx, ry): """ Summary (Definition of the cost). Mean squared reconstruction error. Parameters ---------- x : tensor_like Theano symbolic representing the first input minibatch. Assumed to be 2-tensors, with the first dimension indexing training examples and the second indexing data dimensions. y : tensor_like Theano symbolic representing the seconde input minibatch. Assumed to be 2-tensors, with the first dimension indexing training examples and the second indexing data dimensions. rx : tensor_like Reconstruction of the first minibatch by the model. ry: tensor_like Reconstruction of the second minibatch by the model. Returns ------- Cost: theano_like expression Representation of the cost Notes ----- Symmetric reconstruction cost as defined by Memisevic in: "Gradient-based learning of higher-order image features". This function only works with real valued data. """ return ( ((0.5*((x - rx)**2)) + (0.5*((y - ry)**2)))).sum(axis=1).mean() class NormalizedSymmetricMSRE(SymmetricCost): """ Summary (Normalized Symmetric cost for real valued data). Notes ----- Value used to observe the percentage of reconstruction. """ @staticmethod def cost(x, y, rx, ry): """ Summary (Definition of the cost). Normalized Mean squared reconstruction error. Values between 0 and 1. Parameters ---------- x : tensor_like Theano symbolic representing the first input minibatch. Assumed to be 2-tensors, with the first dimension indexing training examples and the second indexing data dimensions. y : tensor_like Theano symbolic representing the seconde input minibatch. Assumed to be 2-tensors, with the first dimension indexing training examples and the second indexing data dimensions. rx : tensor_like Reconstruction of the first minibatch by the model. ry: tensor_like Reconstruction of the second minibatch by the model. Returns ------- Cost: theano_like expression Representation of the cost Notes ----- Do not use this function to train, only to monitor the average percentage of reconstruction achieved when training on real valued data. """ num = (((0.5*((x - rx)**2)) + (0.5*((y - ry)**2)))).sum(axis=1).mean() den = ((0.5*(x.norm(2, 1)**2)) + (0.5*(y.norm(2, 1)**2))).mean() return num/den
bsd-3-clause
sogelink/ansible
lib/ansible/module_utils/vyos.py
14
4939
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete work. # # (c) 2016 Red Hat Inc. # # 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. # # 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. # from ansible.module_utils._text import to_text from ansible.module_utils.basic import env_fallback, return_values from ansible.module_utils.network_common import to_list from ansible.module_utils.connection import exec_command _DEVICE_CONFIGS = {} vyos_provider_spec = { 'host': dict(), 'port': dict(type='int'), 'username': dict(fallback=(env_fallback, ['ANSIBLE_NET_USERNAME'])), 'password': dict(fallback=(env_fallback, ['ANSIBLE_NET_PASSWORD']), no_log=True), 'ssh_keyfile': dict(fallback=(env_fallback, ['ANSIBLE_NET_SSH_KEYFILE']), type='path'), 'timeout': dict(type='int'), } vyos_argument_spec = { 'provider': dict(type='dict', options=vyos_provider_spec), } vyos_top_spec = { 'host': dict(removed_in_version=2.9), 'port': dict(removed_in_version=2.9, type='int'), 'username': dict(removed_in_version=2.9), 'password': dict(removed_in_version=2.9, no_log=True), 'ssh_keyfile': dict(removed_in_version=2.9, type='path'), 'timeout': dict(removed_in_version=2.9, type='int'), } vyos_argument_spec.update(vyos_top_spec) def get_provider_argspec(): return vyos_provider_spec def get_config(module, target='commands'): cmd = ' '.join(['show configuration', target]) try: return _DEVICE_CONFIGS[cmd] except KeyError: rc, out, err = exec_command(module, cmd) if rc != 0: module.fail_json(msg='unable to retrieve current config', stderr=to_text(err, errors='surrogate_or_strict')) cfg = to_text(out, errors='surrogate_or_strict').strip() _DEVICE_CONFIGS[cmd] = cfg return cfg def run_commands(module, commands, check_rc=True): responses = list() for cmd in to_list(commands): rc, out, err = exec_command(module, cmd) if check_rc and rc != 0: module.fail_json(msg=to_text(err, errors='surrogate_or_strict'), rc=rc) responses.append(to_text(out, errors='surrogate_or_strict')) return responses def load_config(module, commands, commit=False, comment=None): rc, out, err = exec_command(module, 'configure') if rc != 0: module.fail_json(msg='unable to enter configuration mode', output=to_text(err, errors='surrogate_or_strict')) for cmd in to_list(commands): rc, out, err = exec_command(module, cmd) if rc != 0: # discard any changes in case of failure exec_command(module, 'exit discard') module.fail_json(msg='configuration failed') diff = None if module._diff: rc, out, err = exec_command(module, 'compare') out = to_text(out, errors='surrogate_or_strict') if not out.startswith('No changes'): rc, out, err = exec_command(module, 'show') diff = to_text(out, errors='surrogate_or_strict').strip() if commit: cmd = 'commit' if comment: cmd += ' comment "%s"' % comment rc, out, err = exec_command(module, cmd) if rc != 0: # discard any changes in case of failure exec_command(module, 'exit discard') module.fail_json(msg='commit failed: %s' % err) if not commit: exec_command(module, 'exit discard') else: exec_command(module, 'exit') if diff: return diff
gpl-3.0
epitron/youtube-dl
youtube_dl/extractor/nba.py
27
5956
from __future__ import unicode_literals import functools import re from .turner import TurnerBaseIE from ..compat import ( compat_urllib_parse_urlencode, compat_urlparse, ) from ..utils import ( OnDemandPagedList, remove_start, ) class NBAIE(TurnerBaseIE): _VALID_URL = r'https?://(?:watch\.|www\.)?nba\.com/(?P<path>(?:[^/]+/)+(?P<id>[^?]*?))/?(?:/index\.html)?(?:\?.*)?$' _TESTS = [{ 'url': 'http://www.nba.com/video/games/nets/2012/12/04/0021200253-okc-bkn-recap.nba/index.html', 'md5': '9e7729d3010a9c71506fd1248f74e4f4', 'info_dict': { 'id': '0021200253-okc-bkn-recap', 'ext': 'mp4', 'title': 'Thunder vs. Nets', 'description': 'Kevin Durant scores 32 points and dishes out six assists as the Thunder beat the Nets in Brooklyn.', 'duration': 181, 'timestamp': 1354638466, 'upload_date': '20121204', }, 'params': { # m3u8 download 'skip_download': True, }, }, { 'url': 'http://www.nba.com/video/games/hornets/2014/12/05/0021400276-nyk-cha-play5.nba/', 'only_matching': True, }, { 'url': 'http://watch.nba.com/video/channels/playoffs/2015/05/20/0041400301-cle-atl-recap.nba', 'md5': 'b2b39b81cf28615ae0c3360a3f9668c4', 'info_dict': { 'id': 'channels/playoffs/2015/05/20/0041400301-cle-atl-recap.nba', 'ext': 'mp4', 'title': 'Hawks vs. Cavaliers Game 1', 'description': 'md5:8094c3498d35a9bd6b1a8c396a071b4d', 'duration': 228, 'timestamp': 1432134543, 'upload_date': '20150520', }, 'expected_warnings': ['Unable to download f4m manifest'], }, { 'url': 'http://www.nba.com/clippers/news/doc-rivers-were-not-trading-blake', 'info_dict': { 'id': 'teams/clippers/2016/02/17/1455672027478-Doc_Feb16_720.mov-297324', 'ext': 'mp4', 'title': 'Practice: Doc Rivers - 2/16/16', 'description': 'Head Coach Doc Rivers addresses the media following practice.', 'upload_date': '20160216', 'timestamp': 1455672000, }, 'params': { # m3u8 download 'skip_download': True, }, 'expected_warnings': ['Unable to download f4m manifest'], }, { 'url': 'http://www.nba.com/timberwolves/wiggins-shootaround#', 'info_dict': { 'id': 'timberwolves', 'title': 'Shootaround Access - Dec. 12 | Andrew Wiggins', }, 'playlist_count': 30, 'params': { # Download the whole playlist takes too long time 'playlist_items': '1-30', }, }, { 'url': 'http://www.nba.com/timberwolves/wiggins-shootaround#', 'info_dict': { 'id': 'teams/timberwolves/2014/12/12/Wigginsmp4-3462601', 'ext': 'mp4', 'title': 'Shootaround Access - Dec. 12 | Andrew Wiggins', 'description': 'Wolves rookie Andrew Wiggins addresses the media after Friday\'s shootaround.', 'upload_date': '20141212', 'timestamp': 1418418600, }, 'params': { 'noplaylist': True, # m3u8 download 'skip_download': True, }, 'expected_warnings': ['Unable to download f4m manifest'], }] _PAGE_SIZE = 30 def _fetch_page(self, team, video_id, page): search_url = 'http://searchapp2.nba.com/nba-search/query.jsp?' + compat_urllib_parse_urlencode({ 'type': 'teamvideo', 'start': page * self._PAGE_SIZE + 1, 'npp': (page + 1) * self._PAGE_SIZE + 1, 'sort': 'recent', 'output': 'json', 'site': team, }) results = self._download_json( search_url, video_id, note='Download page %d of playlist data' % page)['results'][0] for item in results: yield self.url_result(compat_urlparse.urljoin('http://www.nba.com/', item['url'])) def _extract_playlist(self, orig_path, video_id, webpage): team = orig_path.split('/')[0] if self._downloader.params.get('noplaylist'): self.to_screen('Downloading just video because of --no-playlist') video_path = self._search_regex( r'nbaVideoCore\.firstVideo\s*=\s*\'([^\']+)\';', webpage, 'video path') video_url = 'http://www.nba.com/%s/video/%s' % (team, video_path) return self.url_result(video_url) self.to_screen('Downloading playlist - add --no-playlist to just download video') playlist_title = self._og_search_title(webpage, fatal=False) entries = OnDemandPagedList( functools.partial(self._fetch_page, team, video_id), self._PAGE_SIZE) return self.playlist_result(entries, team, playlist_title) def _real_extract(self, url): path, video_id = re.match(self._VALID_URL, url).groups() orig_path = path if path.startswith('nba/'): path = path[3:] if 'video/' not in path: webpage = self._download_webpage(url, video_id) path = remove_start(self._search_regex(r'data-videoid="([^"]+)"', webpage, 'video id'), '/') if path == '{{id}}': return self._extract_playlist(orig_path, video_id, webpage) # See prepareContentId() of pkgCvp.js if path.startswith('video/teams'): path = 'video/channels/proxy/' + path[6:] return self._extract_cvp_info( 'http://www.nba.com/%s.xml' % path, video_id, { 'default': { 'media_src': 'http://nba.cdn.turner.com/nba/big', }, 'm3u8': { 'media_src': 'http://nbavod-f.akamaihd.net', }, })
unlicense
todaychi/hue
desktop/core/ext-py/Django-1.6.10/django/contrib/gis/geos/prototypes/__init__.py
314
1305
""" This module contains all of the GEOS ctypes function prototypes. Each prototype handles the interaction between the GEOS library and Python via ctypes. """ # Coordinate sequence routines. from django.contrib.gis.geos.prototypes.coordseq import (create_cs, get_cs, cs_clone, cs_getordinate, cs_setordinate, cs_getx, cs_gety, cs_getz, cs_setx, cs_sety, cs_setz, cs_getsize, cs_getdims) # Geometry routines. from django.contrib.gis.geos.prototypes.geom import (from_hex, from_wkb, from_wkt, create_point, create_linestring, create_linearring, create_polygon, create_collection, destroy_geom, get_extring, get_intring, get_nrings, get_geomn, geom_clone, geos_normalize, geos_type, geos_typeid, geos_get_srid, geos_set_srid, get_dims, get_num_coords, get_num_geoms, to_hex, to_wkb, to_wkt) # Miscellaneous routines. from django.contrib.gis.geos.prototypes.misc import * # Predicates from django.contrib.gis.geos.prototypes.predicates import (geos_hasz, geos_isempty, geos_isring, geos_issimple, geos_isvalid, geos_contains, geos_crosses, geos_disjoint, geos_equals, geos_equalsexact, geos_intersects, geos_intersects, geos_overlaps, geos_relatepattern, geos_touches, geos_within) # Topology routines from django.contrib.gis.geos.prototypes.topology import *
apache-2.0
andyneff/voxel-globe
voxel_globe/ingest/metadata/tools.py
1
6144
import os import json from celery.utils.log import get_task_logger from vsi.iglob import glob as iglob logger = get_task_logger(__name__); #Move to ingest.tools when done devving def match_images(images, camera_names, json_config={}): ''' returns dictionary camera_name:image pairs json example: {"image_camera_match": {"frame_00008.png": "frame_00001.txt", "frame_00019.png": "frame_00002.txt", "frame_00022.png": "frame_00003.txt"} } ''' matches = {} try: json_config=json_config['image_camera_match'] except (TypeError, KeyError): json_config={} #lowercase everything... THANK YOU WINDOWS! 8:( camera_safe_names_ext = [x.lower() for x in camera_names] camera_safe_names = [os.path.splitext(x)[0] for x in camera_safe_names_ext] image_safe_names_ext = [s.original_filename.lower() for s in images] json_image_safe_names = [s.lower() for s in json_config] for image_index, image in enumerate(images): #First check the json_config to see if the camera/image is defined there. #This takes priority try: json_image_index = json_image_safe_names.index(image_safe_names_ext[image_index]) json_image_name = json_config.keys()[json_image_index] json_camera_name = json_config[json_image_name] camera_index = camera_safe_names_ext.index(json_camera_name.lower()) camera_name = camera_names[camera_index] matches[camera_name] = image continue except ValueError: pass #Second, guess that the filenames without extension match try: image_name = os.path.splitext(image_safe_names_ext[image_index])[0] #strip the extension to check against camera name camera_index = camera_safe_names.index(image_name) camera_name = camera_names[camera_index] matches[camera_name] = image continue except ValueError: pass logger.debug('No camera matched for %s', image.original_filename) #Third if there are NO matches, guess that when sorted in lowered alpha order #that they match that way... NOT the best, but it's a nice idea... if not matches: from vsi.tools.natural_sort import natural_sorted camera_indexes = [i[0] for i in natural_sorted( enumerate(camera_safe_names_ext), key=lambda x:x[1])] image_indexes = [i[0] for i in natural_sorted( enumerate(image_safe_names_ext), key=lambda x:x[1])] number_matches = min(len(camera_indexes), len(image_indexes)) for match_index in range(number_matches): image_index = image_indexes[match_index] camera_index = camera_indexes[match_index] matches[camera_names[camera_index]] = images[image_index] logger.info('%d out of %d images matched to cameras', len(matches), len(images)) return matches ################## krt/other ################## def load_voxel_globe_metadata(directory_or_filename='ingest_voxel_globe.json'): ''' Loads the ingest_voxel_globe json file Will read in the json configuration file for the ingest. The argument can be a case sensitive filename, or a directory where a case insensitive search for filename 'ingest_voxel_globe.json' will be loaded Arguments directory_or_filename - Directory containing ingest_voxel_globe.json or filename of json file Return Dictionary of json object, or None if file not found ''' if os.path.isdir(directory_or_filename): filename = iglob(os.path.join(directory_or_filename, 'ingest_voxel_globe.json'), False) else: if os.path.exists(directory_or_filename): filename = [directory_or_filename] else: return None config = None for match_ifilename in filename: #Case insensitive with open(match_ifilename, 'r') as fid: config = json.load(fid) return config def create_scene(service_id, name, origin_point, bbox_min_point='POINT(0 0 0)', bbox_max_point='POINT(0 0 0)', default_voxel_size_point='POINT(1 1 1)', geolocated=None): from voxel_globe.meta.models import Scene if geolocated is None: geolocated = not (origin_point[0] == 0 and origin_point[1] == 0 and origin_point[2] == 0) scene = Scene.create(name=name, service_id=service_id, origin=origin_point, bbox_min=bbox_min_point, bbox_max=bbox_max_point, default_voxel_size=default_voxel_size_point, geolocated=geolocated) scene.save() return scene ################## Arducopter ################## class AdjTaggedMetadata(object): def __init__(self, line=None): if line: (self.filename, n) = line.split(' ', 1); n = map(float, n.split(' ')); self.llh_xyz = [n[0], n[1], n[2]]; #degrees, meters self.yrp = n[3:] #degrees else: raise Exception('Not implemented yet'); def __str__(self): return self.filename + (' %0.12g'*3) % (self.llh_xyz[1], self.llh_xyz[0], self.llh_xyz[2]) def __repr__(self): return '%s@%s@%s' % (self.filename, self.llh_xyz, self.yrp) def load_arducopter_metadata(filename): images = [] with open(filename, 'r') as fid: fid.readline(); for line in fid: images += [AdjTaggedMetadata(line)]; return images; ################## CLIF ################## def split_clif(filename): ''' Return dir, camera_id, image_number, extention''' dirname = os.path.dirname(filename) filename = os.path.basename(filename) (filename, extention) = os.path.splitext(filename) (camera_id, image_number) = filename.split('-') return (dirname, camera_id, image_number, extention) ################## EXIF ################## def exif_date_time_parse(datetime): ' Returns ("YYYY-MM-DD", "HH:MM:SS") ' datetime = datetime.split(' ') assert(len(datetime)==2) #will be larger for unknown date/time date=datetime[0].split(':') time=datetime[1] date='-'.join(date) return (date, time)
mit
stvstnfrd/edx-platform
lms/djangoapps/grades/tests/test_signals.py
5
9726
""" Tests for the score change signals defined in the courseware models module. """ import re from datetime import datetime from unittest.mock import MagicMock, patch import ddt import pytest import pytz from django.test import TestCase from submissions.models import score_reset, score_set from common.djangoapps.util.date_utils import to_timestamp from ..constants import ScoreDatabaseTableEnum from ..signals.handlers import ( disconnect_submissions_signal_receiver, problem_raw_score_changed_handler, submissions_score_reset_handler, submissions_score_set_handler ) from ..signals.signals import PROBLEM_RAW_SCORE_CHANGED UUID_REGEX = re.compile('{hex}{{8}}-{hex}{{4}}-{hex}{{4}}-{hex}{{4}}-{hex}{{12}}'.format(hex='[0-9a-f]')) FROZEN_NOW_DATETIME = datetime.now().replace(tzinfo=pytz.UTC) FROZEN_NOW_TIMESTAMP = to_timestamp(FROZEN_NOW_DATETIME) SUBMISSIONS_SCORE_SET_HANDLER = 'submissions_score_set_handler' SUBMISSIONS_SCORE_RESET_HANDLER = 'submissions_score_reset_handler' HANDLERS = { SUBMISSIONS_SCORE_SET_HANDLER: submissions_score_set_handler, SUBMISSIONS_SCORE_RESET_HANDLER: submissions_score_reset_handler, } SUBMISSION_SET_KWARGS = 'submission_set_kwargs' SUBMISSION_RESET_KWARGS = 'submission_reset_kwargs' SUBMISSION_KWARGS = { SUBMISSION_SET_KWARGS: { 'points_possible': 10, 'points_earned': 5, 'anonymous_user_id': 'anonymous_id', 'course_id': 'CourseID', 'item_id': 'i4x://org/course/usage/123456', 'created_at': FROZEN_NOW_TIMESTAMP, }, SUBMISSION_RESET_KWARGS: { 'anonymous_user_id': 'anonymous_id', 'course_id': 'CourseID', 'item_id': 'i4x://org/course/usage/123456', 'created_at': FROZEN_NOW_TIMESTAMP, }, } PROBLEM_RAW_SCORE_CHANGED_KWARGS = { 'raw_earned': 1.0, 'raw_possible': 2.0, 'weight': 4, 'user_id': 'UserID', 'course_id': 'CourseID', 'usage_id': 'i4x://org/course/usage/123456', 'only_if_higher': False, 'score_deleted': True, 'modified': FROZEN_NOW_TIMESTAMP, 'score_db_table': ScoreDatabaseTableEnum.courseware_student_module, 'grader_response': None } PROBLEM_WEIGHTED_SCORE_CHANGED_KWARGS = { 'sender': None, 'weighted_earned': 2.0, 'weighted_possible': 4.0, 'user_id': 'UserID', 'course_id': 'CourseID', 'usage_id': 'i4x://org/course/usage/123456', 'only_if_higher': False, 'score_deleted': True, 'modified': FROZEN_NOW_TIMESTAMP, 'score_db_table': ScoreDatabaseTableEnum.courseware_student_module, 'grader_response': None } @ddt.ddt class ScoreChangedSignalRelayTest(TestCase): """ Tests to ensure that the courseware module correctly catches (a) score_set and score_reset signals from the Submissions API (b) LMS PROBLEM_RAW_SCORE_CHANGED signals and recasts them as LMS PROBLEM_WEIGHTED_SCORE_CHANGED signals. This ensures that listeners in the LMS only have to handle one type of signal for all scoring events regardless of their origin. """ SIGNALS = { 'score_set': score_set, 'score_reset': score_reset, } def setUp(self): """ Configure mocks for all the dependencies of the render method """ super().setUp() self.signal_mock = self.setup_patch( 'lms.djangoapps.grades.signals.signals.PROBLEM_WEIGHTED_SCORE_CHANGED.send', None, ) self.user_mock = MagicMock() self.user_mock.id = 42 self.get_user_mock = self.setup_patch( 'lms.djangoapps.grades.signals.handlers.user_by_anonymous_id', self.user_mock ) def setup_patch(self, function_name, return_value): """ Patch a function with a given return value, and return the mock """ mock = MagicMock(return_value=return_value) new_patch = patch(function_name, new=mock) new_patch.start() self.addCleanup(new_patch.stop) return mock @ddt.data( [SUBMISSIONS_SCORE_SET_HANDLER, SUBMISSION_SET_KWARGS, 5, 10], [SUBMISSIONS_SCORE_RESET_HANDLER, SUBMISSION_RESET_KWARGS, 0, 0], ) @ddt.unpack def test_score_set_signal_handler(self, handler_name, kwargs, earned, possible): """ Ensure that on receipt of a score_(re)set signal from the Submissions API, the signal handler correctly converts it to a PROBLEM_WEIGHTED_SCORE_CHANGED signal. Also ensures that the handler calls user_by_anonymous_id correctly. """ local_kwargs = SUBMISSION_KWARGS[kwargs].copy() handler = HANDLERS[handler_name] handler(None, **local_kwargs) expected_set_kwargs = { 'sender': None, 'weighted_possible': possible, 'weighted_earned': earned, 'user_id': self.user_mock.id, 'anonymous_user_id': 'anonymous_id', 'course_id': 'CourseID', 'usage_id': 'i4x://org/course/usage/123456', 'modified': FROZEN_NOW_TIMESTAMP, 'score_db_table': 'submissions', } if kwargs == SUBMISSION_RESET_KWARGS: expected_set_kwargs['score_deleted'] = True self.signal_mock.assert_called_once_with(**expected_set_kwargs) self.get_user_mock.assert_called_once_with(local_kwargs['anonymous_user_id']) def test_tnl_6599_zero_possible_bug(self): """ Ensure that, if coming from the submissions API, signals indicating a a possible score of 0 are swallowed for reasons outlined in TNL-6559. """ local_kwargs = SUBMISSION_KWARGS[SUBMISSION_SET_KWARGS].copy() local_kwargs['points_earned'] = 0 local_kwargs['points_possible'] = 0 submissions_score_set_handler(None, **local_kwargs) self.signal_mock.assert_not_called() @ddt.data( [SUBMISSIONS_SCORE_SET_HANDLER, SUBMISSION_SET_KWARGS], [SUBMISSIONS_SCORE_RESET_HANDLER, SUBMISSION_RESET_KWARGS] ) @ddt.unpack def test_score_set_missing_kwarg(self, handler_name, kwargs): """ Ensure that, on receipt of a score_(re)set signal from the Submissions API that does not have the correct kwargs, the courseware model does not generate a signal. """ handler = HANDLERS[handler_name] for missing in SUBMISSION_KWARGS[kwargs]: local_kwargs = SUBMISSION_KWARGS[kwargs].copy() del local_kwargs[missing] with pytest.raises(KeyError): handler(None, **local_kwargs) self.signal_mock.assert_not_called() @ddt.data( [SUBMISSIONS_SCORE_SET_HANDLER, SUBMISSION_SET_KWARGS], [SUBMISSIONS_SCORE_RESET_HANDLER, SUBMISSION_RESET_KWARGS] ) @ddt.unpack def test_score_set_bad_user(self, handler_name, kwargs): """ Ensure that, on receipt of a score_(re)set signal from the Submissions API that has an invalid user ID, the courseware model does not generate a signal. """ handler = HANDLERS[handler_name] self.get_user_mock = self.setup_patch('lms.djangoapps.grades.signals.handlers.user_by_anonymous_id', None) handler(None, **SUBMISSION_KWARGS[kwargs]) self.signal_mock.assert_not_called() def test_raw_score_changed_signal_handler(self): problem_raw_score_changed_handler(None, **PROBLEM_RAW_SCORE_CHANGED_KWARGS) expected_set_kwargs = PROBLEM_WEIGHTED_SCORE_CHANGED_KWARGS.copy() self.signal_mock.assert_called_with(**expected_set_kwargs) def test_raw_score_changed_score_deleted_optional(self): local_kwargs = PROBLEM_RAW_SCORE_CHANGED_KWARGS.copy() del local_kwargs['score_deleted'] problem_raw_score_changed_handler(None, **local_kwargs) expected_set_kwargs = PROBLEM_WEIGHTED_SCORE_CHANGED_KWARGS.copy() expected_set_kwargs['score_deleted'] = False self.signal_mock.assert_called_with(**expected_set_kwargs) @ddt.data( ['score_set', SUBMISSION_KWARGS[SUBMISSION_SET_KWARGS]['points_earned'], SUBMISSION_SET_KWARGS], ['score_reset', 0, SUBMISSION_RESET_KWARGS] ) @ddt.unpack def test_disconnect_manager(self, signal_name, weighted_earned, kwargs): """ Tests to confirm the disconnect_submissions_signal_receiver context manager is working correctly. """ signal = self.SIGNALS[signal_name] kwargs = SUBMISSION_KWARGS[kwargs].copy() handler_mock = self.setup_patch('lms.djangoapps.grades.signals.handlers.PROBLEM_WEIGHTED_SCORE_CHANGED.send', None) # Receiver connected before we start signal.send(None, **kwargs) handler_mock.assert_called_once() # Make sure the correct handler was called assert handler_mock.call_args[1]['weighted_earned'] == weighted_earned handler_mock.reset_mock() # Disconnect is functioning with disconnect_submissions_signal_receiver(signal): signal.send(None, **kwargs) handler_mock.assert_not_called() handler_mock.reset_mock() # And we reconnect properly afterwards signal.send(None, **kwargs) handler_mock.assert_called_once() assert handler_mock.call_args[1]['weighted_earned'] == weighted_earned def test_disconnect_manager_bad_arg(self): """ Tests that the disconnect context manager errors when given an invalid signal. """ with pytest.raises(ValueError): with disconnect_submissions_signal_receiver(PROBLEM_RAW_SCORE_CHANGED): pass
agpl-3.0
fidomason/kbengine
kbe/res/scripts/common/Lib/encodings/hex_codec.py
202
1508
"""Python 'hex_codec' Codec - 2-digit hex content transfer encoding. This codec de/encodes from bytes to bytes. Written by Marc-Andre Lemburg ([email protected]). """ import codecs import binascii ### Codec APIs def hex_encode(input, errors='strict'): assert errors == 'strict' return (binascii.b2a_hex(input), len(input)) def hex_decode(input, errors='strict'): assert errors == 'strict' return (binascii.a2b_hex(input), len(input)) class Codec(codecs.Codec): def encode(self, input, errors='strict'): return hex_encode(input, errors) def decode(self, input, errors='strict'): return hex_decode(input, errors) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): assert self.errors == 'strict' return binascii.b2a_hex(input) class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): assert self.errors == 'strict' return binascii.a2b_hex(input) class StreamWriter(Codec, codecs.StreamWriter): charbuffertype = bytes class StreamReader(Codec, codecs.StreamReader): charbuffertype = bytes ### encodings module API def getregentry(): return codecs.CodecInfo( name='hex', encode=hex_encode, decode=hex_decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamwriter=StreamWriter, streamreader=StreamReader, _is_text_encoding=False, )
lgpl-3.0
meletakis/collato
lib/python2.7/site-packages/django/templatetags/static.py
114
4022
try: from urllib.parse import urljoin except ImportError: # Python 2 from urlparse import urljoin from django import template from django.template.base import Node from django.utils.encoding import iri_to_uri register = template.Library() class PrefixNode(template.Node): def __repr__(self): return "<PrefixNode for %r>" % self.name def __init__(self, varname=None, name=None): if name is None: raise template.TemplateSyntaxError( "Prefix nodes must be given a name to return.") self.varname = varname self.name = name @classmethod def handle_token(cls, parser, token, name): """ Class method to parse prefix node and return a Node. """ tokens = token.contents.split() if len(tokens) > 1 and tokens[1] != 'as': raise template.TemplateSyntaxError( "First argument in '%s' must be 'as'" % tokens[0]) if len(tokens) > 1: varname = tokens[2] else: varname = None return cls(varname, name) @classmethod def handle_simple(cls, name): try: from django.conf import settings except ImportError: prefix = '' else: prefix = iri_to_uri(getattr(settings, name, '')) return prefix def render(self, context): prefix = self.handle_simple(self.name) if self.varname is None: return prefix context[self.varname] = prefix return '' @register.tag def get_static_prefix(parser, token): """ Populates a template variable with the static prefix, ``settings.STATIC_URL``. Usage:: {% get_static_prefix [as varname] %} Examples:: {% get_static_prefix %} {% get_static_prefix as static_prefix %} """ return PrefixNode.handle_token(parser, token, "STATIC_URL") @register.tag def get_media_prefix(parser, token): """ Populates a template variable with the media prefix, ``settings.MEDIA_URL``. Usage:: {% get_media_prefix [as varname] %} Examples:: {% get_media_prefix %} {% get_media_prefix as media_prefix %} """ return PrefixNode.handle_token(parser, token, "MEDIA_URL") class StaticNode(Node): def __init__(self, varname=None, path=None): if path is None: raise template.TemplateSyntaxError( "Static template nodes must be given a path to return.") self.path = path self.varname = varname def url(self, context): path = self.path.resolve(context) return self.handle_simple(path) def render(self, context): url = self.url(context) if self.varname is None: return url context[self.varname] = url return '' @classmethod def handle_simple(cls, path): return urljoin(PrefixNode.handle_simple("STATIC_URL"), path) @classmethod def handle_token(cls, parser, token): """ Class method to parse prefix node and return a Node. """ bits = token.split_contents() if len(bits) < 2: raise template.TemplateSyntaxError( "'%s' takes at least one argument (path to file)" % bits[0]) path = parser.compile_filter(bits[1]) if len(bits) >= 2 and bits[-2] == 'as': varname = bits[3] else: varname = None return cls(varname, path) @register.tag('static') def do_static(parser, token): """ Joins the given path with the STATIC_URL setting. Usage:: {% static path [as varname] %} Examples:: {% static "myapp/css/base.css" %} {% static variable_with_path %} {% static "myapp/css/base.css" as admin_base_css %} {% static variable_with_path as varname %} """ return StaticNode.handle_token(parser, token) def static(path): return StaticNode.handle_simple(path)
gpl-2.0
termie/nova-migration-demo
nova/tests/test_volume.py
2
14447
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Tests for Volume Code. """ import cStringIO from nova import context from nova import exception from nova import db from nova import flags from nova import log as logging from nova import test from nova import utils FLAGS = flags.FLAGS LOG = logging.getLogger('nova.tests.volume') class VolumeTestCase(test.TestCase): """Test Case for volumes.""" def setUp(self): super(VolumeTestCase, self).setUp() self.compute = utils.import_object(FLAGS.compute_manager) self.flags(connection_type='fake') self.volume = utils.import_object(FLAGS.volume_manager) self.context = context.get_admin_context() @staticmethod def _create_volume(size='0'): """Create a volume object.""" vol = {} vol['size'] = size vol['user_id'] = 'fake' vol['project_id'] = 'fake' vol['availability_zone'] = FLAGS.storage_availability_zone vol['status'] = "creating" vol['attach_status'] = "detached" return db.volume_create(context.get_admin_context(), vol)['id'] def test_create_delete_volume(self): """Test volume can be created and deleted.""" volume_id = self._create_volume() self.volume.create_volume(self.context, volume_id) self.assertEqual(volume_id, db.volume_get(context.get_admin_context(), volume_id).id) self.volume.delete_volume(self.context, volume_id) self.assertRaises(exception.NotFound, db.volume_get, self.context, volume_id) def test_too_big_volume(self): """Ensure failure if a too large of a volume is requested.""" # FIXME(vish): validation needs to move into the data layer in # volume_create return True try: volume_id = self._create_volume('1001') self.volume.create_volume(self.context, volume_id) self.fail("Should have thrown TypeError") except TypeError: pass def test_too_many_volumes(self): """Ensure that NoMoreTargets is raised when we run out of volumes.""" vols = [] total_slots = FLAGS.iscsi_num_targets for _index in xrange(total_slots): volume_id = self._create_volume() self.volume.create_volume(self.context, volume_id) vols.append(volume_id) volume_id = self._create_volume() self.assertRaises(db.NoMoreTargets, self.volume.create_volume, self.context, volume_id) db.volume_destroy(context.get_admin_context(), volume_id) for volume_id in vols: self.volume.delete_volume(self.context, volume_id) def test_run_attach_detach_volume(self): """Make sure volume can be attached and detached from instance.""" inst = {} inst['image_id'] = 1 inst['reservation_id'] = 'r-fakeres' inst['launch_time'] = '10' inst['user_id'] = 'fake' inst['project_id'] = 'fake' inst['instance_type_id'] = '2' # m1.tiny inst['mac_address'] = utils.generate_mac() inst['ami_launch_index'] = 0 instance_id = db.instance_create(self.context, inst)['id'] mountpoint = "/dev/sdf" volume_id = self._create_volume() self.volume.create_volume(self.context, volume_id) if FLAGS.fake_tests: db.volume_attached(self.context, volume_id, instance_id, mountpoint) else: self.compute.attach_volume(self.context, instance_id, volume_id, mountpoint) vol = db.volume_get(context.get_admin_context(), volume_id) self.assertEqual(vol['status'], "in-use") self.assertEqual(vol['attach_status'], "attached") self.assertEqual(vol['mountpoint'], mountpoint) instance_ref = db.volume_get_instance(self.context, volume_id) self.assertEqual(instance_ref['id'], instance_id) self.assertRaises(exception.Error, self.volume.delete_volume, self.context, volume_id) if FLAGS.fake_tests: db.volume_detached(self.context, volume_id) else: self.compute.detach_volume(self.context, instance_id, volume_id) vol = db.volume_get(self.context, volume_id) self.assertEqual(vol['status'], "available") self.volume.delete_volume(self.context, volume_id) self.assertRaises(exception.VolumeNotFound, db.volume_get, self.context, volume_id) db.instance_destroy(self.context, instance_id) def test_concurrent_volumes_get_different_targets(self): """Ensure multiple concurrent volumes get different targets.""" volume_ids = [] targets = [] def _check(volume_id): """Make sure targets aren't duplicated.""" volume_ids.append(volume_id) admin_context = context.get_admin_context() iscsi_target = db.volume_get_iscsi_target_num(admin_context, volume_id) self.assert_(iscsi_target not in targets) targets.append(iscsi_target) LOG.debug(_("Target %s allocated"), iscsi_target) total_slots = FLAGS.iscsi_num_targets for _index in xrange(total_slots): volume_id = self._create_volume() d = self.volume.create_volume(self.context, volume_id) _check(d) for volume_id in volume_ids: self.volume.delete_volume(self.context, volume_id) def test_multi_node(self): # TODO(termie): Figure out how to test with two nodes, # each of them having a different FLAG for storage_node # This will allow us to test cross-node interactions pass class DriverTestCase(test.TestCase): """Base Test class for Drivers.""" driver_name = "nova.volume.driver.FakeAOEDriver" def setUp(self): super(DriverTestCase, self).setUp() self.flags(volume_driver=self.driver_name, logging_default_format_string="%(message)s") self.volume = utils.import_object(FLAGS.volume_manager) self.context = context.get_admin_context() self.output = "" def _fake_execute(_command, *_args, **_kwargs): """Fake _execute.""" return self.output, None self.volume.driver._execute = _fake_execute self.volume.driver._sync_execute = _fake_execute log = logging.getLogger() self.stream = cStringIO.StringIO() log.addHandler(logging.StreamHandler(self.stream)) inst = {} self.instance_id = db.instance_create(self.context, inst)['id'] def tearDown(self): super(DriverTestCase, self).tearDown() def _attach_volume(self): """Attach volumes to an instance. This function also sets a fake log message.""" return [] def _detach_volume(self, volume_id_list): """Detach volumes from an instance.""" for volume_id in volume_id_list: db.volume_detached(self.context, volume_id) self.volume.delete_volume(self.context, volume_id) class AOETestCase(DriverTestCase): """Test Case for AOEDriver""" driver_name = "nova.volume.driver.AOEDriver" def setUp(self): super(AOETestCase, self).setUp() def tearDown(self): super(AOETestCase, self).tearDown() def _attach_volume(self): """Attach volumes to an instance. This function also sets a fake log message.""" volume_id_list = [] for index in xrange(3): vol = {} vol['size'] = 0 volume_id = db.volume_create(self.context, vol)['id'] self.volume.create_volume(self.context, volume_id) # each volume has a different mountpoint mountpoint = "/dev/sd" + chr((ord('b') + index)) db.volume_attached(self.context, volume_id, self.instance_id, mountpoint) (shelf_id, blade_id) = db.volume_get_shelf_and_blade(self.context, volume_id) self.output += "%s %s eth0 /dev/nova-volumes/vol-foo auto run\n" \ % (shelf_id, blade_id) volume_id_list.append(volume_id) return volume_id_list def test_check_for_export_with_no_volume(self): """No log message when no volume is attached to an instance.""" self.stream.truncate(0) self.volume.check_for_export(self.context, self.instance_id) self.assertEqual(self.stream.getvalue(), '') def test_check_for_export_with_all_vblade_processes(self): """No log message when all the vblade processes are running.""" volume_id_list = self._attach_volume() self.stream.truncate(0) self.volume.check_for_export(self.context, self.instance_id) self.assertEqual(self.stream.getvalue(), '') self._detach_volume(volume_id_list) def test_check_for_export_with_vblade_process_missing(self): """Output a warning message when some vblade processes aren't running.""" volume_id_list = self._attach_volume() # the first vblade process isn't running self.output = self.output.replace("run", "down", 1) (shelf_id, blade_id) = db.volume_get_shelf_and_blade(self.context, volume_id_list[0]) msg_is_match = False self.stream.truncate(0) try: self.volume.check_for_export(self.context, self.instance_id) except exception.ProcessExecutionError, e: volume_id = volume_id_list[0] msg = _("Cannot confirm exported volume id:%(volume_id)s. " "vblade process for e%(shelf_id)s.%(blade_id)s " "isn't running.") % locals() msg_is_match = (0 <= e.message.find(msg)) self.assertTrue(msg_is_match) self._detach_volume(volume_id_list) class ISCSITestCase(DriverTestCase): """Test Case for ISCSIDriver""" driver_name = "nova.volume.driver.ISCSIDriver" def setUp(self): super(ISCSITestCase, self).setUp() def tearDown(self): super(ISCSITestCase, self).tearDown() def _attach_volume(self): """Attach volumes to an instance. This function also sets a fake log message.""" volume_id_list = [] for index in xrange(3): vol = {} vol['size'] = 0 vol_ref = db.volume_create(self.context, vol) self.volume.create_volume(self.context, vol_ref['id']) vol_ref = db.volume_get(self.context, vol_ref['id']) # each volume has a different mountpoint mountpoint = "/dev/sd" + chr((ord('b') + index)) db.volume_attached(self.context, vol_ref['id'], self.instance_id, mountpoint) volume_id_list.append(vol_ref['id']) return volume_id_list def test_check_for_export_with_no_volume(self): """No log message when no volume is attached to an instance.""" self.stream.truncate(0) self.volume.check_for_export(self.context, self.instance_id) self.assertEqual(self.stream.getvalue(), '') def test_check_for_export_with_all_volume_exported(self): """No log message when all the vblade processes are running.""" volume_id_list = self._attach_volume() self.mox.StubOutWithMock(self.volume.driver, '_execute') for i in volume_id_list: tid = db.volume_get_iscsi_target_num(self.context, i) self.volume.driver._execute("sudo", "ietadm", "--op", "show", "--tid=%(tid)d" % locals()) self.stream.truncate(0) self.mox.ReplayAll() self.volume.check_for_export(self.context, self.instance_id) self.assertEqual(self.stream.getvalue(), '') self.mox.UnsetStubs() self._detach_volume(volume_id_list) def test_check_for_export_with_some_volume_missing(self): """Output a warning message when some volumes are not recognied by ietd.""" volume_id_list = self._attach_volume() # the first vblade process isn't running tid = db.volume_get_iscsi_target_num(self.context, volume_id_list[0]) self.mox.StubOutWithMock(self.volume.driver, '_execute') self.volume.driver._execute("sudo", "ietadm", "--op", "show", "--tid=%(tid)d" % locals()).AndRaise( exception.ProcessExecutionError()) self.mox.ReplayAll() self.assertRaises(exception.ProcessExecutionError, self.volume.check_for_export, self.context, self.instance_id) msg = _("Cannot confirm exported volume id:%s.") % volume_id_list[0] self.assertTrue(0 <= self.stream.getvalue().find(msg)) self.mox.UnsetStubs() self._detach_volume(volume_id_list)
apache-2.0
ivanovev/hm
srv/ANASAT.py
1
8497
from util import CachedDict from util.serial import query_serial cache = CachedDict() table_act = { 'TEMP': 0, 'TXOUT': 1, 'RXOUT': 1, 'P12V': 3, 'PA3': 4, 'PA4': 5, 'PA5': 6, 'PA6': 7, 'N5V': 8, 'OSLPLL': 9, 'TXPLL': 10, 'RXPLL': 11, 'LNBV': 12, 'TXIN': 13, 'TXOPLL': 17, 'P5V': 19, 'PA1': 20, 'PA2': 21 } table_offset = { 'TXGAIN': 0, 'RXGAIN': 1, 'TXIN': 2, 'RXOUT': 3, 'TXOUT': 4 } table_p = { 'RXOUT': 98, 'TXIN': 100, 'TXOUT': 102 } def get_baudrate_valid(baud): return int(baud) in [1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600] def get_query_string(port, cmd): a = ANASAT_addr(port) param = cmd.split()[0] if not a or param in ['R', 'CONNECT', 'DISCONNECT']: a = '0000' q = '%s02%s%s' % ('\2', a, cmd) n = 0 for i in range (1, len(q)): n = n + ord(q[i]) n %= 256 q = '%s%X%s' % (q, n, '\3') return q def strip_data(out, cmd): if len(out) > 10: out = out[7:] if len(out) > 3: out = out[:len(out)-3] cc = cmd.split() for c in cc: if out.find(c) == 0: out = out[len(c)+1:] out = out.strip() ret = '' for i in range(0, len(out)): if out[i].isprintable(): ret += out[i] return ret def ANASAT_cmd(port='COM1', cmd='INFO', *args): """ Функция для доступа к параметрам приёмопередатчика ANASAT @param port - для windows: COM1, COM2..., для *nix: ttyS*, ttyUSB*... @param cmd - ALARMS, ADC TXIN, ACT P12V... см. мануал @return - текущее значение """ cmd = ' '.join([cmd] + list(args)) cmd = cmd.strip() cc = cmd.split() param = cc[0] a = ANASAT_addr(port) if not a and param not in ['R', 'BAUDRATE', 'CONNECT', 'DISCONNECT']: a = ANASAT_find(port) if not a: return '' bps = ANASAT_bps(port) read = param not in ['BAUDRATE', 'CONNECT', 'DISCONNECT'] q = get_query_string(port, cmd) out = query_serial(port, bps, 8, 'N', 1, q, '\x03', True) #print('q:', q, 'cmd:', cmd, 'param:', param, 'bps:', bps, 'read:', read, 'len(out)', len(out), 'out:', out) if not out: return '' if param in ['TX', 'TXR', 'TXREQ', 'TXREQUEST', 'TXCHAN', 'RXCHAN', 'TXGAIN', 'RXGAIN', 'TXFREQ', 'RXFREQ'] and len(cc) > 1: return cc[1] return strip_data(out, cmd) def ANASAT_BAUDRATE(port='COM1', bps='9600'): ''' Установить скорость которая будет использоваться для работы с приёмопередатчиком @n команда BAUDRATE в последовательный порт ПОСЫЛАЕТСЯ @param bps - скорость, что-то из списка: 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600 @n либо пустая строка для запроса текущего значения bps @return bps ''' if not get_baudrate_valid(bps): return '' ANASAT_cmd(port, 'BAUDRATE %s' % bps) return ANASAT_bps(port, bps) def ANASAT_ADC_VREF(port='COM1'): ''' То же самое что и ANASAT.cmd(port, 'ADC_VREF') @return ADC_VREF ''' return cache.get(lambda: ANASAT_cmd(port, 'ADC_VREF'), port, 'ADC_VREF') def ANASAT_ACT(port='COM1', param='TEMP'): ''' Получить offset и gain для параметра param @param param - monitor_point из списка: @n TEMP, TXOUT, RXOUT, P12V, PA3, PA4, PA5, PA6, N5V, OSLPLL, TXPLL, RXPLL, LNBV, TXIN, TXOPLL, P5V, PA1, PA2 @return offset gain ''' act = cache.get(lambda: ANASAT_cmd(port, 'ACT'), port, 'ACT') if not act: return '' if param not in table_act: return '' p = table_act[param] aa = act.split() if len(aa) < 2*(p+1): return '' return '%s %s' % (aa[2*p], aa[2*p+1]) def ANASAT_OFFSET_TABLE(port='COM1'): a = ANASAT_addr(port) offset_table = cache.get(lambda: ANASAT_cmd(port, 'OFFSET_TABLE'), port, 'OFFSET_TABLE') if not offset_table and a != '0000': a = ANASAT_addr(port, '0000') offset_table = cache.get(lambda: ANASAT_cmd(port, 'OFFSET_TABLE'), port, 'OFFSET_TABLE') ANASAT_addr(port, a) return offset_table def ANASAT_ADC(port='COM1', param='TEMP'): ''' Получить пересчитанное значение АЦП @ для получения непересчинанного значения можно использовать ANASAT.cmd(port, 'ADC %param%') @param param - monitor_point из списка: @n TEMP, TXOUT, RXOUT, P12V, PA3, PA4, PA5, PA6, N5V, OSLPLL, TXPLL, RXPLL, LNBV, TXIN, TXOPLL, P5V, PA1, PA2 @return значение %param% ''' adc = cache.get(lambda: ANASAT_cmd(port, 'ADC'), port, 'ADC', duration=10) if not adc: return p = table_act[param] aa = adc.split() if len(aa) < p + 1: return '' adc = aa[p] if param in ['RXOUT', 'TXIN', 'TXOUT']: p = cache.get(lambda: ANASAT_cmd(port, 'P'), port, 'P', duration=10) if not p: return '' tp = table_p[param] sp = p[tp:tp+2] ip = int(sp, 16) if ip >= 128: ip = ip - 256 #offset_table = cache.get(lambda: ANASAT_cmd(port, 'OFFSET_TABLE'), port, 'OFFSET_TABLE')#, duration=10) offset_table = ANASAT_OFFSET_TABLE(port) if not offset_table: return '' ot = offset_table.split() tot = table_offset[param] fot = float(ot[tot]) value = ip + fot return '%.1f' % value elif param in table_act: vref = ANASAT_ADC_VREF(port) if not vref: return '' act = ANASAT_ACT(port, param) if not act: return vref = float(vref) adc = int(adc, 16) vread = (float(adc)/255)*vref aa = act.split() offset = float(aa[0]) gain = float(aa[1]) value = (vread - offset)*gain ret = '%.2f' % value ret = ret.rstrip('0') ret = ret.rstrip('.') return ret def ANASAT_ALARM(port='COM1'): ''' То же самое что и ANASAT.cmd(port, 'ALARM') @return ALARM ''' return ANASAT_cmd(port, 'ALARM') def ANASAT_find(port='COM1'): """ Получить адрес приёмопередатчика ANASAT (ODU Packet Address) @param port - для windows: COM1, COM2..., для *nix: ttyS*, ttyUSB*... @return - адрес (например 01FF) """ print('ANASAT_find') ANASAT_addr(port, addr='0000') ANASAT_bps(port, '9600') r = ANASAT_cmd(port, 'DISCONNECT; R 0 1') if not r: ANASAT_bps(port, '1200') r = ANASAT_cmd(port, 'DISCONNECT; R 0 1') if not r: return '' rr = r.split() sn = rr[-2] a = rr[-1] #ANASAT_cmd(port, 'CONNECT %s' % sn) ANASAT_addr(port, a) if ANASAT_bps(port) != '9600': ANASAT_BAUDRATE(port, '9600') return a def ANASAT_addr(port='COM1', addr=''): ''' Получить или задать адрес устройства, подключенного к порту %port% @return addr ''' if not addr: a = cache.find(port, 'addr') return a if a else '' return cache.get(lambda: addr, port, 'addr', forceupd=True) def ANASAT_bps(port='COM1', bps=''): ''' Установить скорость которая будет использоваться для работы с приёмопередатчиком @n команда BAUDRATE в последовательный порт НЕ ПОСЫЛАЕТСЯ @param bps - скорость, что-то из списка: 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600 @n либо пустая строка для запроса текущего значения bps @return bps ''' if not bps: return '%d' % cache.get(lambda: 1200, port, 'bps') if not get_baudrate_valid(bps): return '' cache.get(lambda: int(bps), port, 'bps', forceupd=True) return bps
gpl-3.0
ggalancs/marionette
marionette_tg/record_layer.py
3
5370
#!/usr/bin/env python # -*- coding: utf-8 -*- import binascii PAYLOAD_HEADER_SIZE_IN_BITS = 200 PAYLOAD_HEADER_SIZE_IN_BYTES = PAYLOAD_HEADER_SIZE_IN_BITS / 8 NORMAL = 0x1 END_OF_STREAM = 0x2 class Cell(object): def __init__(self, model_uuid, model_instance_id, stream_id, seq_id, length=0, cell_type=NORMAL): assert stream_id is not None self.cell_type_ = cell_type self.payload_ = '' self.payload_length_ = 0 self.sequence_id_ = seq_id self.cell_length_ = length self.stream_id_ = stream_id self.model_uuid_ = model_uuid self.model_instance_id_ = model_instance_id def __eq__(self, other): retval = ( self.get_payload() == other.get_payload()) and ( self.get_stream_id() == other.get_stream_id()) and ( self.get_model_uuid() == other.get_model_uuid()) and ( self.get_model_instance_id() == other.get_model_instance_id()) and ( self.get_seq_id() == other.get_seq_id()) return retval def get_cell_type(self): return self.cell_type_ def get_payload(self): return str(self.payload_) def set_payload(self, payload): self.payload_ = payload def get_stream_id(self): return int(self.stream_id_) def get_model_uuid(self): return self.model_uuid_ def get_model_instance_id(self): return self.model_instance_id_ def get_seq_id(self): return int(self.sequence_id_) def is_valid(self): retval = True return retval def to_string(self): return serialize(self, self.cell_length_) class EndOfStreamException(Exception): def set_stream_id(self, stream_id): self.stream_id_ = stream_id def get_stream_id(self): return self.stream_id_ def pad_to_bytes(n, val): val = str(val) while len(val) < n: val = '\x00' + val return val def long_to_bytes(N, blocksize=1): """Given an input integer ``N``, ``long_to_bytes`` returns the representation of ``N`` in bytes. If ``blocksize`` is greater than ``1`` then the output string will be right justified and then padded with zero-bytes, such that the return values length is a multiple of ``blocksize``. """ bytestring = hex(N) bytestring = bytestring[2:] if bytestring.startswith('0x') else bytestring bytestring = bytestring[:-1] if bytestring.endswith('L') else bytestring bytestring = '0' + bytestring if (len(bytestring) % 2) != 0 else bytestring bytestring = binascii.unhexlify(bytestring) if blocksize > 0 and len(bytestring) % blocksize != 0: bytestring = '\x00' * \ (blocksize - (len(bytestring) % blocksize)) + bytestring return bytestring def bytes_to_long(bytestring): """Given a ``bytestring`` returns its integer representation ``N``. """ bytestring = '\x00' + bytestring N = int(bytestring.encode('hex'), 16) return N # cell format # total cell length - 4 bytes # payload length - 4 bytes # model uuid - 4 bytes # model instance id - 4 bytes # stream ID - 4 bytes # sequence ID - 4 bytes # cell type - 1 byte # payload (variable) # padding (variable) def serialize(cell_obj, pad_to=0): retval = '' stream_id = cell_obj.get_stream_id() model_uuid = cell_obj.get_model_uuid() model_instance_id = cell_obj.get_model_instance_id() seq_id = cell_obj.get_seq_id() payload = cell_obj.get_payload() padding = '\x00' * ( (pad_to / 8) - len(payload) - PAYLOAD_HEADER_SIZE_IN_BYTES) cell_type = cell_obj.get_cell_type() bytes_cell_len = pad_to_bytes(4, long_to_bytes( PAYLOAD_HEADER_SIZE_IN_BYTES + len(payload) + len(padding))) bytes_payload_len = pad_to_bytes(4, long_to_bytes(len(payload))) bytes_model_uuid = pad_to_bytes(4, long_to_bytes(model_uuid)) bytes_model_instance_id = pad_to_bytes(4, long_to_bytes(model_instance_id)) bytes_stream_id = pad_to_bytes(4, long_to_bytes(stream_id)) bytes_seq_id = pad_to_bytes(4, long_to_bytes(seq_id)) bytes_cell_type = pad_to_bytes(1, long_to_bytes(cell_type)) retval += bytes_cell_len retval += bytes_payload_len retval += bytes_model_uuid retval += bytes_model_instance_id retval += bytes_stream_id retval += bytes_seq_id retval += bytes_cell_type retval += payload retval += padding assert (PAYLOAD_HEADER_SIZE_IN_BYTES + len(payload) + len(padding) ) == len(retval) return retval def unserialize(cell_str): cell_len = bytes_to_long(cell_str[:4]) payload_len = bytes_to_long(cell_str[4:8]) model_uuid = bytes_to_long(cell_str[8:12]) model_instance_id = bytes_to_long(cell_str[12:16]) stream_id = bytes_to_long(cell_str[16:20]) seq_id = bytes_to_long(cell_str[20:24]) cell_type = bytes_to_long(cell_str[24:25]) if cell_len != len(cell_str): raise UnserializeException() payload = cell_str[PAYLOAD_HEADER_SIZE_IN_BYTES: PAYLOAD_HEADER_SIZE_IN_BYTES + payload_len] retval = Cell( model_uuid, model_instance_id, stream_id, seq_id, payload_len, cell_type) retval.set_payload(payload) return retval class UnserializeException(Exception): pass
apache-2.0
WojciechMigda/TCO-PCFStupskiPrize1
src/cell_patches_dbscan.py
1
8930
#!/opt/anaconda2/bin/python # -*- coding: utf-8 -*- """ ################################################################################ # # Copyright (c) 2015 Wojciech Migda # All rights reserved # Distributed under the terms of the MIT license # ################################################################################ # # Filename: cell_patches_kmeans.py # # Decription: # Cell patches from images (with KMeans) # # Authors: # Wojciech Migda # ################################################################################ # # History: # -------- # Date Who Ticket Description # ---------- --- --------- ------------------------------------------------ # 2015-12-20 wm Initial version # ################################################################################ """ from __future__ import print_function DEBUG = False __all__ = [] __version__ = 0.1 __date__ = '2015-12-20' __updated__ = '2015-12-20' from sys import path as sys_path sys_path.insert(0, './Pipe') import pipe as P def pois(im, num_peaks, footprint_radius=2.5, min_dist=8, thr_abs=0.7): from skimage.draw import circle FOOTPRINT_RADIUS = footprint_radius cxy = circle(4, 4, FOOTPRINT_RADIUS) from numpy import zeros cc = zeros((9, 9), dtype=int) cc[cxy] = 1 from skimage.feature import peak_local_max MIN_DIST = min_dist THR_ABS = thr_abs coordinates = [ peak_local_max( im[:, :, layer], min_distance=MIN_DIST, footprint=cc, threshold_abs=THR_ABS, num_peaks=num_peaks) for layer in range(im.shape[2])] return coordinates @P.Pipe def cluster(seq, window, epsilon, with_polar): from numpy import where,array from skimagepipes import cart2polar_ w2 = window / 2 for im, pois in seq: for layer in range(im.shape[2]): p = pois[layer] p = p[where( (p[:, 0] >= w2) & (p[:, 0] < (im.shape[0] - w2)) & (p[:, 1] >= w2) & (p[:, 1] < (im.shape[1] - w2)) ) ] print(str(p.shape[0]) + " pois") patches = array([im[cx - w2:cx + w2, cy - w2:cy + w2, layer].ravel() for cx, cy in p]) if with_polar: patches = array([cart2polar_(im[cx - w2:cx + w2, cy - w2:cy + w2, layer]).ravel() for cx, cy in p]) pass from sklearn.cluster import DBSCAN #clf = DBSCAN(min_samples=5, eps=3.6) #clf = DBSCAN(min_samples=5, eps=3.3) # 16x16 [51,148,105] #clf = DBSCAN(min_samples=5, eps=3.2) # 16x16 [42,105,66] #clf = DBSCAN(min_samples=5, eps=3.1) # 16x16 [36,57,33] #clf = DBSCAN(min_samples=5, eps=2.8) # 14x14 [70,259,128] #clf = DBSCAN(min_samples=5, eps=2.6) # 14x14 [50,104,42*] #clf = DBSCAN(min_samples=5, eps=2.4) # 14x14 [34,34,11] #clf = DBSCAN(min_samples=5, eps=2.2) # 12x12 [84*,248,84] #clf = DBSCAN(min_samples=5, eps=2.1) # 12x12 [69*,155,48] clf = DBSCAN(eps=epsilon, leaf_size=1000) clf.fit(patches) print(clf.components_.shape) nclust = clf.components_.shape[0] VISUALIZE = True VISUALIZE = False if VISUALIZE: from skimage.exposure import rescale_intensity from matplotlib import pyplot as plt fig, ax = plt.subplots(1, nclust, figsize=(8, 3), sharex=True, sharey=True, subplot_kw={'adjustable':'box-forced'}) for i in range(nclust): ax[i].imshow( rescale_intensity( clf.components_[i].reshape((window, window)) ) ,interpolation='nearest' #,cmap=plt.cm.gray ) ax[i].axis('off') pass fig.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0.02, left=0.02, right=0.98) plt.show() pass yield clf.components_ pass return def work(in_csv_file, out_csv_file, max_n_pois, patch_size, epsilon, with_polar): from pypipes import as_csv_rows,iformat,loopcount,itime,iattach from nppipes import itake,iexpand_dims from skimagepipes import as_image,as_float,equalize_hist,imshow,trim,rgb_as_hed from tcopipes import clean features = ( in_csv_file | as_csv_rows #| P.skip(1) #| P.take(3) | itake(0) | P.tee | iformat('../../data/DX/{}-DX.png') | as_image | itime | loopcount | trim(0.2) | as_float | clean | rgb_as_hed | itake(0, axis=2) | iexpand_dims(axis=2) | equalize_hist | imshow("H layer", cmap='gray') | iattach(pois, max_n_pois) | cluster(patch_size, epsilon, with_polar) | P.as_list ) #print(type(next(features, None))) #print(next(features, None).shape) from numpy import vstack from numpy import savetxt #print(vstack(features).shape) savetxt(out_csv_file, vstack(features), delimiter=',', fmt='%f') pass def main(argv=None): # IGNORE:C0111 '''Command line options.''' from sys import argv as Argv if argv is None: argv = Argv pass else: Argv.extend(argv) pass from os.path import basename program_name = basename(Argv[0]) program_version = "v%s" % __version__ program_build_date = str(__updated__) program_version_message = '%%(prog)s %s (%s)' % (program_version, program_build_date) program_shortdesc = __import__('__main__').__doc__.split("\n")[1] program_license = '''%s Created by Wojciech Migda on %s. Copyright 2015 Wojciech Migda. All rights reserved. Licensed under the MIT License Distributed on an "AS IS" basis without warranties or conditions of any kind, either express or implied. USAGE ''' % (program_shortdesc, str(__date__)) try: from argparse import ArgumentParser from argparse import RawDescriptionHelpFormatter from argparse import FileType from sys import stdout,stdin # Setup argument parser parser = ArgumentParser(description=program_license, formatter_class=RawDescriptionHelpFormatter) #parser.add_argument("-D", "--data-dir", # type=str, action='store', dest="data_dir", required=True, # help="directory with input CSV files, BMP 'train' and 'test' subfolders, and where H5 will be stored") parser.add_argument("-i", "--in-csv", action='store', dest="in_csv_file", default=stdin, type=FileType('r'), help="input CSV file name") parser.add_argument("-o", "--out-csv", action='store', dest="out_csv_file", default=stdout, type=FileType('w'), help="output CSV file name") parser.add_argument("-p", "--patch-size", type=int, default=12, action='store', dest="patch_size", help="size of square patch to build the codebook upon, in pixels") parser.add_argument("-N", "--max-pois", type=int, default=5000, action='store', dest="max_n_pois", help="max number of PoIs to collect (num_peaks of peak_local_max)") parser.add_argument("-e", "--epsilon", type=float, default=2.1, action='store', dest="epsilon", help="epsilon for DBSCAN") parser.add_argument("-P", "--with-polar", default=False, action='store_true', dest="with_polar", help="convert patches to polar coordinates") # Process arguments args = parser.parse_args() for k, v in args.__dict__.items(): print(str(k) + ' => ' + str(v)) pass work(args.in_csv_file, args.out_csv_file, args.max_n_pois, args.patch_size, args.epsilon, args.with_polar) return 0 except KeyboardInterrupt: ### handle keyboard interrupt ### return 0 except Exception as e: if DEBUG: raise(e) pass indent = len(program_name) * " " from sys import stderr stderr.write(program_name + ": " + repr(e) + "\n") stderr.write(indent + " for help use --help") return 2 pass if __name__ == "__main__": if DEBUG: from sys import argv argv.append("--in-csv=../../data/training.csv") argv.append("--max-pois=5000") pass from sys import exit as Exit Exit(main()) pass
mit
nis-sdn/odenos
src/main/python/org/o3project/odenos/remoteobject/manager/event_subscription.py
6
2243
# -*- coding:utf-8 -*- # Copyright 2015 NEC Corporation. # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # class EventSubscription(object): SUBSCRIBER_ID = "subscriber_id" EVENT_FILTERS = "event_filters" def __init__(self, subscriber_id=None, event_filters={}): self.subscriber_id = subscriber_id self.event_filters = {k: set(v) for k, v in event_filters.items()} def clear_filter(self): self.event_filters.clear() def add_filter(self, publisher_id, event_id): if publisher_id not in self.event_filters: self.event_filters[publisher_id] = set() self.event_filters[publisher_id].add(event_id) def remove_filter(self, publisher_id, event_id): if publisher_id in self.event_filters: self.event_filters[publisher_id].remove(event_id) def remove_publisher_id(self, publisher_id): self.event_filters.pop(publisher_id, None) @classmethod def create_from_packed(cls, packed): return cls(packed[EventSubscription.SUBSCRIBER_ID], packed[EventSubscription.EVENT_FILTERS]) def packed_object(self): event_filters = {k: list(v) for k, v in self.event_filters.items()} return {self.SUBSCRIBER_ID: self.subscriber_id, self.EVENT_FILTERS: event_filters}
apache-2.0
kjw0106/GCM_app_server
venv/lib/python2.7/site-packages/sqlalchemy/ext/instrumentation.py
147
14856
"""Extensible class instrumentation. The :mod:`sqlalchemy.ext.instrumentation` package provides for alternate systems of class instrumentation within the ORM. Class instrumentation refers to how the ORM places attributes on the class which maintain data and track changes to that data, as well as event hooks installed on the class. .. note:: The extension package is provided for the benefit of integration with other object management packages, which already perform their own instrumentation. It is not intended for general use. For examples of how the instrumentation extension is used, see the example :ref:`examples_instrumentation`. .. versionchanged:: 0.8 The :mod:`sqlalchemy.orm.instrumentation` was split out so that all functionality having to do with non-standard instrumentation was moved out to :mod:`sqlalchemy.ext.instrumentation`. When imported, the module installs itself within :mod:`sqlalchemy.orm.instrumentation` so that it takes effect, including recognition of ``__sa_instrumentation_manager__`` on mapped classes, as well :data:`.instrumentation_finders` being used to determine class instrumentation resolution. """ from ..orm import instrumentation as orm_instrumentation from ..orm.instrumentation import ( ClassManager, InstrumentationFactory, _default_state_getter, _default_dict_getter, _default_manager_getter ) from ..orm import attributes, collections, base as orm_base from .. import util from ..orm import exc as orm_exc import weakref INSTRUMENTATION_MANAGER = '__sa_instrumentation_manager__' """Attribute, elects custom instrumentation when present on a mapped class. Allows a class to specify a slightly or wildly different technique for tracking changes made to mapped attributes and collections. Only one instrumentation implementation is allowed in a given object inheritance hierarchy. The value of this attribute must be a callable and will be passed a class object. The callable must return one of: - An instance of an InstrumentationManager or subclass - An object implementing all or some of InstrumentationManager (TODO) - A dictionary of callables, implementing all or some of the above (TODO) - An instance of a ClassManager or subclass This attribute is consulted by SQLAlchemy instrumentation resolution, once the :mod:`sqlalchemy.ext.instrumentation` module has been imported. If custom finders are installed in the global instrumentation_finders list, they may or may not choose to honor this attribute. """ def find_native_user_instrumentation_hook(cls): """Find user-specified instrumentation management for a class.""" return getattr(cls, INSTRUMENTATION_MANAGER, None) instrumentation_finders = [find_native_user_instrumentation_hook] """An extensible sequence of callables which return instrumentation implementations When a class is registered, each callable will be passed a class object. If None is returned, the next finder in the sequence is consulted. Otherwise the return must be an instrumentation factory that follows the same guidelines as sqlalchemy.ext.instrumentation.INSTRUMENTATION_MANAGER. By default, the only finder is find_native_user_instrumentation_hook, which searches for INSTRUMENTATION_MANAGER. If all finders return None, standard ClassManager instrumentation is used. """ class ExtendedInstrumentationRegistry(InstrumentationFactory): """Extends :class:`.InstrumentationFactory` with additional bookkeeping, to accommodate multiple types of class managers. """ _manager_finders = weakref.WeakKeyDictionary() _state_finders = weakref.WeakKeyDictionary() _dict_finders = weakref.WeakKeyDictionary() _extended = False def _locate_extended_factory(self, class_): for finder in instrumentation_finders: factory = finder(class_) if factory is not None: manager = self._extended_class_manager(class_, factory) return manager, factory else: return None, None def _check_conflicts(self, class_, factory): existing_factories = self._collect_management_factories_for(class_).\ difference([factory]) if existing_factories: raise TypeError( "multiple instrumentation implementations specified " "in %s inheritance hierarchy: %r" % ( class_.__name__, list(existing_factories))) def _extended_class_manager(self, class_, factory): manager = factory(class_) if not isinstance(manager, ClassManager): manager = _ClassInstrumentationAdapter(class_, manager) if factory != ClassManager and not self._extended: # somebody invoked a custom ClassManager. # reinstall global "getter" functions with the more # expensive ones. self._extended = True _install_instrumented_lookups() self._manager_finders[class_] = manager.manager_getter() self._state_finders[class_] = manager.state_getter() self._dict_finders[class_] = manager.dict_getter() return manager def _collect_management_factories_for(self, cls): """Return a collection of factories in play or specified for a hierarchy. Traverses the entire inheritance graph of a cls and returns a collection of instrumentation factories for those classes. Factories are extracted from active ClassManagers, if available, otherwise instrumentation_finders is consulted. """ hierarchy = util.class_hierarchy(cls) factories = set() for member in hierarchy: manager = self.manager_of_class(member) if manager is not None: factories.add(manager.factory) else: for finder in instrumentation_finders: factory = finder(member) if factory is not None: break else: factory = None factories.add(factory) factories.discard(None) return factories def unregister(self, class_): if class_ in self._manager_finders: del self._manager_finders[class_] del self._state_finders[class_] del self._dict_finders[class_] super(ExtendedInstrumentationRegistry, self).unregister(class_) def manager_of_class(self, cls): if cls is None: return None try: finder = self._manager_finders.get(cls, _default_manager_getter) except TypeError: # due to weakref lookup on invalid object return None else: return finder(cls) def state_of(self, instance): if instance is None: raise AttributeError("None has no persistent state.") return self._state_finders.get( instance.__class__, _default_state_getter)(instance) def dict_of(self, instance): if instance is None: raise AttributeError("None has no persistent state.") return self._dict_finders.get( instance.__class__, _default_dict_getter)(instance) orm_instrumentation._instrumentation_factory = \ _instrumentation_factory = ExtendedInstrumentationRegistry() orm_instrumentation.instrumentation_finders = instrumentation_finders class InstrumentationManager(object): """User-defined class instrumentation extension. :class:`.InstrumentationManager` can be subclassed in order to change how class instrumentation proceeds. This class exists for the purposes of integration with other object management frameworks which would like to entirely modify the instrumentation methodology of the ORM, and is not intended for regular usage. For interception of class instrumentation events, see :class:`.InstrumentationEvents`. The API for this class should be considered as semi-stable, and may change slightly with new releases. .. versionchanged:: 0.8 :class:`.InstrumentationManager` was moved from :mod:`sqlalchemy.orm.instrumentation` to :mod:`sqlalchemy.ext.instrumentation`. """ # r4361 added a mandatory (cls) constructor to this interface. # given that, perhaps class_ should be dropped from all of these # signatures. def __init__(self, class_): pass def manage(self, class_, manager): setattr(class_, '_default_class_manager', manager) def dispose(self, class_, manager): delattr(class_, '_default_class_manager') def manager_getter(self, class_): def get(cls): return cls._default_class_manager return get def instrument_attribute(self, class_, key, inst): pass def post_configure_attribute(self, class_, key, inst): pass def install_descriptor(self, class_, key, inst): setattr(class_, key, inst) def uninstall_descriptor(self, class_, key): delattr(class_, key) def install_member(self, class_, key, implementation): setattr(class_, key, implementation) def uninstall_member(self, class_, key): delattr(class_, key) def instrument_collection_class(self, class_, key, collection_class): return collections.prepare_instrumentation(collection_class) def get_instance_dict(self, class_, instance): return instance.__dict__ def initialize_instance_dict(self, class_, instance): pass def install_state(self, class_, instance, state): setattr(instance, '_default_state', state) def remove_state(self, class_, instance): delattr(instance, '_default_state') def state_getter(self, class_): return lambda instance: getattr(instance, '_default_state') def dict_getter(self, class_): return lambda inst: self.get_instance_dict(class_, inst) class _ClassInstrumentationAdapter(ClassManager): """Adapts a user-defined InstrumentationManager to a ClassManager.""" def __init__(self, class_, override): self._adapted = override self._get_state = self._adapted.state_getter(class_) self._get_dict = self._adapted.dict_getter(class_) ClassManager.__init__(self, class_) def manage(self): self._adapted.manage(self.class_, self) def dispose(self): self._adapted.dispose(self.class_) def manager_getter(self): return self._adapted.manager_getter(self.class_) def instrument_attribute(self, key, inst, propagated=False): ClassManager.instrument_attribute(self, key, inst, propagated) if not propagated: self._adapted.instrument_attribute(self.class_, key, inst) def post_configure_attribute(self, key): super(_ClassInstrumentationAdapter, self).post_configure_attribute(key) self._adapted.post_configure_attribute(self.class_, key, self[key]) def install_descriptor(self, key, inst): self._adapted.install_descriptor(self.class_, key, inst) def uninstall_descriptor(self, key): self._adapted.uninstall_descriptor(self.class_, key) def install_member(self, key, implementation): self._adapted.install_member(self.class_, key, implementation) def uninstall_member(self, key): self._adapted.uninstall_member(self.class_, key) def instrument_collection_class(self, key, collection_class): return self._adapted.instrument_collection_class( self.class_, key, collection_class) def initialize_collection(self, key, state, factory): delegate = getattr(self._adapted, 'initialize_collection', None) if delegate: return delegate(key, state, factory) else: return ClassManager.initialize_collection(self, key, state, factory) def new_instance(self, state=None): instance = self.class_.__new__(self.class_) self.setup_instance(instance, state) return instance def _new_state_if_none(self, instance): """Install a default InstanceState if none is present. A private convenience method used by the __init__ decorator. """ if self.has_state(instance): return False else: return self.setup_instance(instance) def setup_instance(self, instance, state=None): self._adapted.initialize_instance_dict(self.class_, instance) if state is None: state = self._state_constructor(instance, self) # the given instance is assumed to have no state self._adapted.install_state(self.class_, instance, state) return state def teardown_instance(self, instance): self._adapted.remove_state(self.class_, instance) def has_state(self, instance): try: self._get_state(instance) except orm_exc.NO_STATE: return False else: return True def state_getter(self): return self._get_state def dict_getter(self): return self._get_dict def _install_instrumented_lookups(): """Replace global class/object management functions with ExtendedInstrumentationRegistry implementations, which allow multiple types of class managers to be present, at the cost of performance. This function is called only by ExtendedInstrumentationRegistry and unit tests specific to this behavior. The _reinstall_default_lookups() function can be called after this one to re-establish the default functions. """ _install_lookups( dict( instance_state=_instrumentation_factory.state_of, instance_dict=_instrumentation_factory.dict_of, manager_of_class=_instrumentation_factory.manager_of_class ) ) def _reinstall_default_lookups(): """Restore simplified lookups.""" _install_lookups( dict( instance_state=_default_state_getter, instance_dict=_default_dict_getter, manager_of_class=_default_manager_getter ) ) _instrumentation_factory._extended = False def _install_lookups(lookups): global instance_state, instance_dict, manager_of_class instance_state = lookups['instance_state'] instance_dict = lookups['instance_dict'] manager_of_class = lookups['manager_of_class'] orm_base.instance_state = attributes.instance_state = \ orm_instrumentation.instance_state = instance_state orm_base.instance_dict = attributes.instance_dict = \ orm_instrumentation.instance_dict = instance_dict orm_base.manager_of_class = attributes.manager_of_class = \ orm_instrumentation.manager_of_class = manager_of_class
mit
ModdedPA/android_external_chromium_org
build/android/pylib/instrumentation/test_package.py
61
1121
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Class representing instrumentation test apk and jar.""" import os from pylib.utils import apk_helper import test_jar class TestPackage(test_jar.TestJar): def __init__(self, apk_path, jar_path): test_jar.TestJar.__init__(self, jar_path) if not os.path.exists(apk_path): raise Exception('%s not found, please build it' % apk_path) self._apk_path = apk_path self._apk_name = os.path.splitext(os.path.basename(apk_path))[0] self._package_name = apk_helper.GetPackageName(self._apk_path) def GetApkPath(self): """Returns the absolute path to the APK.""" return self._apk_path def GetApkName(self): """Returns the name of the apk without the suffix.""" return self._apk_name def GetPackageName(self): """Returns the package name of this APK.""" return self._package_name # Override. def Install(self, adb): adb.ManagedInstall(self.GetApkPath(), package_name=self.GetPackageName())
bsd-3-clause
imruahmed/microblog
flask/lib/python2.7/site-packages/sqlalchemy/sql/__init__.py
49
1737
# sql/__init__.py # Copyright (C) 2005-2015 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from .expression import ( Alias, ClauseElement, ColumnCollection, ColumnElement, CompoundSelect, Delete, FromClause, Insert, Join, Select, Selectable, TableClause, Update, alias, and_, asc, between, bindparam, case, cast, collate, column, delete, desc, distinct, except_, except_all, exists, extract, false, False_, func, funcfilter, insert, intersect, intersect_all, join, label, literal, literal_column, modifier, not_, null, or_, outerjoin, outparam, over, select, subquery, table, text, true, True_, tuple_, type_coerce, union, union_all, update, ) from .visitors import ClauseVisitor def __go(lcls): global __all__ from .. import util as _sa_util import inspect as _inspect __all__ = sorted(name for name, obj in lcls.items() if not (name.startswith('_') or _inspect.ismodule(obj))) from .annotation import _prepare_annotations, Annotated from .elements import AnnotatedColumnElement, ClauseList from .selectable import AnnotatedFromClause _prepare_annotations(ColumnElement, AnnotatedColumnElement) _prepare_annotations(FromClause, AnnotatedFromClause) _prepare_annotations(ClauseList, Annotated) _sa_util.dependencies.resolve_all("sqlalchemy.sql") from . import naming __go(locals())
bsd-3-clause
sunny94/temp
sympy/mpmath/tests/test_ode.py
39
1834
#from sympy.mpmath.calculus import ODE_step_euler, ODE_step_rk4, odeint, arange from sympy.mpmath import odefun, cos, sin, mpf, sinc, mp ''' solvers = [ODE_step_euler, ODE_step_rk4] def test_ode1(): """ Let's solve: x'' + w**2 * x = 0 i.e. x1 = x, x2 = x1': x1' = x2 x2' = -x1 """ def derivs((x1, x2), t): return x2, -x1 for solver in solvers: t = arange(0, 3.1415926, 0.005) sol = odeint(derivs, (0., 1.), t, solver) x1 = [a[0] for a in sol] x2 = [a[1] for a in sol] # the result is x1 = sin(t), x2 = cos(t) # let's just check the end points for t = pi assert abs(x1[-1]) < 1e-2 assert abs(x2[-1] - (-1)) < 1e-2 def test_ode2(): """ Let's solve: x' - x = 0 i.e. x = exp(x) """ def derivs((x), t): return x for solver in solvers: t = arange(0, 1, 1e-3) sol = odeint(derivs, (1.,), t, solver) x = [a[0] for a in sol] # the result is x = exp(t) # let's just check the end point for t = 1, i.e. x = e assert abs(x[-1] - 2.718281828) < 1e-2 ''' def test_odefun_rational(): mp.dps = 15 # A rational function f = lambda t: 1/(1+mpf(t)**2) g = odefun(lambda x, y: [-2*x*y[0]**2], 0, [f(0)]) assert f(2).ae(g(2)[0]) def test_odefun_sinc_large(): mp.dps = 15 # Sinc function; test for large x f = sinc g = odefun(lambda x, y: [(cos(x)-y[0])/x], 1, [f(1)], tol=0.01, degree=5) assert abs(f(100) - g(100)[0])/f(100) < 0.01 def test_odefun_harmonic(): mp.dps = 15 # Harmonic oscillator f = odefun(lambda x, y: [-y[1], y[0]], 0, [1, 0]) for x in [0, 1, 2.5, 8, 3.7]: # we go back to 3.7 to check caching c, s = f(x) assert c.ae(cos(x)) assert s.ae(sin(x))
bsd-3-clause
llhe/tensorflow
tensorflow/python/training/basic_session_run_hooks.py
21
27030
# 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. # ============================================================================== """Some common SessionRunHook classes. @@LoggingTensorHook @@StopAtStepHook @@CheckpointSaverHook @@StepCounterHook @@NanLossDuringTrainingError @@NanTensorHook @@SummarySaverHook @@GlobalStepWaiterHook """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time import numpy as np import six from tensorflow.core.framework.summary_pb2 import Summary from tensorflow.core.util.event_pb2 import SessionLog from tensorflow.python.framework import meta_graph from tensorflow.python.framework import ops from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training import saver as saver_lib from tensorflow.python.training import session_run_hook from tensorflow.python.training import training_util from tensorflow.python.training.session_run_hook import SessionRunArgs from tensorflow.python.training.summary_io import SummaryWriterCache class _HookTimer(object): """Base timer for determining when Hooks should trigger. Should not be instantiated directly. """ def __init__(self): pass def reset(self): """Resets the timer.""" pass def should_trigger_for_step(self, step): """Return true if the timer should trigger for the specified step.""" raise NotImplementedError def update_last_triggered_step(self, step): """Update the last triggered time and step number. Args: step: The current step. Returns: A pair `(elapsed_time, elapsed_steps)`, where `elapsed_time` is the number of seconds between the current trigger and the last one (a float), and `elapsed_steps` is the number of steps between the current trigger and the last one. Both values will be set to `None` on the first trigger. """ raise NotImplementedError def last_triggered_step(self): """Returns the last triggered time step or None if never triggered.""" raise NotImplementedError class SecondOrStepTimer(_HookTimer): """Timer that triggers at most once every N seconds or once every N steps. """ def __init__(self, every_secs=None, every_steps=None): self.reset() self._every_secs = every_secs self._every_steps = every_steps if self._every_secs is None and self._every_steps is None: raise ValueError("Either every_secs or every_steps should be provided.") if (self._every_secs is not None) and (self._every_steps is not None): raise ValueError("Can not provide both every_secs and every_steps.") super(SecondOrStepTimer, self).__init__() def reset(self): self._last_triggered_step = None self._last_triggered_time = None def should_trigger_for_step(self, step): """Return true if the timer should trigger for the specified step. Args: step: Training step to trigger on. Returns: True if the difference between the current time and the time of the last trigger exceeds `every_secs`, or if the difference between the current step and the last triggered step exceeds `every_steps`. False otherwise. """ if self._last_triggered_step is None: return True if self._last_triggered_step == step: return False if self._every_secs is not None: if time.time() >= self._last_triggered_time + self._every_secs: return True if self._every_steps is not None: if step >= self._last_triggered_step + self._every_steps: return True return False def update_last_triggered_step(self, step): current_time = time.time() if self._last_triggered_time is None: elapsed_secs = None elapsed_steps = None else: elapsed_secs = current_time - self._last_triggered_time elapsed_steps = step - self._last_triggered_step self._last_triggered_time = current_time self._last_triggered_step = step return (elapsed_secs, elapsed_steps) def last_triggered_step(self): return self._last_triggered_step class NeverTriggerTimer(_HookTimer): """Timer that never triggers.""" def should_trigger_for_step(self, step): _ = step return False def update_last_triggered_step(self, step): _ = step return (None, None) def last_triggered_step(self): return None class LoggingTensorHook(session_run_hook.SessionRunHook): """Prints the given tensors every N local steps, every N seconds, or at end. The tensors will be printed to the log, with `INFO` severity. If you are not seeing the logs, you might want to add the following line after your imports: ```python tf.logging.set_verbosity(tf.logging.INFO) ``` Note that if `at_end` is True, `tensors` should not include any tensor whose evaluation produces a side effect such as consuming additional inputs. """ def __init__(self, tensors, every_n_iter=None, every_n_secs=None, at_end=False, formatter=None): """Initializes a `LoggingTensorHook`. Args: tensors: `dict` that maps string-valued tags to tensors/tensor names, or `iterable` of tensors/tensor names. every_n_iter: `int`, print the values of `tensors` once every N local steps taken on the current worker. every_n_secs: `int` or `float`, print the values of `tensors` once every N seconds. Exactly one of `every_n_iter` and `every_n_secs` should be provided. at_end: `bool` specifying whether to print the values of `tensors` at the end of the run. formatter: function, takes dict of `tag`->`Tensor` and returns a string. If `None` uses default printing all tensors. Raises: ValueError: if `every_n_iter` is non-positive. """ only_log_at_end = ( at_end and (every_n_iter is None) and (every_n_secs is None)) if (not only_log_at_end and (every_n_iter is None) == (every_n_secs is None)): raise ValueError( "either at_end and/or exactly one of every_n_iter and every_n_secs " "must be provided.") if every_n_iter is not None and every_n_iter <= 0: raise ValueError("invalid every_n_iter=%s." % every_n_iter) if not isinstance(tensors, dict): self._tag_order = tensors tensors = {item: item for item in tensors} else: self._tag_order = tensors.keys() self._tensors = tensors self._formatter = formatter self._timer = ( NeverTriggerTimer() if only_log_at_end else SecondOrStepTimer(every_secs=every_n_secs, every_steps=every_n_iter)) self._log_at_end = at_end def begin(self): self._timer.reset() self._iter_count = 0 # Convert names to tensors if given self._current_tensors = {tag: _as_graph_element(tensor) for (tag, tensor) in self._tensors.items()} def before_run(self, run_context): # pylint: disable=unused-argument self._should_trigger = self._timer.should_trigger_for_step(self._iter_count) if self._should_trigger: return SessionRunArgs(self._current_tensors) else: return None def _log_tensors(self, tensor_values): original = np.get_printoptions() np.set_printoptions(suppress=True) elapsed_secs, _ = self._timer.update_last_triggered_step(self._iter_count) if self._formatter: logging.info(self._formatter(tensor_values)) else: stats = [] for tag in self._tag_order: stats.append("%s = %s" % (tag, tensor_values[tag])) if elapsed_secs is not None: logging.info("%s (%.3f sec)", ", ".join(stats), elapsed_secs) else: logging.info("%s", ", ".join(stats)) np.set_printoptions(**original) def after_run(self, run_context, run_values): _ = run_context if self._should_trigger: self._log_tensors(run_values.results) self._iter_count += 1 def end(self, session): if self._log_at_end: values = session.run(self._current_tensors) self._log_tensors(values) class StopAtStepHook(session_run_hook.SessionRunHook): """Hook that requests stop at a specified step.""" def __init__(self, num_steps=None, last_step=None): """Initializes a `StopAtStepHook`. This hook requests stop after either a number of steps have been executed or a last step has been reached. Only one of the two options can be specified. if `num_steps` is specified, it indicates the number of steps to execute after `begin()` is called. If instead `last_step` is specified, it indicates the last step we want to execute, as passed to the `after_run()` call. Args: num_steps: Number of steps to execute. last_step: Step after which to stop. Raises: ValueError: If one of the arguments is invalid. """ if num_steps is None and last_step is None: raise ValueError("One of num_steps or last_step must be specified.") if num_steps is not None and last_step is not None: raise ValueError("Only one of num_steps or last_step can be specified.") self._num_steps = num_steps self._last_step = last_step def begin(self): self._global_step_tensor = training_util.get_global_step() if self._global_step_tensor is None: raise RuntimeError("Global step should be created to use StopAtStepHook.") def after_create_session(self, session, coord): if self._last_step is None: global_step = session.run(self._global_step_tensor) self._last_step = global_step + self._num_steps def before_run(self, run_context): # pylint: disable=unused-argument return SessionRunArgs(self._global_step_tensor) def after_run(self, run_context, run_values): global_step = run_values.results if global_step >= self._last_step: run_context.request_stop() class CheckpointSaverListener(object): """Interface for listeners that take action before or after checkpoint save. `CheckpointSaverListener` triggers only in steps when `CheckpointSaverHook` is triggered, and provides callbacks at the following points: - before using the session - before each call to `Saver.save()` - after each call to `Saver.save()` - at the end of session To use a listener, implement a class and pass the listener to a `CheckpointSaverHook`, as in this example: ```python class ExampleCheckpointSaverListerner(CheckpointSaverListener): def begin(self): # You can add ops to the graph here. print('Starting the session.') self.your_tensor = ... def before_save(self, session, global_step_value): print('About to write a checkpoint') def after_save(self, session, global_step_value): print('Done writing checkpoint.') def end(self, session, global_step_value): print('Done with the session.') ... listener = ExampleCheckpointSaverListerner() saver_hook = tf.train.CheckpointSaverHook( checkpoint_dir, listeners=[listener]) with tf.train.MonitoredTrainingSession(chief_only_hooks=[saver_hook]): ... ``` A `CheckpointSaverListener` may simply take some action after every checkpoint save. It is also possible for the listener to use its own schedule to act less frequently, e.g. based on global_step_value. In this case, implementors should implement the `end()` method to handle actions related to the last checkpoint save. But the listener should not act twice if `after_save()` already handled this last checkpoint save. """ def begin(self): pass def before_save(self, session, global_step_value): pass def after_save(self, session, global_step_value): pass def end(self, session, global_step_value): pass class CheckpointSaverHook(session_run_hook.SessionRunHook): """Saves checkpoints every N steps or seconds.""" def __init__(self, checkpoint_dir, save_secs=None, save_steps=None, saver=None, checkpoint_basename="model.ckpt", scaffold=None, listeners=None): """Initializes a `CheckpointSaverHook`. Args: checkpoint_dir: `str`, base directory for the checkpoint files. save_secs: `int`, save every N secs. save_steps: `int`, save every N steps. saver: `Saver` object, used for saving. checkpoint_basename: `str`, base name for the checkpoint files. scaffold: `Scaffold`, use to get saver object. listeners: List of `CheckpointSaverListener` subclass instances. Used for callbacks that run immediately before or after this hook saves the checkpoint. Raises: ValueError: One of `save_steps` or `save_secs` should be set. ValueError: Exactly one of saver or scaffold should be set. """ logging.info("Create CheckpointSaverHook.") if saver is not None and scaffold is not None: raise ValueError("You cannot provide both saver and scaffold.") if saver is None and scaffold is None: saver = saver_lib._get_saver_or_default() # pylint: disable=protected-access self._saver = saver self._checkpoint_dir = checkpoint_dir self._save_path = os.path.join(checkpoint_dir, checkpoint_basename) self._scaffold = scaffold self._timer = SecondOrStepTimer(every_secs=save_secs, every_steps=save_steps) self._listeners = listeners or [] def begin(self): self._summary_writer = SummaryWriterCache.get(self._checkpoint_dir) self._global_step_tensor = training_util.get_global_step() if self._global_step_tensor is None: raise RuntimeError( "Global step should be created to use CheckpointSaverHook.") for l in self._listeners: l.begin() def before_run(self, run_context): # pylint: disable=unused-argument if self._timer.last_triggered_step() is None: # We do write graph and saver_def at the first call of before_run. # We cannot do this in begin, since we let other hooks to change graph and # add variables in begin. Graph is finalized after all begin calls. training_util.write_graph( ops.get_default_graph().as_graph_def(add_shapes=True), self._checkpoint_dir, "graph.pbtxt") saver_def = self._get_saver().saver_def if self._get_saver() else None graph = ops.get_default_graph() meta_graph_def = meta_graph.create_meta_graph_def( graph_def=graph.as_graph_def(add_shapes=True), saver_def=saver_def) self._summary_writer.add_graph(graph) self._summary_writer.add_meta_graph(meta_graph_def) return SessionRunArgs(self._global_step_tensor) def after_run(self, run_context, run_values): global_step = run_values.results if self._timer.should_trigger_for_step(global_step): self._timer.update_last_triggered_step(global_step) self._save(global_step, run_context.session) def end(self, session): last_step = session.run(training_util.get_global_step()) if last_step != self._timer.last_triggered_step(): self._save(last_step, session) for l in self._listeners: l.end(session, last_step) def _save(self, step, session): """Saves the latest checkpoint.""" logging.info("Saving checkpoints for %d into %s.", step, self._save_path) for l in self._listeners: l.before_save(session, step) self._get_saver().save(session, self._save_path, global_step=step) self._summary_writer.add_session_log( SessionLog( status=SessionLog.CHECKPOINT, checkpoint_path=self._save_path), step) for l in self._listeners: l.after_save(session, step) def _get_saver(self): if self._saver is not None: return self._saver elif self._scaffold is not None: return self._scaffold.saver return None class StepCounterHook(session_run_hook.SessionRunHook): """Hook that counts steps per second.""" def __init__(self, every_n_steps=100, every_n_secs=None, output_dir=None, summary_writer=None): if (every_n_steps is None) == (every_n_secs is None): raise ValueError( "exactly one of every_n_steps and every_n_secs should be provided.") self._timer = SecondOrStepTimer(every_steps=every_n_steps, every_secs=every_n_secs) self._summary_writer = summary_writer self._output_dir = output_dir def begin(self): if self._summary_writer is None and self._output_dir: self._summary_writer = SummaryWriterCache.get(self._output_dir) self._global_step_tensor = training_util.get_global_step() if self._global_step_tensor is None: raise RuntimeError( "Global step should be created to use StepCounterHook.") self._summary_tag = self._global_step_tensor.op.name + "/sec" def before_run(self, run_context): # pylint: disable=unused-argument return SessionRunArgs(self._global_step_tensor) def after_run(self, run_context, run_values): _ = run_context global_step = run_values.results if self._timer.should_trigger_for_step(global_step): elapsed_time, elapsed_steps = self._timer.update_last_triggered_step( global_step) if elapsed_time is not None: steps_per_sec = elapsed_steps / elapsed_time if self._summary_writer is not None: summary = Summary(value=[Summary.Value( tag=self._summary_tag, simple_value=steps_per_sec)]) self._summary_writer.add_summary(summary, global_step) logging.info("%s: %g", self._summary_tag, steps_per_sec) class NanLossDuringTrainingError(RuntimeError): def __str__(self): return "NaN loss during training." class NanTensorHook(session_run_hook.SessionRunHook): """Monitors the loss tensor and stops training if loss is NaN. Can either fail with exception or just stop training. """ def __init__(self, loss_tensor, fail_on_nan_loss=True): """Initializes a `NanTensorHook`. Args: loss_tensor: `Tensor`, the loss tensor. fail_on_nan_loss: `bool`, whether to raise exception when loss is NaN. """ self._loss_tensor = loss_tensor self._fail_on_nan_loss = fail_on_nan_loss def before_run(self, run_context): # pylint: disable=unused-argument return SessionRunArgs(self._loss_tensor) def after_run(self, run_context, run_values): if np.isnan(run_values.results): failure_message = "Model diverged with loss = NaN." if self._fail_on_nan_loss: logging.error(failure_message) raise NanLossDuringTrainingError else: logging.warning(failure_message) # We don't raise an error but we request stop without an exception. run_context.request_stop() class SummarySaverHook(session_run_hook.SessionRunHook): """Saves summaries every N steps.""" def __init__(self, save_steps=None, save_secs=None, output_dir=None, summary_writer=None, scaffold=None, summary_op=None): """Initializes a `SummarySaverHook`. Args: save_steps: `int`, save summaries every N steps. Exactly one of `save_secs` and `save_steps` should be set. save_secs: `int`, save summaries every N seconds. output_dir: `string`, the directory to save the summaries to. Only used if no `summary_writer` is supplied. summary_writer: `SummaryWriter`. If `None` and an `output_dir` was passed, one will be created accordingly. scaffold: `Scaffold` to get summary_op if it's not provided. summary_op: `Tensor` of type `string` containing the serialized `Summary` protocol buffer or a list of `Tensor`. They are most likely an output by TF summary methods like `tf.summary.scalar` or `tf.summary.merge_all`. It can be passed in as one tensor; if more than one, they must be passed in as a list. Raises: ValueError: Exactly one of scaffold or summary_op should be set. """ if ((scaffold is None and summary_op is None) or (scaffold is not None and summary_op is not None)): raise ValueError( "Exactly one of scaffold or summary_op must be provided.") self._summary_op = summary_op self._summary_writer = summary_writer self._output_dir = output_dir self._scaffold = scaffold self._timer = SecondOrStepTimer(every_secs=save_secs, every_steps=save_steps) # TODO(mdan): Throw an error if output_dir and summary_writer are None. def begin(self): if self._summary_writer is None and self._output_dir: self._summary_writer = SummaryWriterCache.get(self._output_dir) self._next_step = None self._global_step_tensor = training_util.get_global_step() if self._global_step_tensor is None: raise RuntimeError( "Global step should be created to use SummarySaverHook.") def before_run(self, run_context): # pylint: disable=unused-argument self._request_summary = ( self._next_step is None or self._timer.should_trigger_for_step(self._next_step)) requests = {"global_step": self._global_step_tensor} if self._request_summary: if self._get_summary_op() is not None: requests["summary"] = self._get_summary_op() return SessionRunArgs(requests) def after_run(self, run_context, run_values): _ = run_context if not self._summary_writer: return global_step = run_values.results["global_step"] if self._next_step is None: self._summary_writer.add_session_log( SessionLog(status=SessionLog.START), global_step) if self._request_summary: self._timer.update_last_triggered_step(global_step) if "summary" in run_values.results: for summary in run_values.results["summary"]: self._summary_writer.add_summary(summary, global_step) self._next_step = global_step + 1 def end(self, session=None): if self._summary_writer: self._summary_writer.flush() def _get_summary_op(self): """Fetches the summary op either from self._summary_op or self._scaffold. Returns: Returns a list of summary `Tensor`. """ summary_op = None if self._summary_op is not None: summary_op = self._summary_op elif self._scaffold.summary_op is not None: summary_op = self._scaffold.summary_op if summary_op is None: return None if not isinstance(summary_op, list): return [summary_op] return summary_op class GlobalStepWaiterHook(session_run_hook.SessionRunHook): """Delays execution until global step reaches `wait_until_step`. This hook delays execution until global step reaches to `wait_until_step`. It is used to gradually start workers in distributed settings. One example usage would be setting `wait_until_step=int(K*log(task_id+1))` assuming that task_id=0 is the chief. """ def __init__(self, wait_until_step): """Initializes a `GlobalStepWaiterHook`. Args: wait_until_step: an `int` shows until which global step should we wait. """ self._wait_until_step = wait_until_step def begin(self): self._worker_is_started = False self._global_step_tensor = training_util.get_global_step() if self._global_step_tensor is None: raise RuntimeError( "Global step should be created to use _GlobalStepWaiterHook.") def before_run(self, run_context): if self._worker_is_started: return None if self._wait_until_step <= 0: self._worker_is_started = True return None logging.info("Waiting for global step %d before starting training.", self._wait_until_step) last_logged_step = 0 while True: current_step = run_context.session.run(self._global_step_tensor) if current_step >= self._wait_until_step: self._worker_is_started = True return None if current_step - last_logged_step > 1000: logging.info("Waiting for global step %d before starting training. " "Current step is %d.", self._wait_until_step, current_step) last_logged_step = current_step time.sleep(0.5) class FinalOpsHook(session_run_hook.SessionRunHook): """A hook which evaluates `Tensors` at the end of a session.""" def __init__(self, final_ops, final_ops_feed_dict=None): """Initializes `FinalOpHook` with ops to run at the end of the session. Args: final_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names to `Tensors`. final_ops_feed_dict: A feed dictionary to use when running `final_ops_dict`. """ self._final_ops = final_ops self._final_ops_feed_dict = final_ops_feed_dict self._final_ops_values = None @property def final_ops_values(self): return self._final_ops_values def end(self, session): if self._final_ops is not None: self._final_ops_values = session.run(self._final_ops, feed_dict=self._final_ops_feed_dict) class FeedFnHook(session_run_hook.SessionRunHook): """Runs `feed_fn` and sets the `feed_dict` accordingly.""" def __init__(self, feed_fn): """Initializes a `FeedFnHook`. Args: feed_fn: function that takes no arguments and returns `dict` of `Tensor` to feed. """ self.feed_fn = feed_fn def before_run(self, run_context): # pylint: disable=unused-argument return session_run_hook.SessionRunArgs( fetches=None, feed_dict=self.feed_fn()) def _as_graph_element(obj): """Retrieves Graph element.""" graph = ops.get_default_graph() if not isinstance(obj, six.string_types): if not hasattr(obj, "graph") or obj.graph != graph: raise ValueError("Passed %s should have graph attribute that is equal " "to current graph %s." % (obj, graph)) return obj if ":" in obj: element = graph.as_graph_element(obj) else: element = graph.as_graph_element(obj + ":0") # Check that there is no :1 (e.g. it's single output). try: graph.as_graph_element(obj + ":1") except (KeyError, ValueError): pass else: raise ValueError("Name %s is ambiguous, " "as this `Operation` has multiple outputs " "(at least 2)." % obj) return element
apache-2.0
grueni75/GeoDiscoverer
Source/Platform/Target/Android/core/src/main/jni/libxml2-2.9.2/python/tests/reader.py
35
12521
#!/usr/bin/python -u # -*- coding: ISO-8859-1 -*- # # this tests the basic APIs of the XmlTextReader interface # import libxml2 import sys try: import StringIO str_io = StringIO.StringIO except: import io str_io = io.StringIO # Memory debug specific libxml2.debugMemory(1) f = str_io("""<a><b b1="b1"/><c>content of c</c></a>""") input = libxml2.inputBuffer(f) reader = input.newTextReader("test1") ret = reader.Read() if ret != 1: print("test1: Error reading to first element") sys.exit(1) if reader.Name() != "a" or reader.IsEmptyElement() != 0 or \ reader.NodeType() != 1 or reader.HasAttributes() != 0: print("test1: Error reading the first element") sys.exit(1) ret = reader.Read() if ret != 1: print("test1: Error reading to second element") sys.exit(1) if reader.Name() != "b" or reader.IsEmptyElement() != 1 or \ reader.NodeType() != 1 or reader.HasAttributes() != 1: print("test1: Error reading the second element") sys.exit(1) ret = reader.Read() if ret != 1: print("test1: Error reading to third element") sys.exit(1) if reader.Name() != "c" or reader.IsEmptyElement() != 0 or \ reader.NodeType() != 1 or reader.HasAttributes() != 0: print("test1: Error reading the third element") sys.exit(1) ret = reader.Read() if ret != 1: print("test1: Error reading to text node") sys.exit(1) if reader.Name() != "#text" or reader.IsEmptyElement() != 0 or \ reader.NodeType() != 3 or reader.HasAttributes() != 0 or \ reader.Value() != "content of c": print("test1: Error reading the text node") sys.exit(1) ret = reader.Read() if ret != 1: print("test1: Error reading to end of third element") sys.exit(1) if reader.Name() != "c" or reader.IsEmptyElement() != 0 or \ reader.NodeType() != 15 or reader.HasAttributes() != 0: print("test1: Error reading the end of third element") sys.exit(1) ret = reader.Read() if ret != 1: print("test1: Error reading to end of first element") sys.exit(1) if reader.Name() != "a" or reader.IsEmptyElement() != 0 or \ reader.NodeType() != 15 or reader.HasAttributes() != 0: print("test1: Error reading the end of first element") sys.exit(1) ret = reader.Read() if ret != 0: print("test1: Error reading to end of document") sys.exit(1) # # example from the XmlTextReader docs # f = str_io("""<test xmlns:dt="urn:datatypes" dt:type="int"/>""") input = libxml2.inputBuffer(f) reader = input.newTextReader("test2") ret = reader.Read() if ret != 1: print("Error reading test element") sys.exit(1) if reader.GetAttributeNo(0) != "urn:datatypes" or \ reader.GetAttributeNo(1) != "int" or \ reader.GetAttributeNs("type", "urn:datatypes") != "int" or \ reader.GetAttribute("dt:type") != "int": print("error reading test attributes") sys.exit(1) # # example from the XmlTextReader docs # f = str_io("""<root xmlns:a="urn:456"> <item> <ref href="a:b"/> </item> </root>""") input = libxml2.inputBuffer(f) reader = input.newTextReader("test3") ret = reader.Read() while ret == 1: if reader.Name() == "ref": if reader.LookupNamespace("a") != "urn:456": print("error resolving namespace prefix") sys.exit(1) break ret = reader.Read() if ret != 1: print("Error finding the ref element") sys.exit(1) # # Home made example for the various attribute access functions # f = str_io("""<testattr xmlns="urn:1" xmlns:a="urn:2" b="b" a:b="a:b"/>""") input = libxml2.inputBuffer(f) reader = input.newTextReader("test4") ret = reader.Read() if ret != 1: print("Error reading the testattr element") sys.exit(1) # # Attribute exploration by index # if reader.MoveToAttributeNo(0) != 1: print("Failed moveToAttribute(0)") sys.exit(1) if reader.Value() != "urn:1": print("Failed to read attribute(0)") sys.exit(1) if reader.Name() != "xmlns": print("Failed to read attribute(0) name") sys.exit(1) if reader.MoveToAttributeNo(1) != 1: print("Failed moveToAttribute(1)") sys.exit(1) if reader.Value() != "urn:2": print("Failed to read attribute(1)") sys.exit(1) if reader.Name() != "xmlns:a": print("Failed to read attribute(1) name") sys.exit(1) if reader.MoveToAttributeNo(2) != 1: print("Failed moveToAttribute(2)") sys.exit(1) if reader.Value() != "b": print("Failed to read attribute(2)") sys.exit(1) if reader.Name() != "b": print("Failed to read attribute(2) name") sys.exit(1) if reader.MoveToAttributeNo(3) != 1: print("Failed moveToAttribute(3)") sys.exit(1) if reader.Value() != "a:b": print("Failed to read attribute(3)") sys.exit(1) if reader.Name() != "a:b": print("Failed to read attribute(3) name") sys.exit(1) # # Attribute exploration by name # if reader.MoveToAttribute("xmlns") != 1: print("Failed moveToAttribute('xmlns')") sys.exit(1) if reader.Value() != "urn:1": print("Failed to read attribute('xmlns')") sys.exit(1) if reader.MoveToAttribute("xmlns:a") != 1: print("Failed moveToAttribute('xmlns')") sys.exit(1) if reader.Value() != "urn:2": print("Failed to read attribute('xmlns:a')") sys.exit(1) if reader.MoveToAttribute("b") != 1: print("Failed moveToAttribute('b')") sys.exit(1) if reader.Value() != "b": print("Failed to read attribute('b')") sys.exit(1) if reader.MoveToAttribute("a:b") != 1: print("Failed moveToAttribute('a:b')") sys.exit(1) if reader.Value() != "a:b": print("Failed to read attribute('a:b')") sys.exit(1) if reader.MoveToAttributeNs("b", "urn:2") != 1: print("Failed moveToAttribute('b', 'urn:2')") sys.exit(1) if reader.Value() != "a:b": print("Failed to read attribute('b', 'urn:2')") sys.exit(1) # # Go back and read in sequence # if reader.MoveToElement() != 1: print("Failed to move back to element") sys.exit(1) if reader.MoveToFirstAttribute() != 1: print("Failed to move to first attribute") sys.exit(1) if reader.Value() != "urn:1": print("Failed to read attribute(0)") sys.exit(1) if reader.Name() != "xmlns": print("Failed to read attribute(0) name") sys.exit(1) if reader.MoveToNextAttribute() != 1: print("Failed to move to next attribute") sys.exit(1) if reader.Value() != "urn:2": print("Failed to read attribute(1)") sys.exit(1) if reader.Name() != "xmlns:a": print("Failed to read attribute(1) name") sys.exit(1) if reader.MoveToNextAttribute() != 1: print("Failed to move to next attribute") sys.exit(1) if reader.Value() != "b": print("Failed to read attribute(2)") sys.exit(1) if reader.Name() != "b": print("Failed to read attribute(2) name") sys.exit(1) if reader.MoveToNextAttribute() != 1: print("Failed to move to next attribute") sys.exit(1) if reader.Value() != "a:b": print("Failed to read attribute(3)") sys.exit(1) if reader.Name() != "a:b": print("Failed to read attribute(3) name") sys.exit(1) if reader.MoveToNextAttribute() != 0: print("Failed to detect last attribute") sys.exit(1) # # a couple of tests for namespace nodes # f = str_io("""<a xmlns="http://example.com/foo"/>""") input = libxml2.inputBuffer(f) reader = input.newTextReader("test6") ret = reader.Read() if ret != 1: print("test6: failed to Read()") sys.exit(1) ret = reader.MoveToFirstAttribute() if ret != 1: print("test6: failed to MoveToFirstAttribute()") sys.exit(1) if reader.NamespaceUri() != "http://www.w3.org/2000/xmlns/" or \ reader.LocalName() != "xmlns" or reader.Name() != "xmlns" or \ reader.Value() != "http://example.com/foo" or reader.NodeType() != 2: print("test6: failed to read the namespace node") sys.exit(1) f = str_io("""<a xmlns:prefix="http://example.com/foo"/>""") input = libxml2.inputBuffer(f) reader = input.newTextReader("test7") ret = reader.Read() if ret != 1: print("test7: failed to Read()") sys.exit(1) ret = reader.MoveToFirstAttribute() if ret != 1: print("test7: failed to MoveToFirstAttribute()") sys.exit(1) if reader.NamespaceUri() != "http://www.w3.org/2000/xmlns/" or \ reader.LocalName() != "prefix" or reader.Name() != "xmlns:prefix" or \ reader.Value() != "http://example.com/foo" or reader.NodeType() != 2: print("test7: failed to read the namespace node") sys.exit(1) # # Test for a limit case: # f = str_io("""<a/>""") input = libxml2.inputBuffer(f) reader = input.newTextReader("test8") ret = reader.Read() if ret != 1: print("test8: failed to read the node") sys.exit(1) if reader.Name() != "a" or reader.IsEmptyElement() != 1: print("test8: failed to analyze the node") sys.exit(1) ret = reader.Read() if ret != 0: print("test8: failed to detect the EOF") sys.exit(1) # # Another test provided by Stéphane Bidoul and checked with C# # def tst_reader(s): f = str_io(s) input = libxml2.inputBuffer(f) reader = input.newTextReader("tst") res = "" while reader.Read(): res=res + "%s (%s) [%s] %d %d\n" % (reader.NodeType(),reader.Name(), reader.Value(), reader.IsEmptyElement(), reader.Depth()) if reader.NodeType() == 1: # Element while reader.MoveToNextAttribute(): res = res + "-- %s (%s) [%s] %d %d\n" % (reader.NodeType(), reader.Name(),reader.Value(), reader.IsEmptyElement(), reader.Depth()) return res doc="""<a><b b1="b1"/><c>content of c</c></a>""" expect="""1 (a) [None] 0 0 1 (b) [None] 1 1 -- 2 (b1) [b1] 0 2 1 (c) [None] 0 1 3 (#text) [content of c] 0 2 15 (c) [None] 0 1 15 (a) [None] 0 0 """ res = tst_reader(doc) if res != expect: print("test5 failed") print(res) sys.exit(1) doc="""<test><b/><c/></test>""" expect="""1 (test) [None] 0 0 1 (b) [None] 1 1 1 (c) [None] 1 1 15 (test) [None] 0 0 """ res = tst_reader(doc) if res != expect: print("test9 failed") print(res) sys.exit(1) doc="""<a><b>bbb</b><c>ccc</c></a>""" expect="""1 (a) [None] 0 0 1 (b) [None] 0 1 3 (#text) [bbb] 0 2 15 (b) [None] 0 1 1 (c) [None] 0 1 3 (#text) [ccc] 0 2 15 (c) [None] 0 1 15 (a) [None] 0 0 """ res = tst_reader(doc) if res != expect: print("test10 failed") print(res) sys.exit(1) doc="""<test a="a"/>""" expect="""1 (test) [None] 1 0 -- 2 (a) [a] 0 1 """ res = tst_reader(doc) if res != expect: print("test11 failed") print(res) sys.exit(1) doc="""<test><a>aaa</a><b/></test>""" expect="""1 (test) [None] 0 0 1 (a) [None] 0 1 3 (#text) [aaa] 0 2 15 (a) [None] 0 1 1 (b) [None] 1 1 15 (test) [None] 0 0 """ res = tst_reader(doc) if res != expect: print("test12 failed") print(res) sys.exit(1) doc="""<test><p></p></test>""" expect="""1 (test) [None] 0 0 1 (p) [None] 0 1 15 (p) [None] 0 1 15 (test) [None] 0 0 """ res = tst_reader(doc) if res != expect: print("test13 failed") print(res) sys.exit(1) doc="""<p></p>""" expect="""1 (p) [None] 0 0 15 (p) [None] 0 0 """ res = tst_reader(doc) if res != expect: print("test14 failed") print(res) sys.exit(1) # # test from bug #108801 # doc="""<?xml version="1.0" standalone="no"?> <!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN" "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" [ ]> <article> xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx </article> """ expect="""10 (article) [None] 0 0 1 (article) [None] 0 0 3 (#text) [ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ] 0 1 15 (article) [None] 0 0 """ res = tst_reader(doc) if res != expect: print("test15 failed") print(res) sys.exit(1) # # cleanup for memory allocation counting # del f del input del reader # Memory debug specific libxml2.cleanupParser() if libxml2.debugMemory(1) == 0: print("OK") else: print("Memory leak %d bytes" % (libxml2.debugMemory(1))) libxml2.dumpMemory()
gpl-3.0
viki9698/jizhanggroup
django/contrib/auth/tests/basic.py
95
8948
# -*- encoding: utf-8 -*- from __future__ import unicode_literals import locale from django.contrib.auth import get_user_model from django.contrib.auth.management.commands import createsuperuser from django.contrib.auth.models import User, AnonymousUser from django.contrib.auth.tests.custom_user import CustomUser from django.contrib.auth.tests.utils import skipIfCustomUser from django.core.exceptions import ImproperlyConfigured from django.core.management import call_command from django.test import TestCase from django.test.utils import override_settings from django.utils.encoding import force_str from django.utils.six import binary_type, PY3, StringIO def mock_inputs(inputs): """ Decorator to temporarily replace input/getpass to allow interactive createsuperuser. """ def inner(test_func): def wrapped(*args): class mock_getpass: @staticmethod def getpass(prompt=b'Password: ', stream=None): if not PY3: # getpass on Windows only supports prompt as bytestring (#19807) assert isinstance(prompt, binary_type) return inputs['password'] def mock_input(prompt): # prompt should be encoded in Python 2. This line will raise an # Exception if prompt contains unencoded non-ascii on Python 2. prompt = str(prompt) assert str('__proxy__') not in prompt response = '' for key, val in inputs.items(): if force_str(key) in prompt.lower(): response = val break return response old_getpass = createsuperuser.getpass old_input = createsuperuser.input createsuperuser.getpass = mock_getpass createsuperuser.input = mock_input try: test_func(*args) finally: createsuperuser.getpass = old_getpass createsuperuser.input = old_input return wrapped return inner @skipIfCustomUser class BasicTestCase(TestCase): def test_user(self): "Check that users can be created and can set their password" u = User.objects.create_user('testuser', '[email protected]', 'testpw') self.assertTrue(u.has_usable_password()) self.assertFalse(u.check_password('bad')) self.assertTrue(u.check_password('testpw')) # Check we can manually set an unusable password u.set_unusable_password() u.save() self.assertFalse(u.check_password('testpw')) self.assertFalse(u.has_usable_password()) u.set_password('testpw') self.assertTrue(u.check_password('testpw')) u.set_password(None) self.assertFalse(u.has_usable_password()) # Check authentication/permissions self.assertTrue(u.is_authenticated()) self.assertFalse(u.is_staff) self.assertTrue(u.is_active) self.assertFalse(u.is_superuser) # Check API-based user creation with no password u2 = User.objects.create_user('testuser2', '[email protected]') self.assertFalse(u2.has_usable_password()) def test_user_no_email(self): "Check that users can be created without an email" u = User.objects.create_user('testuser1') self.assertEqual(u.email, '') u2 = User.objects.create_user('testuser2', email='') self.assertEqual(u2.email, '') u3 = User.objects.create_user('testuser3', email=None) self.assertEqual(u3.email, '') def test_anonymous_user(self): "Check the properties of the anonymous user" a = AnonymousUser() self.assertEqual(a.pk, None) self.assertFalse(a.is_authenticated()) self.assertFalse(a.is_staff) self.assertFalse(a.is_active) self.assertFalse(a.is_superuser) self.assertEqual(a.groups.all().count(), 0) self.assertEqual(a.user_permissions.all().count(), 0) def test_superuser(self): "Check the creation and properties of a superuser" super = User.objects.create_superuser('super', '[email protected]', 'super') self.assertTrue(super.is_superuser) self.assertTrue(super.is_active) self.assertTrue(super.is_staff) def test_createsuperuser_management_command(self): "Check the operation of the createsuperuser management command" # We can use the management command to create a superuser new_io = StringIO() call_command("createsuperuser", interactive=False, username="joe", email="[email protected]", stdout=new_io ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, 'Superuser created successfully.') u = User.objects.get(username="joe") self.assertEqual(u.email, '[email protected]') # created password should be unusable self.assertFalse(u.has_usable_password()) # We can supress output on the management command new_io = StringIO() call_command("createsuperuser", interactive=False, username="joe2", email="[email protected]", verbosity=0, stdout=new_io ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, '') u = User.objects.get(username="joe2") self.assertEqual(u.email, '[email protected]') self.assertFalse(u.has_usable_password()) call_command("createsuperuser", interactive=False, username="[email protected]", email="[email protected]", verbosity=0 ) u = User.objects.get(username="[email protected]") self.assertEqual(u.email, '[email protected]') self.assertFalse(u.has_usable_password()) @mock_inputs({'password': "nopasswd"}) def test_createsuperuser_nolocale(self): """ Check that createsuperuser does not break when no locale is set. See ticket #16017. """ old_getdefaultlocale = locale.getdefaultlocale try: # Temporarily remove locale information locale.getdefaultlocale = lambda: (None, None) # Call the command in this new environment call_command("createsuperuser", interactive=True, username="[email protected]", email="[email protected]", verbosity=0 ) except TypeError: self.fail("createsuperuser fails if the OS provides no information about the current locale") finally: # Re-apply locale information locale.getdefaultlocale = old_getdefaultlocale # If we were successful, a user should have been created u = User.objects.get(username="[email protected]") self.assertEqual(u.email, '[email protected]') @mock_inputs({ 'password': "nopasswd", 'uživatel': 'foo', # username (cz) 'email': '[email protected]'}) def test_createsuperuser_non_ascii_verbose_name(self): # Aliased so the string doesn't get extracted from django.utils.translation import ugettext_lazy as ulazy username_field = User._meta.get_field('username') old_verbose_name = username_field.verbose_name username_field.verbose_name = ulazy('uživatel') new_io = StringIO() try: call_command("createsuperuser", interactive=True, stdout=new_io ) finally: username_field.verbose_name = old_verbose_name command_output = new_io.getvalue().strip() self.assertEqual(command_output, 'Superuser created successfully.') def test_get_user_model(self): "The current user model can be retrieved" self.assertEqual(get_user_model(), User) @override_settings(AUTH_USER_MODEL='auth.CustomUser') def test_swappable_user(self): "The current user model can be swapped out for another" self.assertEqual(get_user_model(), CustomUser) with self.assertRaises(AttributeError): User.objects.all() @override_settings(AUTH_USER_MODEL='badsetting') def test_swappable_user_bad_setting(self): "The alternate user setting must point to something in the format app.model" with self.assertRaises(ImproperlyConfigured): get_user_model() @override_settings(AUTH_USER_MODEL='thismodel.doesntexist') def test_swappable_user_nonexistent_model(self): "The current user model must point to an installed model" with self.assertRaises(ImproperlyConfigured): get_user_model()
bsd-3-clause
campbe13/openhatch
vendor/packages/mechanize/mechanize/_headersutil.py
133
8371
"""Utility functions for HTTP header value parsing and construction. Copyright 1997-1998, Gisle Aas Copyright 2002-2006, John J. Lee This code is free software; you can redistribute it and/or modify it under the terms of the BSD or ZPL 2.1 licenses (see the file COPYING.txt included with the distribution). """ import os, re from types import StringType from types import UnicodeType STRING_TYPES = StringType, UnicodeType from _util import http2time import _rfc3986 def is_html_file_extension(url, allow_xhtml): ext = os.path.splitext(_rfc3986.urlsplit(url)[2])[1] html_exts = [".htm", ".html"] if allow_xhtml: html_exts += [".xhtml"] return ext in html_exts def is_html(ct_headers, url, allow_xhtml=False): """ ct_headers: Sequence of Content-Type headers url: Response URL """ if not ct_headers: return is_html_file_extension(url, allow_xhtml) headers = split_header_words(ct_headers) if len(headers) < 1: return is_html_file_extension(url, allow_xhtml) first_header = headers[0] first_parameter = first_header[0] ct = first_parameter[0] html_types = ["text/html"] if allow_xhtml: html_types += [ "text/xhtml", "text/xml", "application/xml", "application/xhtml+xml", ] return ct in html_types def unmatched(match): """Return unmatched part of re.Match object.""" start, end = match.span(0) return match.string[:start]+match.string[end:] token_re = re.compile(r"^\s*([^=\s;,]+)") quoted_value_re = re.compile(r"^\s*=\s*\"([^\"\\]*(?:\\.[^\"\\]*)*)\"") value_re = re.compile(r"^\s*=\s*([^\s;,]*)") escape_re = re.compile(r"\\(.)") def split_header_words(header_values): r"""Parse header values into a list of lists containing key,value pairs. The function knows how to deal with ",", ";" and "=" as well as quoted values after "=". A list of space separated tokens are parsed as if they were separated by ";". If the header_values passed as argument contains multiple values, then they are treated as if they were a single value separated by comma ",". This means that this function is useful for parsing header fields that follow this syntax (BNF as from the HTTP/1.1 specification, but we relax the requirement for tokens). headers = #header header = (token | parameter) *( [";"] (token | parameter)) token = 1*<any CHAR except CTLs or separators> separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) qdtext = <any TEXT except <">> quoted-pair = "\" CHAR parameter = attribute "=" value attribute = token value = token | quoted-string Each header is represented by a list of key/value pairs. The value for a simple token (not part of a parameter) is None. Syntactically incorrect headers will not necessarily be parsed as you would want. This is easier to describe with some examples: >>> split_header_words(['foo="bar"; port="80,81"; discard, bar=baz']) [[('foo', 'bar'), ('port', '80,81'), ('discard', None)], [('bar', 'baz')]] >>> split_header_words(['text/html; charset="iso-8859-1"']) [[('text/html', None), ('charset', 'iso-8859-1')]] >>> split_header_words([r'Basic realm="\"foo\bar\""']) [[('Basic', None), ('realm', '"foobar"')]] """ assert type(header_values) not in STRING_TYPES result = [] for text in header_values: orig_text = text pairs = [] while text: m = token_re.search(text) if m: text = unmatched(m) name = m.group(1) m = quoted_value_re.search(text) if m: # quoted value text = unmatched(m) value = m.group(1) value = escape_re.sub(r"\1", value) else: m = value_re.search(text) if m: # unquoted value text = unmatched(m) value = m.group(1) value = value.rstrip() else: # no value, a lone token value = None pairs.append((name, value)) elif text.lstrip().startswith(","): # concatenated headers, as per RFC 2616 section 4.2 text = text.lstrip()[1:] if pairs: result.append(pairs) pairs = [] else: # skip junk non_junk, nr_junk_chars = re.subn("^[=\s;]*", "", text) assert nr_junk_chars > 0, ( "split_header_words bug: '%s', '%s', %s" % (orig_text, text, pairs)) text = non_junk if pairs: result.append(pairs) return result join_escape_re = re.compile(r"([\"\\])") def join_header_words(lists): """Do the inverse of the conversion done by split_header_words. Takes a list of lists of (key, value) pairs and produces a single header value. Attribute values are quoted if needed. >>> join_header_words([[("text/plain", None), ("charset", "iso-8859/1")]]) 'text/plain; charset="iso-8859/1"' >>> join_header_words([[("text/plain", None)], [("charset", "iso-8859/1")]]) 'text/plain, charset="iso-8859/1"' """ headers = [] for pairs in lists: attr = [] for k, v in pairs: if v is not None: if not re.search(r"^\w+$", v): v = join_escape_re.sub(r"\\\1", v) # escape " and \ v = '"%s"' % v if k is None: # Netscape cookies may have no name k = v else: k = "%s=%s" % (k, v) attr.append(k) if attr: headers.append("; ".join(attr)) return ", ".join(headers) def strip_quotes(text): if text.startswith('"'): text = text[1:] if text.endswith('"'): text = text[:-1] return text def parse_ns_headers(ns_headers): """Ad-hoc parser for Netscape protocol cookie-attributes. The old Netscape cookie format for Set-Cookie can for instance contain an unquoted "," in the expires field, so we have to use this ad-hoc parser instead of split_header_words. XXX This may not make the best possible effort to parse all the crap that Netscape Cookie headers contain. Ronald Tschalar's HTTPClient parser is probably better, so could do worse than following that if this ever gives any trouble. Currently, this is also used for parsing RFC 2109 cookies. """ known_attrs = ("expires", "domain", "path", "secure", # RFC 2109 attrs (may turn up in Netscape cookies, too) "version", "port", "max-age") result = [] for ns_header in ns_headers: pairs = [] version_set = False params = re.split(r";\s*", ns_header) for ii in range(len(params)): param = params[ii] param = param.rstrip() if param == "": continue if "=" not in param: k, v = param, None else: k, v = re.split(r"\s*=\s*", param, 1) k = k.lstrip() if ii != 0: lc = k.lower() if lc in known_attrs: k = lc if k == "version": # This is an RFC 2109 cookie. v = strip_quotes(v) version_set = True if k == "expires": # convert expires date to seconds since epoch v = http2time(strip_quotes(v)) # None if invalid pairs.append((k, v)) if pairs: if not version_set: pairs.append(("version", "0")) result.append(pairs) return result def _test(): import doctest, _headersutil return doctest.testmod(_headersutil) if __name__ == "__main__": _test()
agpl-3.0
amyvmiwei/kbengine
kbe/res/scripts/common/Lib/site-packages/pip/_vendor/html5lib/treewalkers/etree.py
310
4625
from __future__ import absolute_import, division, unicode_literals try: from collections import OrderedDict except ImportError: try: from ordereddict import OrderedDict except ImportError: OrderedDict = dict import gettext _ = gettext.gettext import re from pip._vendor.six import text_type from . import _base from ..utils import moduleFactoryFactory tag_regexp = re.compile("{([^}]*)}(.*)") def getETreeBuilder(ElementTreeImplementation): ElementTree = ElementTreeImplementation ElementTreeCommentType = ElementTree.Comment("asd").tag class TreeWalker(_base.NonRecursiveTreeWalker): """Given the particular ElementTree representation, this implementation, to avoid using recursion, returns "nodes" as tuples with the following content: 1. The current element 2. The index of the element relative to its parent 3. A stack of ancestor elements 4. A flag "text", "tail" or None to indicate if the current node is a text node; either the text or tail of the current element (1) """ def getNodeDetails(self, node): if isinstance(node, tuple): # It might be the root Element elt, key, parents, flag = node if flag in ("text", "tail"): return _base.TEXT, getattr(elt, flag) else: node = elt if not(hasattr(node, "tag")): node = node.getroot() if node.tag in ("DOCUMENT_ROOT", "DOCUMENT_FRAGMENT"): return (_base.DOCUMENT,) elif node.tag == "<!DOCTYPE>": return (_base.DOCTYPE, node.text, node.get("publicId"), node.get("systemId")) elif node.tag == ElementTreeCommentType: return _base.COMMENT, node.text else: assert type(node.tag) == text_type, type(node.tag) # This is assumed to be an ordinary element match = tag_regexp.match(node.tag) if match: namespace, tag = match.groups() else: namespace = None tag = node.tag attrs = OrderedDict() for name, value in list(node.attrib.items()): match = tag_regexp.match(name) if match: attrs[(match.group(1), match.group(2))] = value else: attrs[(None, name)] = value return (_base.ELEMENT, namespace, tag, attrs, len(node) or node.text) def getFirstChild(self, node): if isinstance(node, tuple): element, key, parents, flag = node else: element, key, parents, flag = node, None, [], None if flag in ("text", "tail"): return None else: if element.text: return element, key, parents, "text" elif len(element): parents.append(element) return element[0], 0, parents, None else: return None def getNextSibling(self, node): if isinstance(node, tuple): element, key, parents, flag = node else: return None if flag == "text": if len(element): parents.append(element) return element[0], 0, parents, None else: return None else: if element.tail and flag != "tail": return element, key, parents, "tail" elif key < len(parents[-1]) - 1: return parents[-1][key + 1], key + 1, parents, None else: return None def getParentNode(self, node): if isinstance(node, tuple): element, key, parents, flag = node else: return None if flag == "text": if not parents: return element else: return element, key, parents, None else: parent = parents.pop() if not parents: return parent else: return parent, list(parents[-1]).index(parent), parents, None return locals() getETreeModule = moduleFactoryFactory(getETreeBuilder)
lgpl-3.0
meletakis/collato
lib/python2.7/site-packages/django/contrib/admin/views/main.py
85
16606
import operator from functools import reduce from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured from django.core.paginator import InvalidPage from django.core.urlresolvers import reverse from django.db import models from django.db.models.fields import FieldDoesNotExist from django.utils.datastructures import SortedDict from django.utils.encoding import force_str, force_text from django.utils.translation import ugettext, ugettext_lazy from django.utils.http import urlencode from django.contrib.admin import FieldListFilter from django.contrib.admin.options import IncorrectLookupParameters from django.contrib.admin.util import (quote, get_fields_from_path, lookup_needs_distinct, prepare_lookup_value) # Changelist settings ALL_VAR = 'all' ORDER_VAR = 'o' ORDER_TYPE_VAR = 'ot' PAGE_VAR = 'p' SEARCH_VAR = 'q' TO_FIELD_VAR = 't' IS_POPUP_VAR = 'pop' ERROR_FLAG = 'e' IGNORED_PARAMS = ( ALL_VAR, ORDER_VAR, ORDER_TYPE_VAR, SEARCH_VAR, IS_POPUP_VAR, TO_FIELD_VAR) # Text to display within change-list table cells if the value is blank. EMPTY_CHANGELIST_VALUE = ugettext_lazy('(None)') class ChangeList(object): def __init__(self, request, model, list_display, list_display_links, list_filter, date_hierarchy, search_fields, list_select_related, list_per_page, list_max_show_all, list_editable, model_admin): self.model = model self.opts = model._meta self.lookup_opts = self.opts self.root_query_set = model_admin.queryset(request) self.list_display = list_display self.list_display_links = list_display_links self.list_filter = list_filter self.date_hierarchy = date_hierarchy self.search_fields = search_fields self.list_select_related = list_select_related self.list_per_page = list_per_page self.list_max_show_all = list_max_show_all self.model_admin = model_admin # Get search parameters from the query string. try: self.page_num = int(request.GET.get(PAGE_VAR, 0)) except ValueError: self.page_num = 0 self.show_all = ALL_VAR in request.GET self.is_popup = IS_POPUP_VAR in request.GET self.to_field = request.GET.get(TO_FIELD_VAR) self.params = dict(request.GET.items()) if PAGE_VAR in self.params: del self.params[PAGE_VAR] if ERROR_FLAG in self.params: del self.params[ERROR_FLAG] if self.is_popup: self.list_editable = () else: self.list_editable = list_editable self.query = request.GET.get(SEARCH_VAR, '') self.query_set = self.get_query_set(request) self.get_results(request) if self.is_popup: title = ugettext('Select %s') else: title = ugettext('Select %s to change') self.title = title % force_text(self.opts.verbose_name) self.pk_attname = self.lookup_opts.pk.attname def get_filters(self, request): lookup_params = self.params.copy() # a dictionary of the query string use_distinct = False # Remove all the parameters that are globally and systematically # ignored. for ignored in IGNORED_PARAMS: if ignored in lookup_params: del lookup_params[ignored] # Normalize the types of keys for key, value in lookup_params.items(): if not isinstance(key, str): # 'key' will be used as a keyword argument later, so Python # requires it to be a string. del lookup_params[key] lookup_params[force_str(key)] = value if not self.model_admin.lookup_allowed(key, value): raise SuspiciousOperation("Filtering by %s not allowed" % key) filter_specs = [] if self.list_filter: for list_filter in self.list_filter: if callable(list_filter): # This is simply a custom list filter class. spec = list_filter(request, lookup_params, self.model, self.model_admin) else: field_path = None if isinstance(list_filter, (tuple, list)): # This is a custom FieldListFilter class for a given field. field, field_list_filter_class = list_filter else: # This is simply a field name, so use the default # FieldListFilter class that has been registered for # the type of the given field. field, field_list_filter_class = list_filter, FieldListFilter.create if not isinstance(field, models.Field): field_path = field field = get_fields_from_path(self.model, field_path)[-1] spec = field_list_filter_class(field, request, lookup_params, self.model, self.model_admin, field_path=field_path) # Check if we need to use distinct() use_distinct = (use_distinct or lookup_needs_distinct(self.lookup_opts, field_path)) if spec and spec.has_output(): filter_specs.append(spec) # At this point, all the parameters used by the various ListFilters # have been removed from lookup_params, which now only contains other # parameters passed via the query string. We now loop through the # remaining parameters both to ensure that all the parameters are valid # fields and to determine if at least one of them needs distinct(). If # the lookup parameters aren't real fields, then bail out. try: for key, value in lookup_params.items(): lookup_params[key] = prepare_lookup_value(key, value) use_distinct = (use_distinct or lookup_needs_distinct(self.lookup_opts, key)) return filter_specs, bool(filter_specs), lookup_params, use_distinct except FieldDoesNotExist as e: raise IncorrectLookupParameters(e) def get_query_string(self, new_params=None, remove=None): if new_params is None: new_params = {} if remove is None: remove = [] p = self.params.copy() for r in remove: for k in list(p): if k.startswith(r): del p[k] for k, v in new_params.items(): if v is None: if k in p: del p[k] else: p[k] = v return '?%s' % urlencode(sorted(p.items())) def get_results(self, request): paginator = self.model_admin.get_paginator(request, self.query_set, self.list_per_page) # Get the number of objects, with admin filters applied. result_count = paginator.count # Get the total number of objects, with no admin filters applied. # Perform a slight optimization: Check to see whether any filters were # given. If not, use paginator.hits to calculate the number of objects, # because we've already done paginator.hits and the value is cached. if not self.query_set.query.where: full_result_count = result_count else: full_result_count = self.root_query_set.count() can_show_all = result_count <= self.list_max_show_all multi_page = result_count > self.list_per_page # Get the list of objects to display on this page. if (self.show_all and can_show_all) or not multi_page: result_list = self.query_set._clone() else: try: result_list = paginator.page(self.page_num+1).object_list except InvalidPage: raise IncorrectLookupParameters self.result_count = result_count self.full_result_count = full_result_count self.result_list = result_list self.can_show_all = can_show_all self.multi_page = multi_page self.paginator = paginator def _get_default_ordering(self): ordering = [] if self.model_admin.ordering: ordering = self.model_admin.ordering elif self.lookup_opts.ordering: ordering = self.lookup_opts.ordering return ordering def get_ordering_field(self, field_name): """ Returns the proper model field name corresponding to the given field_name to use for ordering. field_name may either be the name of a proper model field or the name of a method (on the admin or model) or a callable with the 'admin_order_field' attribute. Returns None if no proper model field name can be matched. """ try: field = self.lookup_opts.get_field(field_name) return field.name except models.FieldDoesNotExist: # See whether field_name is a name of a non-field # that allows sorting. if callable(field_name): attr = field_name elif hasattr(self.model_admin, field_name): attr = getattr(self.model_admin, field_name) else: attr = getattr(self.model, field_name) return getattr(attr, 'admin_order_field', None) def get_ordering(self, request, queryset): """ Returns the list of ordering fields for the change list. First we check the get_ordering() method in model admin, then we check the object's default ordering. Then, any manually-specified ordering from the query string overrides anything. Finally, a deterministic order is guaranteed by ensuring the primary key is used as the last ordering field. """ params = self.params ordering = list(self.model_admin.get_ordering(request) or self._get_default_ordering()) if ORDER_VAR in params: # Clear ordering and used params ordering = [] order_params = params[ORDER_VAR].split('.') for p in order_params: try: none, pfx, idx = p.rpartition('-') field_name = self.list_display[int(idx)] order_field = self.get_ordering_field(field_name) if not order_field: continue # No 'admin_order_field', skip it ordering.append(pfx + order_field) except (IndexError, ValueError): continue # Invalid ordering specified, skip it. # Add the given query's ordering fields, if any. ordering.extend(queryset.query.order_by) # Ensure that the primary key is systematically present in the list of # ordering fields so we can guarantee a deterministic order across all # database backends. pk_name = self.lookup_opts.pk.name if not (set(ordering) & set(['pk', '-pk', pk_name, '-' + pk_name])): # The two sets do not intersect, meaning the pk isn't present. So # we add it. ordering.append('-pk') return ordering def get_ordering_field_columns(self): """ Returns a SortedDict of ordering field column numbers and asc/desc """ # We must cope with more than one column having the same underlying sort # field, so we base things on column numbers. ordering = self._get_default_ordering() ordering_fields = SortedDict() if ORDER_VAR not in self.params: # for ordering specified on ModelAdmin or model Meta, we don't know # the right column numbers absolutely, because there might be more # than one column associated with that ordering, so we guess. for field in ordering: if field.startswith('-'): field = field[1:] order_type = 'desc' else: order_type = 'asc' for index, attr in enumerate(self.list_display): if self.get_ordering_field(attr) == field: ordering_fields[index] = order_type break else: for p in self.params[ORDER_VAR].split('.'): none, pfx, idx = p.rpartition('-') try: idx = int(idx) except ValueError: continue # skip it ordering_fields[idx] = 'desc' if pfx == '-' else 'asc' return ordering_fields def get_query_set(self, request): # First, we collect all the declared list filters. (self.filter_specs, self.has_filters, remaining_lookup_params, use_distinct) = self.get_filters(request) # Then, we let every list filter modify the queryset to its liking. qs = self.root_query_set for filter_spec in self.filter_specs: new_qs = filter_spec.queryset(request, qs) if new_qs is not None: qs = new_qs try: # Finally, we apply the remaining lookup parameters from the query # string (i.e. those that haven't already been processed by the # filters). qs = qs.filter(**remaining_lookup_params) except (SuspiciousOperation, ImproperlyConfigured): # Allow certain types of errors to be re-raised as-is so that the # caller can treat them in a special way. raise except Exception as e: # Every other error is caught with a naked except, because we don't # have any other way of validating lookup parameters. They might be # invalid if the keyword arguments are incorrect, or if the values # are not in the correct type, so we might get FieldError, # ValueError, ValidationError, or ?. raise IncorrectLookupParameters(e) # Use select_related() if one of the list_display options is a field # with a relationship and the provided queryset doesn't already have # select_related defined. if not qs.query.select_related: if self.list_select_related: qs = qs.select_related() else: for field_name in self.list_display: try: field = self.lookup_opts.get_field(field_name) except models.FieldDoesNotExist: pass else: if isinstance(field.rel, models.ManyToOneRel): qs = qs.select_related() break # Set ordering. ordering = self.get_ordering(request, qs) qs = qs.order_by(*ordering) # Apply keyword searches. def construct_search(field_name): if field_name.startswith('^'): return "%s__istartswith" % field_name[1:] elif field_name.startswith('='): return "%s__iexact" % field_name[1:] elif field_name.startswith('@'): return "%s__search" % field_name[1:] else: return "%s__icontains" % field_name if self.search_fields and self.query: orm_lookups = [construct_search(str(search_field)) for search_field in self.search_fields] for bit in self.query.split(): or_queries = [models.Q(**{orm_lookup: bit}) for orm_lookup in orm_lookups] qs = qs.filter(reduce(operator.or_, or_queries)) if not use_distinct: for search_spec in orm_lookups: if lookup_needs_distinct(self.lookup_opts, search_spec): use_distinct = True break if use_distinct: return qs.distinct() else: return qs def url_for_result(self, result): pk = getattr(result, self.pk_attname) return reverse('admin:%s_%s_change' % (self.opts.app_label, self.opts.module_name), args=(quote(pk),), current_app=self.model_admin.admin_site.name)
gpl-2.0
andersonresende/django
django/contrib/formtools/wizard/storage/base.py
79
4920
from django.core.files.uploadedfile import UploadedFile from django.utils.datastructures import MultiValueDict from django.utils.functional import lazy_property from django.utils import six from django.contrib.formtools.wizard.storage.exceptions import NoFileStorageConfigured class BaseStorage(object): step_key = 'step' step_data_key = 'step_data' step_files_key = 'step_files' extra_data_key = 'extra_data' def __init__(self, prefix, request=None, file_storage=None): self.prefix = 'wizard_%s' % prefix self.request = request self.file_storage = file_storage self._files = {} self._tmp_files = [] def init_data(self): self.data = { self.step_key: None, self.step_data_key: {}, self.step_files_key: {}, self.extra_data_key: {}, } def reset(self): # Store unused temporary file names in order to delete them # at the end of the response cycle through a callback attached in # `update_response`. wizard_files = self.data[self.step_files_key] for step_files in six.itervalues(wizard_files): for step_file in six.itervalues(step_files): self._tmp_files.append(step_file['tmp_name']) self.init_data() def _get_current_step(self): return self.data[self.step_key] def _set_current_step(self, step): self.data[self.step_key] = step current_step = lazy_property(_get_current_step, _set_current_step) def _get_extra_data(self): return self.data[self.extra_data_key] def _set_extra_data(self, extra_data): self.data[self.extra_data_key] = extra_data extra_data = lazy_property(_get_extra_data, _set_extra_data) def get_step_data(self, step): # When reading the serialized data, upconvert it to a MultiValueDict, # some serializers (json) don't preserve the type of the object. values = self.data[self.step_data_key].get(step, None) if values is not None: values = MultiValueDict(values) return values def set_step_data(self, step, cleaned_data): # If the value is a MultiValueDict, convert it to a regular dict of the # underlying contents. Some serializers call the public API on it (as # opposed to the underlying dict methods), in which case the content # can be truncated (__getitem__ returns only the first item). if isinstance(cleaned_data, MultiValueDict): cleaned_data = dict(cleaned_data.lists()) self.data[self.step_data_key][step] = cleaned_data @property def current_step_data(self): return self.get_step_data(self.current_step) def get_step_files(self, step): wizard_files = self.data[self.step_files_key].get(step, {}) if wizard_files and not self.file_storage: raise NoFileStorageConfigured( "You need to define 'file_storage' in your " "wizard view in order to handle file uploads.") files = {} for field, field_dict in six.iteritems(wizard_files): field_dict = field_dict.copy() tmp_name = field_dict.pop('tmp_name') if (step, field) not in self._files: self._files[(step, field)] = UploadedFile( file=self.file_storage.open(tmp_name), **field_dict) files[field] = self._files[(step, field)] return files or None def set_step_files(self, step, files): if files and not self.file_storage: raise NoFileStorageConfigured( "You need to define 'file_storage' in your " "wizard view in order to handle file uploads.") if step not in self.data[self.step_files_key]: self.data[self.step_files_key][step] = {} for field, field_file in six.iteritems(files or {}): tmp_filename = self.file_storage.save(field_file.name, field_file) file_dict = { 'tmp_name': tmp_filename, 'name': field_file.name, 'content_type': field_file.content_type, 'size': field_file.size, 'charset': field_file.charset } self.data[self.step_files_key][step][field] = file_dict @property def current_step_files(self): return self.get_step_files(self.current_step) def update_response(self, response): def post_render_callback(response): for file in self._files.values(): if not file.closed: file.close() for tmp_file in self._tmp_files: self.file_storage.delete(tmp_file) if hasattr(response, 'render'): response.add_post_render_callback(post_render_callback) else: post_render_callback(response)
bsd-3-clause
CMUSV-VisTrails/WorkflowRecommendation
vistrails/db/versions/v0_9_3/translate/v0_9_1.py
1
3964
############################################################################### ## ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: [email protected] ## ## This file is part of VisTrails. ## ## "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 University of Utah 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 copy from db.versions.v0_9_3.domain import DBVistrail, DBAction, DBTag, DBModule, \ DBConnection, DBPortSpec, DBFunction, DBParameter, DBLocation, DBAdd, \ DBChange, DBDelete, DBAnnotation, DBPort, DBAbstractionRef, DBGroup, \ DBWorkflow, DBLog def translateVistrail(_vistrail): def update_key(old_obj, translate_dict): return '__notes__' def update_annotation(old_obj, translate_dict): new_dict = {'DBAnnotation': {'key': update_key}} new_list = [] for annotation in old_obj.db_annotations: if annotation.db_key == 'notes': new_list.append(DBAnnotation.update_version(annotation, new_dict)) else: new_list.append(DBAnnotation.update_version(annotation, {})) return new_list def update_session(old_obj, translate_dict): if not old_obj.db_session: session = None else: session = long(old_obj.db_session) return session def update_workflow(old_obj, translate_dict): return DBWorkflow.update_version(old_obj.db_workflow, translate_dict) translate_dict = {'DBAction': {'annotations': update_annotation, 'session': update_session}, 'DBGroup': {'workflow': update_workflow}} # pass DBVistrail because domain contains enriched version of the auto_gen vistrail = DBVistrail.update_version(_vistrail, translate_dict) vistrail.db_version = '0.9.3' return vistrail def translateWorkflow(_workflow): def update_workflow(old_obj, translate_dict): return DBWorkflow.update_version(old_obj.db_workflow, translate_dict) translate_dict = {'DBGroup': {'workflow': update_workflow}} workflow = update_workflow(_workflow, translate_dict) workflow.db_version = '0.9.3' return workflow def translateLog(_log): log = DBLog.update_version(_log, translate_dict) log.db_version = '0.9.3' return log
bsd-3-clause
yesudeep/old-milsalumni
app/console/app/pygments/cmdline.py
19
12149
# -*- coding: utf-8 -*- """ pygments.cmdline ~~~~~~~~~~~~~~~~ Command line interface. :copyright: 2006-2008 by Georg Brandl. :license: BSD, see LICENSE for more details. """ import sys import getopt from textwrap import dedent from pygments import __version__, __author__, highlight from pygments.util import ClassNotFound, OptionError, docstring_headline from pygments.lexers import get_all_lexers, get_lexer_by_name, get_lexer_for_filename, \ find_lexer_class, guess_lexer, TextLexer from pygments.formatters import get_all_formatters, get_formatter_by_name, \ get_formatter_for_filename, find_formatter_class, \ TerminalFormatter # pylint:disable-msg=E0611 from pygments.filters import get_all_filters, find_filter_class from pygments.styles import get_all_styles, get_style_by_name USAGE = """\ Usage: %s [-l <lexer> | -g] [-F <filter>[:<options>]] [-f <formatter>] [-O <options>] [-P <option=value>] [-o <outfile>] [<infile>] %s -S <style> -f <formatter> [-a <arg>] [-O <options>] [-P <option=value>] %s -L [<which> ...] %s -H <type> <name> %s -h | -V Highlight the input file and write the result to <outfile>. If no input file is given, use stdin, if -o is not given, use stdout. <lexer> is a lexer name (query all lexer names with -L). If -l is not given, the lexer is guessed from the extension of the input file name (this obviously doesn't work if the input is stdin). If -g is passed, attempt to guess the lexer from the file contents, or pass through as plain text if this fails (this can work for stdin). Likewise, <formatter> is a formatter name, and will be guessed from the extension of the output file name. If no output file is given, the terminal formatter will be used by default. With the -O option, you can give the lexer and formatter a comma- separated list of options, e.g. ``-O bg=light,python=cool``. The -P option adds lexer and formatter options like the -O option, but you can only give one option per -P. That way, the option value may contain commas and equals signs, which it can't with -O, e.g. ``-P "heading=Pygments, the Python highlighter". With the -F option, you can add filters to the token stream, you can give options in the same way as for -O after a colon (note: there must not be spaces around the colon). The -O, -P and -F options can be given multiple times. With the -S option, print out style definitions for style <style> for formatter <formatter>. The argument given by -a is formatter dependent. The -L option lists lexers, formatters, styles or filters -- set `which` to the thing you want to list (e.g. "styles"), or omit it to list everything. The -H option prints detailed help for the object <name> of type <type>, where <type> is one of "lexer", "formatter" or "filter". The -h option prints this help. The -V option prints the package version. """ def _parse_options(o_strs): opts = {} if not o_strs: return opts for o_str in o_strs: if not o_str: continue o_args = o_str.split(',') for o_arg in o_args: o_arg = o_arg.strip() try: o_key, o_val = o_arg.split('=') o_key = o_key.strip() o_val = o_val.strip() except ValueError: opts[o_arg] = True else: opts[o_key] = o_val return opts def _parse_filters(f_strs): filters = [] if not f_strs: return filters for f_str in f_strs: if ':' in f_str: fname, fopts = f_str.split(':', 1) filters.append((fname, _parse_options([fopts]))) else: filters.append((f_str, {})) return filters def _print_help(what, name): try: if what == 'lexer': cls = find_lexer_class(name) print "Help on the %s lexer:" % cls.name print dedent(cls.__doc__) elif what == 'formatter': cls = find_formatter_class(name) print "Help on the %s formatter:" % cls.name print dedent(cls.__doc__) elif what == 'filter': cls = find_filter_class(name) print "Help on the %s filter:" % name print dedent(cls.__doc__) except AttributeError: print >>sys.stderr, "%s not found!" % what def _print_list(what): if what == 'lexer': print print "Lexers:" print "~~~~~~~" info = [] for fullname, names, exts, _ in get_all_lexers(): tup = (', '.join(names)+':', fullname, exts and '(filenames ' + ', '.join(exts) + ')' or '') info.append(tup) info.sort() for i in info: print ('* %s\n %s %s') % i elif what == 'formatter': print print "Formatters:" print "~~~~~~~~~~~" info = [] for cls in get_all_formatters(): doc = docstring_headline(cls) tup = (', '.join(cls.aliases) + ':', doc, cls.filenames and '(filenames ' + ', '.join(cls.filenames) + ')' or '') info.append(tup) info.sort() for i in info: print ('* %s\n %s %s') % i elif what == 'filter': print print "Filters:" print "~~~~~~~~" for name in get_all_filters(): cls = find_filter_class(name) print "* " + name + ':' print " %s" % docstring_headline(cls) elif what == 'style': print print "Styles:" print "~~~~~~~" for name in get_all_styles(): cls = get_style_by_name(name) print "* " + name + ':' print " %s" % docstring_headline(cls) def main(args=sys.argv): """ Main command line entry point. """ # pylint: disable-msg=R0911,R0912,R0915 usage = USAGE % ((args[0],) * 5) try: popts, args = getopt.getopt(args[1:], "l:f:F:o:O:P:LS:a:hVHg") except getopt.GetoptError, err: print >>sys.stderr, usage return 2 opts = {} O_opts = [] P_opts = [] F_opts = [] for opt, arg in popts: if opt == '-O': O_opts.append(arg) elif opt == '-P': P_opts.append(arg) elif opt == '-F': F_opts.append(arg) opts[opt] = arg if not opts and not args: print usage return 0 if opts.pop('-h', None) is not None: print usage return 0 if opts.pop('-V', None) is not None: print 'Pygments version %s, (c) 2006-2008 by %s.' % (__version__, __author__) return 0 # handle ``pygmentize -L`` L_opt = opts.pop('-L', None) if L_opt is not None: if opts: print >>sys.stderr, usage return 2 # print version main(['', '-V']) if not args: args = ['lexer', 'formatter', 'filter', 'style'] for arg in args: _print_list(arg.rstrip('s')) return 0 # handle ``pygmentize -H`` H_opt = opts.pop('-H', None) if H_opt is not None: if opts or len(args) != 2: print >>sys.stderr, usage return 2 what, name = args if what not in ('lexer', 'formatter', 'filter'): print >>sys.stderr, usage return 2 _print_help(what, name) return 0 # parse -O options parsed_opts = _parse_options(O_opts) opts.pop('-O', None) # parse -P options for p_opt in P_opts: try: name, value = p_opt.split('=', 1) except ValueError: parsed_opts[p_opt] = True else: parsed_opts[name] = value opts.pop('-P', None) # handle ``pygmentize -S`` S_opt = opts.pop('-S', None) a_opt = opts.pop('-a', None) if S_opt is not None: f_opt = opts.pop('-f', None) if not f_opt: print >>sys.stderr, usage return 2 if opts or args: print >>sys.stderr, usage return 2 try: parsed_opts['style'] = S_opt fmter = get_formatter_by_name(f_opt, **parsed_opts) except ClassNotFound, err: print >>sys.stderr, err return 1 arg = a_opt or '' print fmter.get_style_defs(arg) return 0 # if no -S is given, -a is not allowed if a_opt is not None: print >>sys.stderr, usage return 2 # parse -F options F_opts = _parse_filters(F_opts) opts.pop('-F', None) # select formatter outfn = opts.pop('-o', None) fmter = opts.pop('-f', None) if fmter: try: fmter = get_formatter_by_name(fmter, **parsed_opts) except (OptionError, ClassNotFound), err: print >>sys.stderr, 'Error:', err return 1 if outfn: if not fmter: try: fmter = get_formatter_for_filename(outfn, **parsed_opts) except (OptionError, ClassNotFound), err: print >>sys.stderr, 'Error:', err return 1 try: outfile = file(outfn, 'wb') except Exception, err: print >>sys.stderr, 'Error: cannot open outfile:', err return 1 else: if not fmter: fmter = TerminalFormatter(**parsed_opts) outfile = sys.stdout # select lexer lexer = opts.pop('-l', None) if lexer: try: lexer = get_lexer_by_name(lexer, **parsed_opts) except (OptionError, ClassNotFound), err: print >>sys.stderr, 'Error:', err return 1 if args: if len(args) > 1: print >>sys.stderr, usage return 2 infn = args[0] try: code = file(infn).read() except Exception, err: print >>sys.stderr, 'Error: cannot read infile:', err return 1 if not lexer: try: lexer = get_lexer_for_filename(infn, **parsed_opts) except ClassNotFound, err: if '-g' in opts: try: lexer = guess_lexer(code) except ClassNotFound: lexer = TextLexer() else: print >>sys.stderr, 'Error:', err return 1 except OptionError, err: print >>sys.stderr, 'Error:', err return 1 else: if '-g' in opts: code = sys.stdin.read() try: lexer = guess_lexer(code) except ClassNotFound: lexer = TextLexer() elif not lexer: print >>sys.stderr, 'Error: no lexer name given and reading ' + \ 'from stdin (try using -g or -l <lexer>)' return 2 else: code = sys.stdin.read() # No encoding given? Use latin1 if output file given, # stdin/stdout encoding otherwise. # (This is a compromise, I'm not too happy with it...) if 'encoding' not in parsed_opts and 'outencoding' not in parsed_opts: if outfn: # encoding pass-through fmter.encoding = 'latin1' else: # use terminal encoding lexer.encoding = getattr(sys.stdin, 'encoding', None) or 'ascii' fmter.encoding = getattr(sys.stdout, 'encoding', None) or 'ascii' # ... and do it! try: # process filters for fname, fopts in F_opts: lexer.add_filter(fname, **fopts) highlight(code, lexer, fmter, outfile) except Exception, err: import traceback info = traceback.format_exception(*sys.exc_info()) msg = info[-1].strip() if len(info) >= 3: # extract relevant file and position info msg += '\n (f%s)' % info[-2].split('\n')[0].strip()[1:] print >>sys.stderr print >>sys.stderr, '*** Error while highlighting:' print >>sys.stderr, msg return 1 return 0
mit
wang701/nexus_9_flounder_kernel_src
scripts/tracing/dma-api/smmu.py
96
7013
"""Low-level memory management tracking""" VERBOSITY = 0 # TODO: use logging class Bitmap(object): """Just a raw bitmap for reserving the pages""" def __init__(self, size, verbosity): self._size = size self._bits = 0 self._verbosity = verbosity self._bits_allocd = 0 def _mask(self, offset, length): """length amount of 1's, shifted left by offset""" assert offset >= 0, "offset < 0" assert offset < self._size, "offset 0x%d >= size %s" % (offset, self._size) bitstring = (1 << length) - 1 return bitstring << offset def _indices(self, offset, length): """Bit numbers starting from offset""" return range(offset, offset + length) def alloc(self, offset, length): """Reserve the bits, warn if verbose and some set already""" mask = self._mask(offset, length) if (self._bits & mask) != 0 and self._verbosity >= 1: print "warning: duplicate allocation" self._bits |= mask self._bits_allocd += length return self._indices(offset, length) def free(self, offset, length): """Free the bits, warn if verbose and some not set yet""" mask = self._mask(offset, length) if (self._bits & mask) != mask and self._verbosity >= 1: print "warning: freeing freed memory, mapbits %x" % (self._bits & mask) self._bits &= ~mask self._bits_allocd -= length return self._indices(offset, length) def contains(self, offset, length): """Are some bits in the given range set?""" mask = self._mask(offset, length) return self._bits & mask def __repr__(self): return "<bitmap, %d/%d allocd>" % (self._bits_allocd, self._size) class Memory(object): """Store and handle raw bitmaps, check mapping collisions between devices""" PAGESHIFT = 12 PAGESIZE = 1 << PAGESHIFT PAGEMASK = PAGESIZE - 1 def __init__(self, addr, size, asid): """addr: lowest possible address, size: bytes, asid: arbitrary id""" assert (addr & self.PAGEMASK) == 0, addr assert (size & self.PAGEMASK) == 0, size self._addr = addr self._size = size self._end = addr + size self._asid = asid self._bitmap = Bitmap(size >> self.PAGESHIFT, VERBOSITY) self._devmaps = {} if VERBOSITY >= 1: print "memory at %08x-%08x" % (addr, addr + size) def to_bit(self, addr): """Address to bitmap position""" return addr >> self.PAGESHIFT def alloc(self, dev, addr, size): """Allocate (map) for the given device, verify things""" if addr >= self._end: if VERBOSITY >= 1: print "warning: %s mapping beyond bitmap: %08x" % (dev, addr) return [] if (addr & self.PAGEMASK) != 0: if VERBOSITY >= 1: print "warning: alloc not aligned at 0x%x, size %d (new addr 0x%x, size %d)" % ( addr, size, addr & ~self.PAGEMASK, size + (addr & self.PAGEMASK)) addr &= ~self.PAGEMASK size += addr & self.PAGEMASK if size < self.PAGESIZE: size = self.PAGESIZE for user, bmp in self._devmaps.iteritems(): if bmp.contains(self.to_bit(addr - self._addr), self.to_bit(size)): if VERBOSITY >= 1: print "warning: %s mapping [0x%x,0x%x) already used by %s" % ( dev, addr, addr + size, user) devmap = self._devmaps.setdefault(dev, Bitmap(self._bitmap._size, 0)) self._alloc(devmap, addr, size) bits = self._alloc(self._bitmap, addr, size) return bits def _alloc(self, bitmap, addr, size): """Allocate from an internal bitmap""" return bitmap.alloc(self.to_bit(addr - self._addr), self.to_bit(size)) def free(self, dev, addr, size): """Free (unmap) for the given device, verify things""" if (addr & self.PAGEMASK) != 0: if VERBOSITY >= 1: print "warning: free not aligned at 0x%x, size %d (new addr 0x%x, size %d)" % ( addr, size, addr & ~self.PAGEMASK, size + (addr & self.PAGEMASK)) addr &= ~self.PAGEMASK size += addr & self.PAGEMASK if size < self.PAGESIZE: size = self.PAGESIZE devmap = self._devmaps.setdefault(dev, Bitmap(self._bitmap._size, 0)) owners = [] for user, bmp in self._devmaps.iteritems(): if bmp.contains(self.to_bit(addr - self._addr), self.to_bit(size)): owners.append((user, bmp)) if len(owners) == 0: if VERBOSITY >= 1: print "warning: %s freeing 0x%x that nobody owns" % (dev, addr) elif len(owners) == 1: if owners[0][0] != dev and VERBOSITY >= 2: print "note: %s freeing 0x%x allocd by %s" % ( dev, addr, owners[0][0]) devmap = owners[0][1] self._free(devmap, addr, size) bits = self._free(self._bitmap, addr, size) return bits def _free(self, bitmap, addr, size): """Free from an internal bitmap""" return bitmap.free(self.to_bit(addr - self._addr), self.to_bit(size)) class Device(object): """Keep track of allocations per device/process This needs more tricky work for tracking inter-process maps/unmaps :( """ def __init__(self, name, mem): self._name = name self._mem = mem self._max_alloc = 0 self._cur_alloc = 0 self._alloc_history = [] self._addresses = [] def alloc(self, addr, size): pages = self._mem.alloc(self, addr, size) if pages is not False: self._cur_alloc += size self._max_alloc = max(self._max_alloc, self._cur_alloc) self._alloc_history.append(self._cur_alloc) if addr in self._addresses: if VERBOSITY >= 1: print "warning: %s allocing dupe address %x %s" % (self._name, addr, len([x for x in self._addresses if x == addr])) self._addresses.append(addr) return pages def free(self, addr, size): pages = self._mem.free(self, addr, size) self._cur_alloc -= size if addr in self._addresses: self._addresses.remove(addr) else: if VERBOSITY >= 1: print "warning: %s freeing unallocated %x" % (self._name, addr) return pages def history_at(self, i): return self._alloc_history[i] @property def name(self): return self._name def __str__(self): return self.name def __repr__(self): return "<dev: %s>" % self.name @property def max_allocated(self): return self._max_alloc class AsidSpace(object): # TODO: don't pre-grep by archdata but put devices' mem maps here. pass
gpl-2.0
TheoChevalier/bedrock
bedrock/mozorg/tests/test_models.py
3
4006
# -*- coding: utf-8 -*- # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from django.core.cache import cache from django.db.utils import DatabaseError from django.db.models.signals import post_save from django.test import override_settings from mock import patch from pathlib2 import Path from bedrock.mozorg.models import BlogArticle, TwitterCache from bedrock.mozorg.tests import TestCase HACKS_FILE = Path(__file__).parent.joinpath('test_files', 'data', 'hacks-blog.xml') TEST_BLOG_FEEDS = { 'hacks': { 'name': 'Hacks', 'url': 'https://hacks.mozilla.org', 'feed_url': str(HACKS_FILE), } } @override_settings(BLOG_FEEDS=TEST_BLOG_FEEDS) class TestBlogArticle(TestCase): @classmethod def setUpClass(cls): super(TestBlogArticle, cls).setUpClass() BlogArticle.update_feeds(num_articles=4) def test_htmlify(self): a = BlogArticle.objects.first() self.assertNotIn('Continue reading', a.htmlify()) def test_ordering(self): a = BlogArticle.objects.first() self.assertEqual(a.link, 'https://hacks.mozilla.org/2016/09/firefox-49-fixes-' 'sites-designed-with-webkit-in-mind-and-more/') def test_blog_link(self): a = BlogArticle.objects.first() self.assertEqual(a.blog_link, TEST_BLOG_FEEDS['hacks']['url']) def test_parse_feed(self): feed = BlogArticle.parse_feed('dude', { 'feed_url': str(HACKS_FILE), 'name': 'The Dude Feeds', }) self.assertEqual(feed.mozorg_feed_id, 'dude') self.assertEqual(feed.mozorg_feed_name, 'The Dude Feeds') @patch('bedrock.mozorg.models.parse') def test_parse_feed_no_feed_url(self, parse_mock): BlogArticle.parse_feed('dude', { 'url': 'https://example.com', 'name': 'The Dude Feeds', }) parse_mock.assert_called_with('https://example.com/feed/atom/') @patch.object(TwitterCache.objects, 'get') class TestTwitterCacheManager(TestCase): def setUp(self): cache.clear() def test_results_cached(self, get_mock): """Results from get_tweets_for() should be cached.""" get_mock.return_value.tweets = ['dude'] tweets = TwitterCache.objects.get_tweets_for('dude') self.assertEqual(['dude'], tweets) tweets = TwitterCache.objects.get_tweets_for('dude') self.assertEqual(['dude'], tweets) get_mock.assert_called_once_with(account='dude') get_mock.return_value.tweets = ['donny'] tweets = TwitterCache.objects.get_tweets_for('donny') self.assertEqual(['donny'], tweets) tweets = TwitterCache.objects.get_tweets_for('donny') self.assertEqual(['donny'], tweets) self.assertEqual(get_mock.call_count, 2) def test_errors_fail_silently(self, get_mock): """Errors should return an empty list""" get_mock.side_effect = TwitterCache.DoesNotExist self.assertEqual(TwitterCache.objects.get_tweets_for('dude'), []) self.assertEqual(TwitterCache.objects.get_tweets_for('dude'), []) # and even errors should be cached get_mock.assert_called_once_with(account='dude') get_mock.reset_mock() get_mock.side_effect = DatabaseError self.assertEqual(TwitterCache.objects.get_tweets_for('walter'), []) self.assertEqual(TwitterCache.objects.get_tweets_for('walter'), []) # and even errors should be cached get_mock.assert_called_once_with(account='walter') @patch('bedrock.mozorg.models.cache_tweets') def test_cache_post_save(self, mock_cache_tweets, get_mock): post_save.send(TwitterCache, instance=TwitterCache(account='me', tweets=['I twote'])) mock_cache_tweets.assert_called_once_with('me', ['I twote'])
mpl-2.0
h4ck3rm1k3/ansible
docsite/build-site.py
211
2937
#!/usr/bin/env python # (c) 2012, Michael DeHaan <[email protected]> # # This file is part of the Ansible Documentation # # 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/>. __docformat__ = 'restructuredtext' import os import sys import traceback try: from sphinx.application import Sphinx except ImportError: print "#################################" print "Dependency missing: Python Sphinx" print "#################################" sys.exit(1) import os class SphinxBuilder(object): """ Creates HTML documentation using Sphinx. """ def __init__(self): """ Run the DocCommand. """ print "Creating html documentation ..." try: buildername = 'html' outdir = os.path.abspath(os.path.join(os.getcwd(), "htmlout")) # Create the output directory if it doesn't exist if not os.access(outdir, os.F_OK): os.mkdir(outdir) doctreedir = os.path.join('./', '.doctrees') confdir = os.path.abspath('./') srcdir = os.path.abspath('rst') freshenv = True # Create the builder app = Sphinx(srcdir, confdir, outdir, doctreedir, buildername, {}, sys.stdout, sys.stderr, freshenv) app.builder.build_all() except ImportError, ie: traceback.print_exc() except Exception, ex: print >> sys.stderr, "FAIL! exiting ... (%s)" % ex def build_docs(self): self.app.builder.build_all() def build_rst_docs(): docgen = SphinxBuilder() if __name__ == '__main__': if '-h' in sys.argv or '--help' in sys.argv: print "This script builds the html documentation from rst/asciidoc sources.\n" print " Run 'make docs' to build everything." print " Run 'make viewdocs' to build and then preview in a web browser." sys.exit(0) build_rst_docs() if "view" in sys.argv: import webbrowser if not webbrowser.open('htmlout/index.html'): print >> sys.stderr, "Could not open on your webbrowser."
gpl-3.0
myfluxi/android_kernel_lge_hammerhead
scripts/gcc-wrapper.py
181
3495
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011-2012, The Linux Foundation. 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 Linux Foundation 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, FITNESS FOR A PARTICULAR PURPOSE AND # NON-INFRINGEMENT 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. # Invoke gcc, looking for warnings, and causing a failure if there are # non-whitelisted warnings. import errno import re import os import sys import subprocess # Note that gcc uses unicode, which may depend on the locale. TODO: # force LANG to be set to en_US.UTF-8 to get consistent warnings. allowed_warnings = set([ "return_address.c:62", "hci_conn.c:407", "cpufreq_interactive.c:804", "cpufreq_interactive.c:847", "ene_ub6250.c:2118", ]) # Capture the name of the object file, can find it. ofile = None warning_re = re.compile(r'''(.*/|)([^/]+\.[a-z]+:\d+):(\d+:)? warning:''') def interpret_warning(line): """Decode the message from gcc. The messages we care about have a filename, and a warning""" line = line.rstrip('\n') m = warning_re.match(line) if m and m.group(2) not in allowed_warnings: print "error, forbidden warning:", m.group(2) # If there is a warning, remove any object if it exists. if ofile: try: os.remove(ofile) except OSError: pass sys.exit(1) def run_gcc(): args = sys.argv[1:] # Look for -o try: i = args.index('-o') global ofile ofile = args[i+1] except (ValueError, IndexError): pass compiler = sys.argv[0] try: proc = subprocess.Popen(args, stderr=subprocess.PIPE) for line in proc.stderr: print line, interpret_warning(line) result = proc.wait() except OSError as e: result = e.errno if result == errno.ENOENT: print args[0] + ':',e.strerror print 'Is your PATH set correctly?' else: print ' '.join(args), str(e) return result if __name__ == '__main__': status = run_gcc() sys.exit(status)
gpl-2.0
pjaehrling/finetuneAlexVGG
preprocessing/tf_models/inception.py
1
13193
# 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. # ============================================================================== """Provides utilities to preprocess images for the Inception networks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow.python.ops import control_flow_ops def apply_with_random_selector(x, func, num_cases): """Computes func(x, sel), with sel sampled from [0...num_cases-1]. Args: x: input Tensor. func: Python function to apply. num_cases: Python int32, number of cases to sample sel from. Returns: The result of func(x, sel), where func receives the value of the selector as a python integer, but sel is sampled dynamically. """ sel = tf.random_uniform([], maxval=num_cases, dtype=tf.int32) # Pass the real x only to one of the func calls. return control_flow_ops.merge([ func(control_flow_ops.switch(x, tf.equal(sel, case))[1], case) for case in range(num_cases)])[0] def distort_color(image, color_ordering=0, fast_mode=True, scope=None): """Distort the color of a Tensor image. Each color distortion is non-commutative and thus ordering of the color ops matters. Ideally we would randomly permute the ordering of the color ops. Rather then adding that level of complication, we select a distinct ordering of color ops for each preprocessing thread. Args: image: 3-D Tensor containing single image in [0, 1]. color_ordering: Python int, a type of distortion (valid values: 0-3). fast_mode: Avoids slower ops (random_hue and random_contrast) scope: Optional scope for name_scope. Returns: 3-D Tensor color-distorted image on range [0, 1] Raises: ValueError: if color_ordering not in [0, 3] """ with tf.name_scope(scope, 'distort_color', [image]): if fast_mode: if color_ordering == 0: image = tf.image.random_brightness(image, max_delta=32. / 255.) image = tf.image.random_saturation(image, lower=0.5, upper=1.5) else: image = tf.image.random_saturation(image, lower=0.5, upper=1.5) image = tf.image.random_brightness(image, max_delta=32. / 255.) else: if color_ordering == 0: image = tf.image.random_brightness(image, max_delta=32. / 255.) image = tf.image.random_saturation(image, lower=0.5, upper=1.5) image = tf.image.random_hue(image, max_delta=0.2) image = tf.image.random_contrast(image, lower=0.5, upper=1.5) elif color_ordering == 1: image = tf.image.random_saturation(image, lower=0.5, upper=1.5) image = tf.image.random_brightness(image, max_delta=32. / 255.) image = tf.image.random_contrast(image, lower=0.5, upper=1.5) image = tf.image.random_hue(image, max_delta=0.2) elif color_ordering == 2: image = tf.image.random_contrast(image, lower=0.5, upper=1.5) image = tf.image.random_hue(image, max_delta=0.2) image = tf.image.random_brightness(image, max_delta=32. / 255.) image = tf.image.random_saturation(image, lower=0.5, upper=1.5) elif color_ordering == 3: image = tf.image.random_hue(image, max_delta=0.2) image = tf.image.random_saturation(image, lower=0.5, upper=1.5) image = tf.image.random_contrast(image, lower=0.5, upper=1.5) image = tf.image.random_brightness(image, max_delta=32. / 255.) else: raise ValueError('color_ordering must be in [0, 3]') # The random_* ops do not necessarily clamp. return tf.clip_by_value(image, 0.0, 1.0) def distorted_bounding_box_crop(image, bbox, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), max_attempts=100, scope=None): """Generates cropped_image using a one of the bboxes randomly distorted. See `tf.image.sample_distorted_bounding_box` for more documentation. Args: image: 3-D Tensor of image (it will be converted to floats in [0, 1]). bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates are arranged as [ymin, xmin, ymax, xmax]. If num_boxes is 0 then it would use the whole image. min_object_covered: An optional `float`. Defaults to `0.1`. The cropped area of the image must contain at least this fraction of any bounding box supplied. aspect_ratio_range: An optional list of `floats`. The cropped area of the image must have an aspect ratio = width / height within this range. area_range: An optional list of `floats`. The cropped area of the image must contain a fraction of the supplied image within in this range. max_attempts: An optional `int`. Number of attempts at generating a cropped region of the image of the specified constraints. After `max_attempts` failures, return the entire image. scope: Optional scope for name_scope. Returns: A tuple, a 3-D Tensor cropped_image and the distorted bbox """ with tf.name_scope(scope, 'distorted_bounding_box_crop', [image, bbox]): # Each bounding box has shape [1, num_boxes, box coords] and # the coordinates are ordered [ymin, xmin, ymax, xmax]. # A large fraction of image datasets contain a human-annotated bounding # box delineating the region of the image containing the object of interest. # We choose to create a new bounding box for the object which is a randomly # distorted version of the human-annotated bounding box that obeys an # allowed range of aspect ratios, sizes and overlap with the human-annotated # bounding box. If no box is supplied, then we assume the bounding box is # the entire image. sample_distorted_bounding_box = tf.image.sample_distorted_bounding_box( tf.shape(image), bounding_boxes=bbox, min_object_covered=min_object_covered, aspect_ratio_range=aspect_ratio_range, area_range=area_range, max_attempts=max_attempts, use_image_if_no_bounding_boxes=True) bbox_begin, bbox_size, distort_bbox = sample_distorted_bounding_box # Crop the image to the specified bounding box. cropped_image = tf.slice(image, bbox_begin, bbox_size) return cropped_image, distort_bbox def preprocess_for_train(image, height, width, bbox, fast_mode=True, scope=None): """Distort one image for training a network. Distorting images provides a useful technique for augmenting the data set during training in order to make the network invariant to aspects of the image that do not effect the label. Additionally it would create image_summaries to display the different transformations applied to the image. Args: image: 3-D Tensor of image. If dtype is tf.float32 then the range should be [0, 1], otherwise it would converted to tf.float32 assuming that the range is [0, MAX], where MAX is largest positive representable number for int(8/16/32) data type (see `tf.image.convert_image_dtype` for details). height: integer width: integer bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates are arranged as [ymin, xmin, ymax, xmax]. fast_mode: Optional boolean, if True avoids slower transformations (i.e. bi-cubic resizing, random_hue or random_contrast). scope: Optional scope for name_scope. Returns: 3-D float Tensor of distorted image used for training with range [-1, 1]. """ with tf.name_scope(scope, 'distort_image', [image, height, width, bbox]): if bbox is None: bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4]) if image.dtype != tf.float32: image = tf.image.convert_image_dtype(image, dtype=tf.float32) # Each bounding box has shape [1, num_boxes, box coords] and # the coordinates are ordered [ymin, xmin, ymax, xmax]. image_with_box = tf.image.draw_bounding_boxes(tf.expand_dims(image, 0), bbox) tf.summary.image('image_with_bounding_boxes', image_with_box) distorted_image, distorted_bbox = distorted_bounding_box_crop(image, bbox) # Restore the shape since the dynamic slice based upon the bbox_size loses the third dimension. distorted_image.set_shape([None, None, 3]) image_with_distorted_box = tf.image.draw_bounding_boxes(tf.expand_dims(image, 0), distorted_bbox) tf.summary.image('images_with_distorted_bounding_box', image_with_distorted_box) # This resizing operation may distort the images because the aspect ratio is not respected. # We select a resize method in a round robin fashion based on the thread number. # Note that ResizeMethod contains 4 enumerated resizing methods. # We select only 1 case for fast_mode bilinear. num_resize_cases = 1 if fast_mode else 4 distorted_image = apply_with_random_selector( distorted_image, lambda x, method: tf.image.resize_images(x, [height, width], method), num_cases=num_resize_cases ) tf.summary.image('cropped_resized_image', tf.expand_dims(distorted_image, 0)) # Randomly flip the image horizontally. distorted_image = tf.image.random_flip_left_right(distorted_image) # Randomly distort the colors. There are 4 ways to do it. distorted_image = apply_with_random_selector( distorted_image, lambda x, ordering: distort_color(x, ordering, fast_mode), num_cases=4 ) tf.summary.image('final_distorted_image', tf.expand_dims(distorted_image, 0)) distorted_image = tf.subtract(distorted_image, 0.5) distorted_image = tf.multiply(distorted_image, 2.0) return distorted_image def preprocess_for_eval(image, height, width, central_fraction=0.875, scope=None): """Prepare one image for evaluation. If height and width are specified it would output an image with that size by applying resize_bilinear. If central_fraction is specified it would crop the central fraction of the input image. Args: image: 3-D Tensor of image. If dtype is tf.float32 then the range should be [0, 1], otherwise it would converted to tf.float32 assuming that the range is [0, MAX], where MAX is largest positive representable number for int(8/16/32) data type (see `tf.image.convert_image_dtype` for details). height: integer width: integer central_fraction: Optional Float, fraction of the image to crop. scope: Optional scope for name_scope. Returns: 3-D float Tensor of prepared image. """ with tf.name_scope(scope, 'eval_image', [image, height, width]): if image.dtype != tf.float32: image = tf.image.convert_image_dtype(image, dtype=tf.float32) # Crop the central region of the image with an area containing 87.5% of # the original image. if central_fraction: image = tf.image.central_crop(image, central_fraction=central_fraction) if height and width: # Resize the image to the specified height and width. image = tf.expand_dims(image, 0) image = tf.image.resize_bilinear(image, [height, width], align_corners=False) image = tf.squeeze(image, [0]) image = tf.subtract(image, 0.5) image = tf.multiply(image, 2.0) return image def preprocess_image(image, output_height, output_width, is_training=False, bbox=None, fast_mode=True): """Pre-process one image for training or evaluation. Args: image: 3-D Tensor [height, width, channels] with the image. If dtype is tf.float32 then the range should be [0, 1], otherwise it would converted to tf.float32 assuming that the range is [0, MAX], where MAX is largest positive representable number for int(8/16/32) data type (see `tf.image.convert_image_dtype` for details). height: integer, image expected height. width: integer, image expected width. is_training: Boolean. If true it would transform an image for train, otherwise it would transform it for evaluation. bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates are arranged as [ymin, xmin, ymax, xmax]. fast_mode: Optional boolean, if True avoids slower transformations. Returns: 3-D float Tensor containing an appropriately scaled image Raises: ValueError: if user does not provide bounding box """ if is_training: return preprocess_for_train(image, output_height, output_width, bbox, fast_mode) else: return preprocess_for_eval(image, output_height, output_width)
apache-2.0
alikins/ansible
test/units/module_utils/facts/base.py
118
2325
# base unit test classes for ansible/module_utils/facts/ tests # -*- coding: utf-8 -*- # # 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) __metaclass__ = type from ansible.compat.tests import unittest from ansible.compat.tests.mock import Mock class BaseFactsTest(unittest.TestCase): # just a base class, not an actual test __test__ = False gather_subset = ['all'] valid_subsets = None fact_namespace = None collector_class = None # a dict ansible_facts. Some fact collectors depend on facts gathered by # other collectors (like 'ansible_architecture' or 'ansible_system') which # can be passed via the collected_facts arg to collect() collected_facts = None def _mock_module(self): mock_module = Mock() mock_module.params = {'gather_subset': self.gather_subset, 'gather_timeout': 5, 'filter': '*'} mock_module.get_bin_path = Mock(return_value=None) return mock_module def test_collect(self): module = self._mock_module() fact_collector = self.collector_class() facts_dict = fact_collector.collect(module=module, collected_facts=self.collected_facts) self.assertIsInstance(facts_dict, dict) return facts_dict def test_collect_with_namespace(self): module = self._mock_module() fact_collector = self.collector_class() facts_dict = fact_collector.collect_with_namespace(module=module, collected_facts=self.collected_facts) self.assertIsInstance(facts_dict, dict) return facts_dict
gpl-3.0
ganzenmg/lammps_current
tools/i-pi/ipi/inputs/atoms.py
33
5049
"""Deals with creating the atoms class. Copyright (C) 2013, Joshua More and Michele Ceriotti 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/>. Generates an atoms class either from a set of positions and momenta. This class is only used if no beads tag is present in the xml file. Classes: InputAtoms: Deals with creating the Atoms object from a file, and writing the checkpoints. """ import numpy as np from ipi.engine.atoms import * from ipi.utils.inputvalue import * from ipi.utils.depend import * from ipi.utils.units import unit_to_internal __all__ = ['InputAtoms'] class InputAtoms(Input): """Atoms input class. Handles generating the appropriate atoms class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: natoms: An optional integer giving the number of atoms. Defaults to 0. q: An optional array giving the atom positions. Defaults to an empty array with no elements. p: An optional array giving the atom momenta. Defaults to an empty array with no elements. m: An optional array giving the atom masses. Defaults to an empty array with no elements. names: An optional array giving the atom names. Defaults to an empty array with no elements """ fields={ "natoms" : (InputValue, {"dtype" : int, "default" : 0, "help" : "The number of atoms." }), "q" : (InputArray, {"dtype" : float, "default" : input_default(factory=np.zeros, args=(0,)), "help" : "The positions of the atoms, in the format [x1, y1, z1, x2, ... ].", "dimension" : "length" }), "p" : (InputArray, {"dtype" : float, "default" : input_default(factory=np.zeros, args=(0,)), "help" : "The momenta of the atoms, in the format [px1, py1, pz1, px2, ... ].", "dimension" : "momentum" }), "m" : (InputArray, {"dtype" : float, "default" : input_default(factory=np.zeros, args=(0,)), "help" : "The masses of the atoms, in the format [m1, m2, ... ].", "dimension" : "mass" }), "names" : (InputArray, {"dtype" : str, "default" : input_default(factory=np.zeros, args=(0,), kwargs = {'dtype': np.dtype('|S6')}), "help" : "The names of the atoms, in the format [name1, name2, ... ]." }) } default_help = "Deals with a single replica of the system or classical simulations." default_label = "ATOMS" def store(self, atoms): """Takes an Atoms instance and stores a minimal representation of it. Args: atoms: An Atoms object from which to initialise from. filename: An optional string giving a filename to take the atom positions from. Defaults to ''. """ super(InputAtoms,self).store() self.natoms.store(atoms.natoms) self.q.store(depstrip(atoms.q)) self.p.store(depstrip(atoms.p)) self.m.store(depstrip(atoms.m)) self.names.store(depstrip(atoms.names)) def fetch(self): """Creates an atoms object. Returns: An atoms object of the appropriate type and with the appropriate properties given the attributes of the InputAtoms object. """ super(InputAtoms,self).fetch() atoms = Atoms(self.natoms.fetch()) atoms.q = self.q.fetch() atoms.p = self.p.fetch() atoms.m = self.m.fetch() atoms.names = self.names.fetch() return atoms def write(self, name="", indent=""): """Overloads Input write() function so that nothing is written if no atoms are present. This occurs if the beads object has been specified, so that the classical atoms object is not initialized. Returns: A string giving the appropriate xml tags for the checkpoint file. """ if self.natoms.fetch() > 0: return super(InputAtoms,self).write(name=name,indent=indent) else: return ""
gpl-2.0
xq262144/hue
desktop/core/ext-py/boto-2.46.1/boto/fps/__init__.py
429
1101
# Copyright (c) 2008, Chris Moyer http://coredumped.org # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. #
apache-2.0
hanv89/api-client-python
lib/pyasn1/type/namedtype.py
162
5725
# NamedType specification for constructed types import sys from pyasn1.type import tagmap from pyasn1 import error class NamedType: isOptional = 0 isDefaulted = 0 def __init__(self, name, t): self.__name = name; self.__type = t def __repr__(self): return '%s(%r, %r)' % ( self.__class__.__name__, self.__name, self.__type ) def __eq__(self, other): return tuple(self) == tuple(other) def __ne__(self, other): return tuple(self) != tuple(other) def __lt__(self, other): return tuple(self) < tuple(other) def __le__(self, other): return tuple(self) <= tuple(other) def __gt__(self, other): return tuple(self) > tuple(other) def __ge__(self, other): return tuple(self) >= tuple(other) def __hash__(self): return hash(tuple(self)) def getType(self): return self.__type def getName(self): return self.__name def __getitem__(self, idx): if idx == 0: return self.__name if idx == 1: return self.__type raise IndexError() class OptionalNamedType(NamedType): isOptional = 1 class DefaultedNamedType(NamedType): isDefaulted = 1 class NamedTypes: def __init__(self, *namedTypes): self.__namedTypes = namedTypes self.__namedTypesLen = len(self.__namedTypes) self.__minTagSet = None self.__tagToPosIdx = {}; self.__nameToPosIdx = {} self.__tagMap = { False: None, True: None } self.__ambigiousTypes = {} def __repr__(self): return '%s(%s)' % ( self.__class__.__name__, ', '.join([ repr(x) for x in self.__namedTypes ]) ) def __eq__(self, other): return tuple(self) == tuple(other) def __ne__(self, other): return tuple(self) != tuple(other) def __lt__(self, other): return tuple(self) < tuple(other) def __le__(self, other): return tuple(self) <= tuple(other) def __gt__(self, other): return tuple(self) > tuple(other) def __ge__(self, other): return tuple(self) >= tuple(other) def __hash__(self): return hash(tuple(self)) def __getitem__(self, idx): return self.__namedTypes[idx] if sys.version_info[0] <= 2: def __nonzero__(self): return bool(self.__namedTypesLen) else: def __bool__(self): return bool(self.__namedTypesLen) def __len__(self): return self.__namedTypesLen def clone(self): return self.__class__(*self.__namedTypes) def getTypeByPosition(self, idx): if idx < 0 or idx >= self.__namedTypesLen: raise error.PyAsn1Error('Type position out of range') else: return self.__namedTypes[idx].getType() def getPositionByType(self, tagSet): if not self.__tagToPosIdx: idx = self.__namedTypesLen while idx > 0: idx = idx - 1 tagMap = self.__namedTypes[idx].getType().getTagMap() for t in tagMap.getPosMap(): if t in self.__tagToPosIdx: raise error.PyAsn1Error('Duplicate type %s' % (t,)) self.__tagToPosIdx[t] = idx try: return self.__tagToPosIdx[tagSet] except KeyError: raise error.PyAsn1Error('Type %s not found' % (tagSet,)) def getNameByPosition(self, idx): try: return self.__namedTypes[idx].getName() except IndexError: raise error.PyAsn1Error('Type position out of range') def getPositionByName(self, name): if not self.__nameToPosIdx: idx = self.__namedTypesLen while idx > 0: idx = idx - 1 n = self.__namedTypes[idx].getName() if n in self.__nameToPosIdx: raise error.PyAsn1Error('Duplicate name %s' % (n,)) self.__nameToPosIdx[n] = idx try: return self.__nameToPosIdx[name] except KeyError: raise error.PyAsn1Error('Name %s not found' % (name,)) def __buildAmbigiousTagMap(self): ambigiousTypes = () idx = self.__namedTypesLen while idx > 0: idx = idx - 1 t = self.__namedTypes[idx] if t.isOptional or t.isDefaulted: ambigiousTypes = (t, ) + ambigiousTypes else: ambigiousTypes = (t, ) self.__ambigiousTypes[idx] = NamedTypes(*ambigiousTypes) def getTagMapNearPosition(self, idx): if not self.__ambigiousTypes: self.__buildAmbigiousTagMap() try: return self.__ambigiousTypes[idx].getTagMap() except KeyError: raise error.PyAsn1Error('Type position out of range') def getPositionNearType(self, tagSet, idx): if not self.__ambigiousTypes: self.__buildAmbigiousTagMap() try: return idx+self.__ambigiousTypes[idx].getPositionByType(tagSet) except KeyError: raise error.PyAsn1Error('Type position out of range') def genMinTagSet(self): if self.__minTagSet is None: for t in self.__namedTypes: __type = t.getType() tagSet = getattr(__type,'getMinTagSet',__type.getTagSet)() if self.__minTagSet is None or tagSet < self.__minTagSet: self.__minTagSet = tagSet return self.__minTagSet def getTagMap(self, uniq=False): if self.__tagMap[uniq] is None: tagMap = tagmap.TagMap() for nt in self.__namedTypes: tagMap = tagMap.clone( nt.getType(), nt.getType().getTagMap(), uniq ) self.__tagMap[uniq] = tagMap return self.__tagMap[uniq]
apache-2.0
debugger22/sympy
sympy/functions/special/hyper.py
56
33825
"""Hypergeometric and Meijer G-functions""" from __future__ import print_function, division from sympy.core import S, I, pi, oo, ilcm, Mod from sympy.core.function import Function, Derivative, ArgumentIndexError from sympy.core.containers import Tuple from sympy.core.compatibility import reduce, range from sympy.core.mul import Mul from sympy.core.symbol import Dummy from sympy.functions import (sqrt, exp, log, sin, cos, asin, atan, sinh, cosh, asinh, acosh, atanh, acoth) class TupleArg(Tuple): def limit(self, x, xlim, dir='+'): """ Compute limit x->xlim. """ from sympy.series.limits import limit return TupleArg(*[limit(f, x, xlim, dir) for f in self.args]) # TODO should __new__ accept **options? # TODO should constructors should check if parameters are sensible? def _prep_tuple(v): """ Turn an iterable argument V into a Tuple and unpolarify, since both hypergeometric and meijer g-functions are unbranched in their parameters. Examples ======== >>> from sympy.functions.special.hyper import _prep_tuple >>> _prep_tuple([1, 2, 3]) (1, 2, 3) >>> _prep_tuple((4, 5)) (4, 5) >>> _prep_tuple((7, 8, 9)) (7, 8, 9) """ from sympy import unpolarify return TupleArg(*[unpolarify(x) for x in v]) class TupleParametersBase(Function): """ Base class that takes care of differentiation, when some of the arguments are actually tuples. """ # This is not deduced automatically since there are Tuples as arguments. is_commutative = True def _eval_derivative(self, s): try: res = 0 if self.args[0].has(s) or self.args[1].has(s): for i, p in enumerate(self._diffargs): m = self._diffargs[i].diff(s) if m != 0: res += self.fdiff((1, i))*m return res + self.fdiff(3)*self.args[2].diff(s) except (ArgumentIndexError, NotImplementedError): return Derivative(self, s) class hyper(TupleParametersBase): r""" The (generalized) hypergeometric function is defined by a series where the ratios of successive terms are a rational function of the summation index. When convergent, it is continued analytically to the largest possible domain. The hypergeometric function depends on two vectors of parameters, called the numerator parameters :math:`a_p`, and the denominator parameters :math:`b_q`. It also has an argument :math:`z`. The series definition is .. math :: {}_pF_q\left(\begin{matrix} a_1, \dots, a_p \\ b_1, \dots, b_q \end{matrix} \middle| z \right) = \sum_{n=0}^\infty \frac{(a_1)_n \dots (a_p)_n}{(b_1)_n \dots (b_q)_n} \frac{z^n}{n!}, where :math:`(a)_n = (a)(a+1)\dots(a+n-1)` denotes the rising factorial. If one of the :math:`b_q` is a non-positive integer then the series is undefined unless one of the `a_p` is a larger (i.e. smaller in magnitude) non-positive integer. If none of the :math:`b_q` is a non-positive integer and one of the :math:`a_p` is a non-positive integer, then the series reduces to a polynomial. To simplify the following discussion, we assume that none of the :math:`a_p` or :math:`b_q` is a non-positive integer. For more details, see the references. The series converges for all :math:`z` if :math:`p \le q`, and thus defines an entire single-valued function in this case. If :math:`p = q+1` the series converges for :math:`|z| < 1`, and can be continued analytically into a half-plane. If :math:`p > q+1` the series is divergent for all :math:`z`. Note: The hypergeometric function constructor currently does *not* check if the parameters actually yield a well-defined function. Examples ======== The parameters :math:`a_p` and :math:`b_q` can be passed as arbitrary iterables, for example: >>> from sympy.functions import hyper >>> from sympy.abc import x, n, a >>> hyper((1, 2, 3), [3, 4], x) hyper((1, 2, 3), (3, 4), x) There is also pretty printing (it looks better using unicode): >>> from sympy import pprint >>> pprint(hyper((1, 2, 3), [3, 4], x), use_unicode=False) _ |_ /1, 2, 3 | \ | | | x| 3 2 \ 3, 4 | / The parameters must always be iterables, even if they are vectors of length one or zero: >>> hyper((1, ), [], x) hyper((1,), (), x) But of course they may be variables (but if they depend on x then you should not expect much implemented functionality): >>> hyper((n, a), (n**2,), x) hyper((n, a), (n**2,), x) The hypergeometric function generalizes many named special functions. The function hyperexpand() tries to express a hypergeometric function using named special functions. For example: >>> from sympy import hyperexpand >>> hyperexpand(hyper([], [], x)) exp(x) You can also use expand_func: >>> from sympy import expand_func >>> expand_func(x*hyper([1, 1], [2], -x)) log(x + 1) More examples: >>> from sympy import S >>> hyperexpand(hyper([], [S(1)/2], -x**2/4)) cos(x) >>> hyperexpand(x*hyper([S(1)/2, S(1)/2], [S(3)/2], x**2)) asin(x) We can also sometimes hyperexpand parametric functions: >>> from sympy.abc import a >>> hyperexpand(hyper([-a], [], x)) (-x + 1)**a See Also ======== sympy.simplify.hyperexpand sympy.functions.special.gamma_functions.gamma meijerg References ========== .. [1] Luke, Y. L. (1969), The Special Functions and Their Approximations, Volume 1 .. [2] http://en.wikipedia.org/wiki/Generalized_hypergeometric_function """ def __new__(cls, ap, bq, z): # TODO should we check convergence conditions? return Function.__new__(cls, _prep_tuple(ap), _prep_tuple(bq), z) @classmethod def eval(cls, ap, bq, z): from sympy import unpolarify if len(ap) <= len(bq): nz = unpolarify(z) if z != nz: return hyper(ap, bq, nz) def fdiff(self, argindex=3): if argindex != 3: raise ArgumentIndexError(self, argindex) nap = Tuple(*[a + 1 for a in self.ap]) nbq = Tuple(*[b + 1 for b in self.bq]) fac = Mul(*self.ap)/Mul(*self.bq) return fac*hyper(nap, nbq, self.argument) def _eval_expand_func(self, **hints): from sympy import gamma, hyperexpand if len(self.ap) == 2 and len(self.bq) == 1 and self.argument == 1: a, b = self.ap c = self.bq[0] return gamma(c)*gamma(c - a - b)/gamma(c - a)/gamma(c - b) return hyperexpand(self) def _eval_rewrite_as_Sum(self, ap, bq, z): from sympy.functions import factorial, RisingFactorial, Piecewise from sympy import Sum n = Dummy("n", integer=True) rfap = Tuple(*[RisingFactorial(a, n) for a in ap]) rfbq = Tuple(*[RisingFactorial(b, n) for b in bq]) coeff = Mul(*rfap) / Mul(*rfbq) return Piecewise((Sum(coeff * z**n / factorial(n), (n, 0, oo)), self.convergence_statement), (self, True)) @property def argument(self): """ Argument of the hypergeometric function. """ return self.args[2] @property def ap(self): """ Numerator parameters of the hypergeometric function. """ return Tuple(*self.args[0]) @property def bq(self): """ Denominator parameters of the hypergeometric function. """ return Tuple(*self.args[1]) @property def _diffargs(self): return self.ap + self.bq @property def eta(self): """ A quantity related to the convergence of the series. """ return sum(self.ap) - sum(self.bq) @property def radius_of_convergence(self): """ Compute the radius of convergence of the defining series. Note that even if this is not oo, the function may still be evaluated outside of the radius of convergence by analytic continuation. But if this is zero, then the function is not actually defined anywhere else. >>> from sympy.functions import hyper >>> from sympy.abc import z >>> hyper((1, 2), [3], z).radius_of_convergence 1 >>> hyper((1, 2, 3), [4], z).radius_of_convergence 0 >>> hyper((1, 2), (3, 4), z).radius_of_convergence oo """ if any(a.is_integer and (a <= 0) == True for a in self.ap + self.bq): aints = [a for a in self.ap if a.is_Integer and (a <= 0) == True] bints = [a for a in self.bq if a.is_Integer and (a <= 0) == True] if len(aints) < len(bints): return S(0) popped = False for b in bints: cancelled = False while aints: a = aints.pop() if a >= b: cancelled = True break popped = True if not cancelled: return S(0) if aints or popped: # There are still non-positive numerator parameters. # This is a polynomial. return oo if len(self.ap) == len(self.bq) + 1: return S(1) elif len(self.ap) <= len(self.bq): return oo else: return S(0) @property def convergence_statement(self): """ Return a condition on z under which the series converges. """ from sympy import And, Or, re, Ne, oo R = self.radius_of_convergence if R == 0: return False if R == oo: return True # The special functions and their approximations, page 44 e = self.eta z = self.argument c1 = And(re(e) < 0, abs(z) <= 1) c2 = And(0 <= re(e), re(e) < 1, abs(z) <= 1, Ne(z, 1)) c3 = And(re(e) >= 1, abs(z) < 1) return Or(c1, c2, c3) def _eval_simplify(self, ratio, measure): from sympy.simplify.hyperexpand import hyperexpand return hyperexpand(self) def _sage_(self): import sage.all as sage ap = [arg._sage_() for arg in self.args[0]] bq = [arg._sage_() for arg in self.args[1]] return sage.hypergeometric(ap, bq, self.argument._sage_()) class meijerg(TupleParametersBase): r""" The Meijer G-function is defined by a Mellin-Barnes type integral that resembles an inverse Mellin transform. It generalizes the hypergeometric functions. The Meijer G-function depends on four sets of parameters. There are "*numerator parameters*" :math:`a_1, \dots, a_n` and :math:`a_{n+1}, \dots, a_p`, and there are "*denominator parameters*" :math:`b_1, \dots, b_m` and :math:`b_{m+1}, \dots, b_q`. Confusingly, it is traditionally denoted as follows (note the position of `m`, `n`, `p`, `q`, and how they relate to the lengths of the four parameter vectors): .. math :: G_{p,q}^{m,n} \left(\begin{matrix}a_1, \dots, a_n & a_{n+1}, \dots, a_p \\ b_1, \dots, b_m & b_{m+1}, \dots, b_q \end{matrix} \middle| z \right). However, in sympy the four parameter vectors are always available separately (see examples), so that there is no need to keep track of the decorating sub- and super-scripts on the G symbol. The G function is defined as the following integral: .. math :: \frac{1}{2 \pi i} \int_L \frac{\prod_{j=1}^m \Gamma(b_j - s) \prod_{j=1}^n \Gamma(1 - a_j + s)}{\prod_{j=m+1}^q \Gamma(1- b_j +s) \prod_{j=n+1}^p \Gamma(a_j - s)} z^s \mathrm{d}s, where :math:`\Gamma(z)` is the gamma function. There are three possible contours which we will not describe in detail here (see the references). If the integral converges along more than one of them the definitions agree. The contours all separate the poles of :math:`\Gamma(1-a_j+s)` from the poles of :math:`\Gamma(b_k-s)`, so in particular the G function is undefined if :math:`a_j - b_k \in \mathbb{Z}_{>0}` for some :math:`j \le n` and :math:`k \le m`. The conditions under which one of the contours yields a convergent integral are complicated and we do not state them here, see the references. Note: Currently the Meijer G-function constructor does *not* check any convergence conditions. Examples ======== You can pass the parameters either as four separate vectors: >>> from sympy.functions import meijerg >>> from sympy.abc import x, a >>> from sympy.core.containers import Tuple >>> from sympy import pprint >>> pprint(meijerg((1, 2), (a, 4), (5,), [], x), use_unicode=False) __1, 2 /1, 2 a, 4 | \ /__ | | x| \_|4, 1 \ 5 | / or as two nested vectors: >>> pprint(meijerg([(1, 2), (3, 4)], ([5], Tuple()), x), use_unicode=False) __1, 2 /1, 2 3, 4 | \ /__ | | x| \_|4, 1 \ 5 | / As with the hypergeometric function, the parameters may be passed as arbitrary iterables. Vectors of length zero and one also have to be passed as iterables. The parameters need not be constants, but if they depend on the argument then not much implemented functionality should be expected. All the subvectors of parameters are available: >>> from sympy import pprint >>> g = meijerg([1], [2], [3], [4], x) >>> pprint(g, use_unicode=False) __1, 1 /1 2 | \ /__ | | x| \_|2, 2 \3 4 | / >>> g.an (1,) >>> g.ap (1, 2) >>> g.aother (2,) >>> g.bm (3,) >>> g.bq (3, 4) >>> g.bother (4,) The Meijer G-function generalizes the hypergeometric functions. In some cases it can be expressed in terms of hypergeometric functions, using Slater's theorem. For example: >>> from sympy import hyperexpand >>> from sympy.abc import a, b, c >>> hyperexpand(meijerg([a], [], [c], [b], x), allow_hyper=True) x**c*gamma(-a + c + 1)*hyper((-a + c + 1,), (-b + c + 1,), -x)/gamma(-b + c + 1) Thus the Meijer G-function also subsumes many named functions as special cases. You can use expand_func or hyperexpand to (try to) rewrite a Meijer G-function in terms of named special functions. For example: >>> from sympy import expand_func, S >>> expand_func(meijerg([[],[]], [[0],[]], -x)) exp(x) >>> hyperexpand(meijerg([[],[]], [[S(1)/2],[0]], (x/2)**2)) sin(x)/sqrt(pi) See Also ======== hyper sympy.simplify.hyperexpand References ========== .. [1] Luke, Y. L. (1969), The Special Functions and Their Approximations, Volume 1 .. [2] http://en.wikipedia.org/wiki/Meijer_G-function """ def __new__(cls, *args): if len(args) == 5: args = [(args[0], args[1]), (args[2], args[3]), args[4]] if len(args) != 3: raise TypeError("args must eiter be as, as', bs, bs', z or " "as, bs, z") def tr(p): if len(p) != 2: raise TypeError("wrong argument") return TupleArg(_prep_tuple(p[0]), _prep_tuple(p[1])) # TODO should we check convergence conditions? return Function.__new__(cls, tr(args[0]), tr(args[1]), args[2]) def fdiff(self, argindex=3): if argindex != 3: return self._diff_wrt_parameter(argindex[1]) if len(self.an) >= 1: a = list(self.an) a[0] -= 1 G = meijerg(a, self.aother, self.bm, self.bother, self.argument) return 1/self.argument * ((self.an[0] - 1)*self + G) elif len(self.bm) >= 1: b = list(self.bm) b[0] += 1 G = meijerg(self.an, self.aother, b, self.bother, self.argument) return 1/self.argument * (self.bm[0]*self - G) else: return S.Zero def _diff_wrt_parameter(self, idx): # Differentiation wrt a parameter can only be done in very special # cases. In particular, if we want to differentiate with respect to # `a`, all other gamma factors have to reduce to rational functions. # # Let MT denote mellin transform. Suppose T(-s) is the gamma factor # appearing in the definition of G. Then # # MT(log(z)G(z)) = d/ds T(s) = d/da T(s) + ... # # Thus d/da G(z) = log(z)G(z) - ... # The ... can be evaluated as a G function under the above conditions, # the formula being most easily derived by using # # d Gamma(s + n) Gamma(s + n) / 1 1 1 \ # -- ------------ = ------------ | - + ---- + ... + --------- | # ds Gamma(s) Gamma(s) \ s s + 1 s + n - 1 / # # which follows from the difference equation of the digamma function. # (There is a similar equation for -n instead of +n). # We first figure out how to pair the parameters. an = list(self.an) ap = list(self.aother) bm = list(self.bm) bq = list(self.bother) if idx < len(an): an.pop(idx) else: idx -= len(an) if idx < len(ap): ap.pop(idx) else: idx -= len(ap) if idx < len(bm): bm.pop(idx) else: bq.pop(idx - len(bm)) pairs1 = [] pairs2 = [] for l1, l2, pairs in [(an, bq, pairs1), (ap, bm, pairs2)]: while l1: x = l1.pop() found = None for i, y in enumerate(l2): if not Mod((x - y).simplify(), 1): found = i break if found is None: raise NotImplementedError('Derivative not expressible ' 'as G-function?') y = l2[i] l2.pop(i) pairs.append((x, y)) # Now build the result. res = log(self.argument)*self for a, b in pairs1: sign = 1 n = a - b base = b if n < 0: sign = -1 n = b - a base = a for k in range(n): res -= sign*meijerg(self.an + (base + k + 1,), self.aother, self.bm, self.bother + (base + k + 0,), self.argument) for a, b in pairs2: sign = 1 n = b - a base = a if n < 0: sign = -1 n = a - b base = b for k in range(n): res -= sign*meijerg(self.an, self.aother + (base + k + 1,), self.bm + (base + k + 0,), self.bother, self.argument) return res def get_period(self): """ Return a number P such that G(x*exp(I*P)) == G(x). >>> from sympy.functions.special.hyper import meijerg >>> from sympy.abc import z >>> from sympy import pi, S >>> meijerg([1], [], [], [], z).get_period() 2*pi >>> meijerg([pi], [], [], [], z).get_period() oo >>> meijerg([1, 2], [], [], [], z).get_period() oo >>> meijerg([1,1], [2], [1, S(1)/2, S(1)/3], [1], z).get_period() 12*pi """ # This follows from slater's theorem. def compute(l): # first check that no two differ by an integer for i, b in enumerate(l): if not b.is_Rational: return oo for j in range(i + 1, len(l)): if not Mod((b - l[j]).simplify(), 1): return oo return reduce(ilcm, (x.q for x in l), 1) beta = compute(self.bm) alpha = compute(self.an) p, q = len(self.ap), len(self.bq) if p == q: if beta == oo or alpha == oo: return oo return 2*pi*ilcm(alpha, beta) elif p < q: return 2*pi*beta else: return 2*pi*alpha def _eval_expand_func(self, **hints): from sympy import hyperexpand return hyperexpand(self) def _eval_evalf(self, prec): # The default code is insufficient for polar arguments. # mpmath provides an optional argument "r", which evaluates # G(z**(1/r)). I am not sure what its intended use is, but we hijack it # here in the following way: to evaluate at a number z of |argument| # less than (say) n*pi, we put r=1/n, compute z' = root(z, n) # (carefully so as not to loose the branch information), and evaluate # G(z'**(1/r)) = G(z'**n) = G(z). from sympy.functions import exp_polar, ceiling from sympy import Expr import mpmath z = self.argument znum = self.argument._eval_evalf(prec) if znum.has(exp_polar): znum, branch = znum.as_coeff_mul(exp_polar) if len(branch) != 1: return branch = branch[0].args[0]/I else: branch = S(0) n = ceiling(abs(branch/S.Pi)) + 1 znum = znum**(S(1)/n)*exp(I*branch / n) # Convert all args to mpf or mpc try: [z, r, ap, bq] = [arg._to_mpmath(prec) for arg in [znum, 1/n, self.args[0], self.args[1]]] except ValueError: return with mpmath.workprec(prec): v = mpmath.meijerg(ap, bq, z, r) return Expr._from_mpmath(v, prec) def integrand(self, s): """ Get the defining integrand D(s). """ from sympy import gamma return self.argument**s \ * Mul(*(gamma(b - s) for b in self.bm)) \ * Mul(*(gamma(1 - a + s) for a in self.an)) \ / Mul(*(gamma(1 - b + s) for b in self.bother)) \ / Mul(*(gamma(a - s) for a in self.aother)) @property def argument(self): """ Argument of the Meijer G-function. """ return self.args[2] @property def an(self): """ First set of numerator parameters. """ return Tuple(*self.args[0][0]) @property def ap(self): """ Combined numerator parameters. """ return Tuple(*(self.args[0][0] + self.args[0][1])) @property def aother(self): """ Second set of numerator parameters. """ return Tuple(*self.args[0][1]) @property def bm(self): """ First set of denominator parameters. """ return Tuple(*self.args[1][0]) @property def bq(self): """ Combined denominator parameters. """ return Tuple(*(self.args[1][0] + self.args[1][1])) @property def bother(self): """ Second set of denominator parameters. """ return Tuple(*self.args[1][1]) @property def _diffargs(self): return self.ap + self.bq @property def nu(self): """ A quantity related to the convergence region of the integral, c.f. references. """ return sum(self.bq) - sum(self.ap) @property def delta(self): """ A quantity related to the convergence region of the integral, c.f. references. """ return len(self.bm) + len(self.an) - S(len(self.ap) + len(self.bq))/2 class HyperRep(Function): """ A base class for "hyper representation functions". This is used exclusively in hyperexpand(), but fits more logically here. pFq is branched at 1 if p == q+1. For use with slater-expansion, we want define an "analytic continuation" to all polar numbers, which is continuous on circles and on the ray t*exp_polar(I*pi). Moreover, we want a "nice" expression for the various cases. This base class contains the core logic, concrete derived classes only supply the actual functions. """ @classmethod def eval(cls, *args): from sympy import unpolarify newargs = tuple(map(unpolarify, args[:-1])) + args[-1:] if args != newargs: return cls(*newargs) @classmethod def _expr_small(cls, x): """ An expression for F(x) which holds for |x| < 1. """ raise NotImplementedError @classmethod def _expr_small_minus(cls, x): """ An expression for F(-x) which holds for |x| < 1. """ raise NotImplementedError @classmethod def _expr_big(cls, x, n): """ An expression for F(exp_polar(2*I*pi*n)*x), |x| > 1. """ raise NotImplementedError @classmethod def _expr_big_minus(cls, x, n): """ An expression for F(exp_polar(2*I*pi*n + pi*I)*x), |x| > 1. """ raise NotImplementedError def _eval_rewrite_as_nonrep(self, *args): from sympy import Piecewise x, n = self.args[-1].extract_branch_factor(allow_half=True) minus = False newargs = self.args[:-1] + (x,) if not n.is_Integer: minus = True n -= S(1)/2 newerargs = newargs + (n,) if minus: small = self._expr_small_minus(*newargs) big = self._expr_big_minus(*newerargs) else: small = self._expr_small(*newargs) big = self._expr_big(*newerargs) if big == small: return small return Piecewise((big, abs(x) > 1), (small, True)) def _eval_rewrite_as_nonrepsmall(self, *args): x, n = self.args[-1].extract_branch_factor(allow_half=True) args = self.args[:-1] + (x,) if not n.is_Integer: return self._expr_small_minus(*args) return self._expr_small(*args) class HyperRep_power1(HyperRep): """ Return a representative for hyper([-a], [], z) == (1 - z)**a. """ @classmethod def _expr_small(cls, a, x): return (1 - x)**a @classmethod def _expr_small_minus(cls, a, x): return (1 + x)**a @classmethod def _expr_big(cls, a, x, n): if a.is_integer: return cls._expr_small(a, x) return (x - 1)**a*exp((2*n - 1)*pi*I*a) @classmethod def _expr_big_minus(cls, a, x, n): if a.is_integer: return cls._expr_small_minus(a, x) return (1 + x)**a*exp(2*n*pi*I*a) class HyperRep_power2(HyperRep): """ Return a representative for hyper([a, a - 1/2], [2*a], z). """ @classmethod def _expr_small(cls, a, x): return 2**(2*a - 1)*(1 + sqrt(1 - x))**(1 - 2*a) @classmethod def _expr_small_minus(cls, a, x): return 2**(2*a - 1)*(1 + sqrt(1 + x))**(1 - 2*a) @classmethod def _expr_big(cls, a, x, n): sgn = -1 if n.is_odd: sgn = 1 n -= 1 return 2**(2*a - 1)*(1 + sgn*I*sqrt(x - 1))**(1 - 2*a) \ *exp(-2*n*pi*I*a) @classmethod def _expr_big_minus(cls, a, x, n): sgn = 1 if n.is_odd: sgn = -1 return sgn*2**(2*a - 1)*(sqrt(1 + x) + sgn)**(1 - 2*a)*exp(-2*pi*I*a*n) class HyperRep_log1(HyperRep): """ Represent -z*hyper([1, 1], [2], z) == log(1 - z). """ @classmethod def _expr_small(cls, x): return log(1 - x) @classmethod def _expr_small_minus(cls, x): return log(1 + x) @classmethod def _expr_big(cls, x, n): return log(x - 1) + (2*n - 1)*pi*I @classmethod def _expr_big_minus(cls, x, n): return log(1 + x) + 2*n*pi*I class HyperRep_atanh(HyperRep): """ Represent hyper([1/2, 1], [3/2], z) == atanh(sqrt(z))/sqrt(z). """ @classmethod def _expr_small(cls, x): return atanh(sqrt(x))/sqrt(x) def _expr_small_minus(cls, x): return atan(sqrt(x))/sqrt(x) def _expr_big(cls, x, n): if n.is_even: return (acoth(sqrt(x)) + I*pi/2)/sqrt(x) else: return (acoth(sqrt(x)) - I*pi/2)/sqrt(x) def _expr_big_minus(cls, x, n): if n.is_even: return atan(sqrt(x))/sqrt(x) else: return (atan(sqrt(x)) - pi)/sqrt(x) class HyperRep_asin1(HyperRep): """ Represent hyper([1/2, 1/2], [3/2], z) == asin(sqrt(z))/sqrt(z). """ @classmethod def _expr_small(cls, z): return asin(sqrt(z))/sqrt(z) @classmethod def _expr_small_minus(cls, z): return asinh(sqrt(z))/sqrt(z) @classmethod def _expr_big(cls, z, n): return S(-1)**n*((S(1)/2 - n)*pi/sqrt(z) + I*acosh(sqrt(z))/sqrt(z)) @classmethod def _expr_big_minus(cls, z, n): return S(-1)**n*(asinh(sqrt(z))/sqrt(z) + n*pi*I/sqrt(z)) class HyperRep_asin2(HyperRep): """ Represent hyper([1, 1], [3/2], z) == asin(sqrt(z))/sqrt(z)/sqrt(1-z). """ # TODO this can be nicer @classmethod def _expr_small(cls, z): return HyperRep_asin1._expr_small(z) \ /HyperRep_power1._expr_small(S(1)/2, z) @classmethod def _expr_small_minus(cls, z): return HyperRep_asin1._expr_small_minus(z) \ /HyperRep_power1._expr_small_minus(S(1)/2, z) @classmethod def _expr_big(cls, z, n): return HyperRep_asin1._expr_big(z, n) \ /HyperRep_power1._expr_big(S(1)/2, z, n) @classmethod def _expr_big_minus(cls, z, n): return HyperRep_asin1._expr_big_minus(z, n) \ /HyperRep_power1._expr_big_minus(S(1)/2, z, n) class HyperRep_sqrts1(HyperRep): """ Return a representative for hyper([-a, 1/2 - a], [1/2], z). """ @classmethod def _expr_small(cls, a, z): return ((1 - sqrt(z))**(2*a) + (1 + sqrt(z))**(2*a))/2 @classmethod def _expr_small_minus(cls, a, z): return (1 + z)**a*cos(2*a*atan(sqrt(z))) @classmethod def _expr_big(cls, a, z, n): if n.is_even: return ((sqrt(z) + 1)**(2*a)*exp(2*pi*I*n*a) + (sqrt(z) - 1)**(2*a)*exp(2*pi*I*(n - 1)*a))/2 else: n -= 1 return ((sqrt(z) - 1)**(2*a)*exp(2*pi*I*a*(n + 1)) + (sqrt(z) + 1)**(2*a)*exp(2*pi*I*a*n))/2 @classmethod def _expr_big_minus(cls, a, z, n): if n.is_even: return (1 + z)**a*exp(2*pi*I*n*a)*cos(2*a*atan(sqrt(z))) else: return (1 + z)**a*exp(2*pi*I*n*a)*cos(2*a*atan(sqrt(z)) - 2*pi*a) class HyperRep_sqrts2(HyperRep): """ Return a representative for sqrt(z)/2*[(1-sqrt(z))**2a - (1 + sqrt(z))**2a] == -2*z/(2*a+1) d/dz hyper([-a - 1/2, -a], [1/2], z)""" @classmethod def _expr_small(cls, a, z): return sqrt(z)*((1 - sqrt(z))**(2*a) - (1 + sqrt(z))**(2*a))/2 @classmethod def _expr_small_minus(cls, a, z): return sqrt(z)*(1 + z)**a*sin(2*a*atan(sqrt(z))) @classmethod def _expr_big(cls, a, z, n): if n.is_even: return sqrt(z)/2*((sqrt(z) - 1)**(2*a)*exp(2*pi*I*a*(n - 1)) - (sqrt(z) + 1)**(2*a)*exp(2*pi*I*a*n)) else: n -= 1 return sqrt(z)/2*((sqrt(z) - 1)**(2*a)*exp(2*pi*I*a*(n + 1)) - (sqrt(z) + 1)**(2*a)*exp(2*pi*I*a*n)) def _expr_big_minus(cls, a, z, n): if n.is_even: return (1 + z)**a*exp(2*pi*I*n*a)*sqrt(z)*sin(2*a*atan(sqrt(z))) else: return (1 + z)**a*exp(2*pi*I*n*a)*sqrt(z) \ *sin(2*a*atan(sqrt(z)) - 2*pi*a) class HyperRep_log2(HyperRep): """ Represent log(1/2 + sqrt(1 - z)/2) == -z/4*hyper([3/2, 1, 1], [2, 2], z) """ @classmethod def _expr_small(cls, z): return log(S(1)/2 + sqrt(1 - z)/2) @classmethod def _expr_small_minus(cls, z): return log(S(1)/2 + sqrt(1 + z)/2) @classmethod def _expr_big(cls, z, n): if n.is_even: return (n - S(1)/2)*pi*I + log(sqrt(z)/2) + I*asin(1/sqrt(z)) else: return (n - S(1)/2)*pi*I + log(sqrt(z)/2) - I*asin(1/sqrt(z)) def _expr_big_minus(cls, z, n): if n.is_even: return pi*I*n + log(S(1)/2 + sqrt(1 + z)/2) else: return pi*I*n + log(sqrt(1 + z)/2 - S(1)/2) class HyperRep_cosasin(HyperRep): """ Represent hyper([a, -a], [1/2], z) == cos(2*a*asin(sqrt(z))). """ # Note there are many alternative expressions, e.g. as powers of a sum of # square roots. @classmethod def _expr_small(cls, a, z): return cos(2*a*asin(sqrt(z))) @classmethod def _expr_small_minus(cls, a, z): return cosh(2*a*asinh(sqrt(z))) @classmethod def _expr_big(cls, a, z, n): return cosh(2*a*acosh(sqrt(z)) + a*pi*I*(2*n - 1)) @classmethod def _expr_big_minus(cls, a, z, n): return cosh(2*a*asinh(sqrt(z)) + 2*a*pi*I*n) class HyperRep_sinasin(HyperRep): """ Represent 2*a*z*hyper([1 - a, 1 + a], [3/2], z) == sqrt(z)/sqrt(1-z)*sin(2*a*asin(sqrt(z))) """ @classmethod def _expr_small(cls, a, z): return sqrt(z)/sqrt(1 - z)*sin(2*a*asin(sqrt(z))) @classmethod def _expr_small_minus(cls, a, z): return -sqrt(z)/sqrt(1 + z)*sinh(2*a*asinh(sqrt(z))) @classmethod def _expr_big(cls, a, z, n): return -1/sqrt(1 - 1/z)*sinh(2*a*acosh(sqrt(z)) + a*pi*I*(2*n - 1)) @classmethod def _expr_big_minus(cls, a, z, n): return -1/sqrt(1 + 1/z)*sinh(2*a*asinh(sqrt(z)) + 2*a*pi*I*n)
bsd-3-clause
vodik/pacman
test/pacman/tests/upgrade078.py
23
1514
self.description = "-U --recursive upgrades outdated dependencies" # git (new package) # |-- perl (up to date) # |-- glibc (out of date, will be updated) # |-- curl (out of date, will be updated) # |-- expat (up to date) perl_lpkg = pmpkg("perl", "5.14.1-3") perl_lpkg.depends = ["glibc"] self.addpkg2db("local", perl_lpkg) glibc_lpkg = pmpkg("glibc", "2.1.3-1") self.addpkg2db("local", glibc_lpkg) curl_lpkg = pmpkg("curl", "7.20-1") self.addpkg2db("local", curl_lpkg) expat_lpkg = pmpkg("expat", "2.0.1-6") self.addpkg2db("local", expat_lpkg) # Sync db perl_sync = pmpkg("perl", "5.14.1-3") perl_sync.depends = ["glibc"] self.addpkg2db("sync", perl_sync) glibc_sync = pmpkg("glibc", "2.1.4-4") self.addpkg2db("sync", glibc_sync) curl_sync = pmpkg("curl", "7.21.7-1") self.addpkg2db("sync", curl_sync) expat_sync = pmpkg("expat", "2.0.1-6") self.addpkg2db("sync", expat_sync) p = pmpkg("git", "1.7.6-1") p.depends = ["curl", "expat", "perl"] self.addpkg(p) self.args = "-U --recursive %s" % p.filename() self.addrule("PACMAN_RETCODE=0") self.addrule("PKG_DEPENDS=git|curl") self.addrule("PKG_DEPENDS=git|expat") self.addrule("PKG_DEPENDS=git|perl") self.addrule("PKG_DEPENDS=perl|glibc") self.addrule("PKG_EXIST=git") self.addrule("PKG_VERSION=git|1.7.6-1") self.addrule("PKG_VERSION=curl|7.21.7-1") self.addrule("PKG_VERSION=glibc|2.1.4-4") self.addrule("PKG_VERSION=perl|5.14.1-3") self.addrule("PKG_VERSION=expat|2.0.1-6") # --recursive operation was removed for now self.expectfailure = True
gpl-2.0
daniel-brettschneider/SiENA
ns-3.26/src/uan/bindings/modulegen__gcc_LP64.py
38
545082
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.uan', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] module.add_class('AttributeConstructionList', import_from_module='ns.core') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer [class] module.add_class('DeviceEnergyModelContainer', import_from_module='ns.energy') ## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelHelper [class] module.add_class('DeviceEnergyModelHelper', allow_subclassing=True, import_from_module='ns.energy') ## energy-model-helper.h (module 'energy'): ns3::EnergySourceHelper [class] module.add_class('EnergySourceHelper', allow_subclassing=True, import_from_module='ns.energy') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', import_from_module='ns.core') ## 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-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-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] module.add_class('Mac48Address', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class] module.add_class('NetDeviceContainer', import_from_module='ns.network') ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData_e [enumeration] module.add_enum('TagData_e', ['MAX_SIZE'], outer_class=root_module['ns3::PacketTagList::TagData'], import_from_module='ns.network') ## uan-mac-rc.h (module 'uan'): ns3::Reservation [class] module.add_class('Reservation') ## 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') ## simulator.h (module 'core'): ns3::Simulator [enumeration] module.add_enum('', ['NO_CONTEXT'], outer_class=root_module['ns3::Simulator'], 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') ## uan-prop-model.h (module 'uan'): ns3::Tap [class] module.add_class('Tap') ## nstime.h (module 'core'): ns3::TimeWithUnit [class] module.add_class('TimeWithUnit', import_from_module='ns.core') ## traced-value.h (module 'core'): ns3::TracedValue<double> [class] module.add_class('TracedValue', import_from_module='ns.core', template_parameters=['double']) ## 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::SupportLevel [enumeration] module.add_enum('SupportLevel', ['SUPPORTED', 'DEPRECATED', 'OBSOLETE'], 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']) ## uan-address.h (module 'uan'): ns3::UanAddress [class] module.add_class('UanAddress') ## uan-address.h (module 'uan'): ns3::UanAddress [class] root_module['ns3::UanAddress'].implicitly_converts_to(root_module['ns3::Address']) ## uan-helper.h (module 'uan'): ns3::UanHelper [class] module.add_class('UanHelper') ## uan-tx-mode.h (module 'uan'): ns3::UanModesList [class] module.add_class('UanModesList') ## uan-transducer.h (module 'uan'): ns3::UanPacketArrival [class] module.add_class('UanPacketArrival') ## uan-prop-model.h (module 'uan'): ns3::UanPdp [class] module.add_class('UanPdp') ## uan-phy.h (module 'uan'): ns3::UanPhyListener [class] module.add_class('UanPhyListener', allow_subclassing=True) ## uan-tx-mode.h (module 'uan'): ns3::UanTxMode [class] module.add_class('UanTxMode') ## uan-tx-mode.h (module 'uan'): ns3::UanTxMode::ModulationType [enumeration] module.add_enum('ModulationType', ['PSK', 'QAM', 'FSK', 'OTHER'], outer_class=root_module['ns3::UanTxMode']) ## uan-tx-mode.h (module 'uan'): ns3::UanTxModeFactory [class] module.add_class('UanTxModeFactory') ## vector.h (module 'core'): ns3::Vector2D [class] module.add_class('Vector2D', import_from_module='ns.core') ## vector.h (module 'core'): ns3::Vector3D [class] module.add_class('Vector3D', import_from_module='ns.core') ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t::impl_type [enumeration] module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core') ## acoustic-modem-energy-model-helper.h (module 'uan'): ns3::AcousticModemEnergyModelHelper [class] module.add_class('AcousticModemEnergyModelHelper', parent=root_module['ns3::DeviceEnergyModelHelper']) ## 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']) ## 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::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NetDeviceQueue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NetDeviceQueue>'], 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::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::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::QueueItem', 'ns3::empty', 'ns3::DefaultDeleter<ns3::QueueItem>'], 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')) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time [class] root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable [class] module.add_class('TriangularRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## uan-header-common.h (module 'uan'): ns3::UanHeaderCommon [class] module.add_class('UanHeaderCommon', parent=root_module['ns3::Header']) ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcAck [class] module.add_class('UanHeaderRcAck', parent=root_module['ns3::Header']) ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCts [class] module.add_class('UanHeaderRcCts', parent=root_module['ns3::Header']) ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCtsGlobal [class] module.add_class('UanHeaderRcCtsGlobal', parent=root_module['ns3::Header']) ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcData [class] module.add_class('UanHeaderRcData', parent=root_module['ns3::Header']) ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcRts [class] module.add_class('UanHeaderRcRts', parent=root_module['ns3::Header']) ## uan-mac.h (module 'uan'): ns3::UanMac [class] module.add_class('UanMac', parent=root_module['ns3::Object']) ## uan-mac-aloha.h (module 'uan'): ns3::UanMacAloha [class] module.add_class('UanMacAloha', parent=root_module['ns3::UanMac']) ## uan-mac-cw.h (module 'uan'): ns3::UanMacCw [class] module.add_class('UanMacCw', parent=[root_module['ns3::UanMac'], root_module['ns3::UanPhyListener']]) ## uan-mac-rc.h (module 'uan'): ns3::UanMacRc [class] module.add_class('UanMacRc', parent=root_module['ns3::UanMac']) ## uan-mac-rc.h (module 'uan'): ns3::UanMacRc [enumeration] module.add_enum('', ['TYPE_DATA', 'TYPE_GWPING', 'TYPE_RTS', 'TYPE_CTS', 'TYPE_ACK'], outer_class=root_module['ns3::UanMacRc']) ## uan-mac-rc-gw.h (module 'uan'): ns3::UanMacRcGw [class] module.add_class('UanMacRcGw', parent=root_module['ns3::UanMac']) ## uan-noise-model.h (module 'uan'): ns3::UanNoiseModel [class] module.add_class('UanNoiseModel', parent=root_module['ns3::Object']) ## uan-noise-model-default.h (module 'uan'): ns3::UanNoiseModelDefault [class] module.add_class('UanNoiseModelDefault', parent=root_module['ns3::UanNoiseModel']) ## uan-phy.h (module 'uan'): ns3::UanPhy [class] module.add_class('UanPhy', parent=root_module['ns3::Object']) ## uan-phy.h (module 'uan'): ns3::UanPhy::State [enumeration] module.add_enum('State', ['IDLE', 'CCABUSY', 'RX', 'TX', 'SLEEP', 'DISABLED'], outer_class=root_module['ns3::UanPhy']) ## uan-phy.h (module 'uan'): ns3::UanPhyCalcSinr [class] module.add_class('UanPhyCalcSinr', parent=root_module['ns3::Object']) ## uan-phy-gen.h (module 'uan'): ns3::UanPhyCalcSinrDefault [class] module.add_class('UanPhyCalcSinrDefault', parent=root_module['ns3::UanPhyCalcSinr']) ## uan-phy-dual.h (module 'uan'): ns3::UanPhyCalcSinrDual [class] module.add_class('UanPhyCalcSinrDual', parent=root_module['ns3::UanPhyCalcSinr']) ## uan-phy-gen.h (module 'uan'): ns3::UanPhyCalcSinrFhFsk [class] module.add_class('UanPhyCalcSinrFhFsk', parent=root_module['ns3::UanPhyCalcSinr']) ## uan-phy-dual.h (module 'uan'): ns3::UanPhyDual [class] module.add_class('UanPhyDual', parent=root_module['ns3::UanPhy']) ## uan-phy-gen.h (module 'uan'): ns3::UanPhyGen [class] module.add_class('UanPhyGen', parent=root_module['ns3::UanPhy']) ## uan-phy.h (module 'uan'): ns3::UanPhyPer [class] module.add_class('UanPhyPer', parent=root_module['ns3::Object']) ## uan-phy-gen.h (module 'uan'): ns3::UanPhyPerGenDefault [class] module.add_class('UanPhyPerGenDefault', parent=root_module['ns3::UanPhyPer']) ## uan-phy-gen.h (module 'uan'): ns3::UanPhyPerUmodem [class] module.add_class('UanPhyPerUmodem', parent=root_module['ns3::UanPhyPer']) ## uan-prop-model.h (module 'uan'): ns3::UanPropModel [class] module.add_class('UanPropModel', parent=root_module['ns3::Object']) ## uan-prop-model-ideal.h (module 'uan'): ns3::UanPropModelIdeal [class] module.add_class('UanPropModelIdeal', parent=root_module['ns3::UanPropModel']) ## uan-prop-model-thorp.h (module 'uan'): ns3::UanPropModelThorp [class] module.add_class('UanPropModelThorp', parent=root_module['ns3::UanPropModel']) ## uan-transducer.h (module 'uan'): ns3::UanTransducer [class] module.add_class('UanTransducer', parent=root_module['ns3::Object']) ## uan-transducer.h (module 'uan'): ns3::UanTransducer::State [enumeration] module.add_enum('State', ['TX', 'RX'], outer_class=root_module['ns3::UanTransducer']) ## uan-transducer-hd.h (module 'uan'): ns3::UanTransducerHd [class] module.add_class('UanTransducerHd', parent=root_module['ns3::UanTransducer']) ## 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']) ## 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']) ## 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> >']) ## boolean.h (module 'core'): ns3::BooleanChecker [class] module.add_class('BooleanChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## boolean.h (module 'core'): ns3::BooleanValue [class] module.add_class('BooleanValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## channel.h (module 'network'): ns3::Channel [class] module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object']) ## 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']) ## device-energy-model.h (module 'energy'): ns3::DeviceEnergyModel [class] module.add_class('DeviceEnergyModel', import_from_module='ns.energy', parent=root_module['ns3::Object']) ## double.h (module 'core'): ns3::DoubleValue [class] module.add_class('DoubleValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## 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::EmptyAttributeAccessor [class] module.add_class('EmptyAttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::AttributeAccessor']) ## attribute.h (module 'core'): ns3::EmptyAttributeChecker [class] module.add_class('EmptyAttributeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## energy-harvester.h (module 'energy'): ns3::EnergyHarvester [class] module.add_class('EnergyHarvester', import_from_module='ns.energy', parent=root_module['ns3::Object']) ## energy-source.h (module 'energy'): ns3::EnergySource [class] module.add_class('EnergySource', import_from_module='ns.energy', parent=root_module['ns3::Object']) ## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer [class] module.add_class('EnergySourceContainer', import_from_module='ns.energy', parent=root_module['ns3::Object']) ## 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']) ## integer.h (module 'core'): ns3::IntegerValue [class] module.add_class('IntegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## 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']) ## mobility-model.h (module 'mobility'): ns3::MobilityModel [class] module.add_class('MobilityModel', import_from_module='ns.mobility', parent=root_module['ns3::Object']) ## 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') ## net-device.h (module 'network'): ns3::NetDeviceQueue [class] module.add_class('NetDeviceQueue', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >']) ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface [class] module.add_class('NetDeviceQueueInterface', import_from_module='ns.network', parent=root_module['ns3::Object']) ## 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']) ## 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']) ## pointer.h (module 'core'): ns3::PointerChecker [class] module.add_class('PointerChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## pointer.h (module 'core'): ns3::PointerValue [class] module.add_class('PointerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## net-device.h (module 'network'): ns3::QueueItem [class] module.add_class('QueueItem', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >']) ## net-device.h (module 'network'): ns3::QueueItem::Uint8Values [enumeration] module.add_enum('Uint8Values', ['IP_DSFIELD'], outer_class=root_module['ns3::QueueItem'], import_from_module='ns.network') ## 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']) ## uan-channel.h (module 'uan'): ns3::UanChannel [class] module.add_class('UanChannel', parent=root_module['ns3::Channel']) ## uan-tx-mode.h (module 'uan'): ns3::UanModesListChecker [class] module.add_class('UanModesListChecker', parent=root_module['ns3::AttributeChecker']) ## uan-tx-mode.h (module 'uan'): ns3::UanModesListValue [class] module.add_class('UanModesListValue', parent=root_module['ns3::AttributeValue']) ## uan-net-device.h (module 'uan'): ns3::UanNetDevice [class] module.add_class('UanNetDevice', parent=root_module['ns3::NetDevice']) ## uinteger.h (module 'core'): ns3::UintegerValue [class] module.add_class('UintegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## vector.h (module 'core'): ns3::Vector2DChecker [class] module.add_class('Vector2DChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## vector.h (module 'core'): ns3::Vector2DValue [class] module.add_class('Vector2DValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## vector.h (module 'core'): ns3::Vector3DChecker [class] module.add_class('Vector3DChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## vector.h (module 'core'): ns3::Vector3DValue [class] module.add_class('Vector3DValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## acoustic-modem-energy-model.h (module 'uan'): ns3::AcousticModemEnergyModel [class] module.add_class('AcousticModemEnergyModel', parent=root_module['ns3::DeviceEnergyModel']) ## address.h (module 'network'): ns3::AddressChecker [class] module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## address.h (module 'network'): ns3::AddressValue [class] module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) module.add_container('std::list< std::pair< ns3::Ptr< ns3::Packet >, ns3::UanAddress > >', 'std::pair< ns3::Ptr< ns3::Packet >, ns3::UanAddress >', container_type=u'list') module.add_container('std::vector< ns3::Tap >', 'ns3::Tap', container_type=u'vector') module.add_container('std::vector< std::complex< double > >', 'std::complex< double >', container_type=u'vector') module.add_container('std::vector< double >', 'double', container_type=u'vector') module.add_container('std::set< unsigned char >', 'unsigned char', container_type=u'set') module.add_container('std::list< ns3::UanPacketArrival >', 'ns3::UanPacketArrival', container_type=u'list') module.add_container('std::list< ns3::Ptr< ns3::UanPhy > >', 'ns3::Ptr< ns3::UanPhy >', container_type=u'list') module.add_container('std::vector< std::pair< ns3::Ptr< ns3::UanNetDevice >, ns3::Ptr< ns3::UanTransducer > > >', 'std::pair< ns3::Ptr< ns3::UanNetDevice >, ns3::Ptr< ns3::UanTransducer > >', container_type=u'vector') module.add_container('std::list< ns3::Ptr< ns3::UanTransducer > >', 'ns3::Ptr< ns3::UanTransducer >', container_type=u'list') typehandlers.add_type_alias(u'ns3::Vector3DValue', u'ns3::VectorValue') typehandlers.add_type_alias(u'ns3::Vector3DValue*', u'ns3::VectorValue*') typehandlers.add_type_alias(u'ns3::Vector3DValue&', u'ns3::VectorValue&') module.add_typedef(root_module['ns3::Vector3DValue'], 'VectorValue') typehandlers.add_type_alias(u'ns3::Vector3D', u'ns3::Vector') typehandlers.add_type_alias(u'ns3::Vector3D*', u'ns3::Vector*') typehandlers.add_type_alias(u'ns3::Vector3D&', u'ns3::Vector&') module.add_typedef(root_module['ns3::Vector3D'], 'Vector') typehandlers.add_type_alias(u'ns3::Vector3DChecker', u'ns3::VectorChecker') typehandlers.add_type_alias(u'ns3::Vector3DChecker*', u'ns3::VectorChecker*') typehandlers.add_type_alias(u'ns3::Vector3DChecker&', u'ns3::VectorChecker&') module.add_typedef(root_module['ns3::Vector3DChecker'], 'VectorChecker') ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace Hash nested_module = module.add_cpp_namespace('Hash') register_types_ns3_Hash(nested_module) ## Register a nested module for the namespace TracedValueCallback nested_module = module.add_cpp_namespace('TracedValueCallback') register_types_ns3_TracedValueCallback(nested_module) ## 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_Hash(module): root_module = module.get_root() ## hash-function.h (module 'core'): ns3::Hash::Implementation [class] module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash64Function_ptr&') ## Register a nested module for the namespace Function nested_module = module.add_cpp_namespace('Function') register_types_ns3_Hash_Function(nested_module) def register_types_ns3_Hash_Function(module): root_module = module.get_root() ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class] module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class] module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class] module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class] module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) def register_types_ns3_TracedValueCallback(module): root_module = module.get_root() typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) *', u'ns3::TracedValueCallback::Uint8') typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) **', u'ns3::TracedValueCallback::Uint8*') typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) *&', u'ns3::TracedValueCallback::Uint8&') typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) *', u'ns3::TracedValueCallback::Int8') typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) **', u'ns3::TracedValueCallback::Int8*') typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) *&', u'ns3::TracedValueCallback::Int8&') typehandlers.add_type_alias(u'void ( * ) ( double, double ) *', u'ns3::TracedValueCallback::Double') typehandlers.add_type_alias(u'void ( * ) ( double, double ) **', u'ns3::TracedValueCallback::Double*') typehandlers.add_type_alias(u'void ( * ) ( double, double ) *&', u'ns3::TracedValueCallback::Double&') typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) *', u'ns3::TracedValueCallback::Uint32') typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) **', u'ns3::TracedValueCallback::Uint32*') typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) *&', u'ns3::TracedValueCallback::Uint32&') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *', u'ns3::TracedValueCallback::Time') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) **', u'ns3::TracedValueCallback::Time*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *&', u'ns3::TracedValueCallback::Time&') typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) *', u'ns3::TracedValueCallback::Bool') typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) **', u'ns3::TracedValueCallback::Bool*') typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) *&', u'ns3::TracedValueCallback::Bool&') typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) *', u'ns3::TracedValueCallback::Int16') typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) **', u'ns3::TracedValueCallback::Int16*') typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) *&', u'ns3::TracedValueCallback::Int16&') typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) *', u'ns3::TracedValueCallback::Int32') typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) **', u'ns3::TracedValueCallback::Int32*') typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) *&', u'ns3::TracedValueCallback::Int32&') typehandlers.add_type_alias(u'void ( * ) ( ) *', u'ns3::TracedValueCallback::Void') typehandlers.add_type_alias(u'void ( * ) ( ) **', u'ns3::TracedValueCallback::Void*') typehandlers.add_type_alias(u'void ( * ) ( ) *&', u'ns3::TracedValueCallback::Void&') typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) *', u'ns3::TracedValueCallback::Uint16') typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) **', u'ns3::TracedValueCallback::Uint16*') typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) *&', u'ns3::TracedValueCallback::Uint16&') 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_Ns3DeviceEnergyModelContainer_methods(root_module, root_module['ns3::DeviceEnergyModelContainer']) register_Ns3DeviceEnergyModelHelper_methods(root_module, root_module['ns3::DeviceEnergyModelHelper']) register_Ns3EnergySourceHelper_methods(root_module, root_module['ns3::EnergySourceHelper']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_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_Ns3Reservation_methods(root_module, root_module['ns3::Reservation']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3Tap_methods(root_module, root_module['ns3::Tap']) register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit']) register_Ns3TracedValue__Double_methods(root_module, root_module['ns3::TracedValue< double >']) 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_Ns3UanAddress_methods(root_module, root_module['ns3::UanAddress']) register_Ns3UanHelper_methods(root_module, root_module['ns3::UanHelper']) register_Ns3UanModesList_methods(root_module, root_module['ns3::UanModesList']) register_Ns3UanPacketArrival_methods(root_module, root_module['ns3::UanPacketArrival']) register_Ns3UanPdp_methods(root_module, root_module['ns3::UanPdp']) register_Ns3UanPhyListener_methods(root_module, root_module['ns3::UanPhyListener']) register_Ns3UanTxMode_methods(root_module, root_module['ns3::UanTxMode']) register_Ns3UanTxModeFactory_methods(root_module, root_module['ns3::UanTxModeFactory']) register_Ns3Vector2D_methods(root_module, root_module['ns3::Vector2D']) register_Ns3Vector3D_methods(root_module, root_module['ns3::Vector3D']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3AcousticModemEnergyModelHelper_methods(root_module, root_module['ns3::AcousticModemEnergyModelHelper']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) 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__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >']) 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__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) 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_Ns3UanHeaderCommon_methods(root_module, root_module['ns3::UanHeaderCommon']) register_Ns3UanHeaderRcAck_methods(root_module, root_module['ns3::UanHeaderRcAck']) register_Ns3UanHeaderRcCts_methods(root_module, root_module['ns3::UanHeaderRcCts']) register_Ns3UanHeaderRcCtsGlobal_methods(root_module, root_module['ns3::UanHeaderRcCtsGlobal']) register_Ns3UanHeaderRcData_methods(root_module, root_module['ns3::UanHeaderRcData']) register_Ns3UanHeaderRcRts_methods(root_module, root_module['ns3::UanHeaderRcRts']) register_Ns3UanMac_methods(root_module, root_module['ns3::UanMac']) register_Ns3UanMacAloha_methods(root_module, root_module['ns3::UanMacAloha']) register_Ns3UanMacCw_methods(root_module, root_module['ns3::UanMacCw']) register_Ns3UanMacRc_methods(root_module, root_module['ns3::UanMacRc']) register_Ns3UanMacRcGw_methods(root_module, root_module['ns3::UanMacRcGw']) register_Ns3UanNoiseModel_methods(root_module, root_module['ns3::UanNoiseModel']) register_Ns3UanNoiseModelDefault_methods(root_module, root_module['ns3::UanNoiseModelDefault']) register_Ns3UanPhy_methods(root_module, root_module['ns3::UanPhy']) register_Ns3UanPhyCalcSinr_methods(root_module, root_module['ns3::UanPhyCalcSinr']) register_Ns3UanPhyCalcSinrDefault_methods(root_module, root_module['ns3::UanPhyCalcSinrDefault']) register_Ns3UanPhyCalcSinrDual_methods(root_module, root_module['ns3::UanPhyCalcSinrDual']) register_Ns3UanPhyCalcSinrFhFsk_methods(root_module, root_module['ns3::UanPhyCalcSinrFhFsk']) register_Ns3UanPhyDual_methods(root_module, root_module['ns3::UanPhyDual']) register_Ns3UanPhyGen_methods(root_module, root_module['ns3::UanPhyGen']) register_Ns3UanPhyPer_methods(root_module, root_module['ns3::UanPhyPer']) register_Ns3UanPhyPerGenDefault_methods(root_module, root_module['ns3::UanPhyPerGenDefault']) register_Ns3UanPhyPerUmodem_methods(root_module, root_module['ns3::UanPhyPerUmodem']) register_Ns3UanPropModel_methods(root_module, root_module['ns3::UanPropModel']) register_Ns3UanPropModelIdeal_methods(root_module, root_module['ns3::UanPropModelIdeal']) register_Ns3UanPropModelThorp_methods(root_module, root_module['ns3::UanPropModelThorp']) register_Ns3UanTransducer_methods(root_module, root_module['ns3::UanTransducer']) register_Ns3UanTransducerHd_methods(root_module, root_module['ns3::UanTransducerHd']) register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable']) register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable']) register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable']) register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable']) 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_Ns3BooleanChecker_methods(root_module, root_module['ns3::BooleanChecker']) register_Ns3BooleanValue_methods(root_module, root_module['ns3::BooleanValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3Channel_methods(root_module, root_module['ns3::Channel']) register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable']) register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable']) register_Ns3DeviceEnergyModel_methods(root_module, root_module['ns3::DeviceEnergyModel']) register_Ns3DoubleValue_methods(root_module, root_module['ns3::DoubleValue']) register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable']) register_Ns3EmptyAttributeAccessor_methods(root_module, root_module['ns3::EmptyAttributeAccessor']) register_Ns3EmptyAttributeChecker_methods(root_module, root_module['ns3::EmptyAttributeChecker']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EnergyHarvester_methods(root_module, root_module['ns3::EnergyHarvester']) register_Ns3EnergySource_methods(root_module, root_module['ns3::EnergySource']) register_Ns3EnergySourceContainer_methods(root_module, root_module['ns3::EnergySourceContainer']) 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_Ns3IntegerValue_methods(root_module, root_module['ns3::IntegerValue']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_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_Ns3MobilityModel_methods(root_module, root_module['ns3::MobilityModel']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NetDeviceQueue_methods(root_module, root_module['ns3::NetDeviceQueue']) register_Ns3NetDeviceQueueInterface_methods(root_module, root_module['ns3::NetDeviceQueueInterface']) 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_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable']) register_Ns3PointerChecker_methods(root_module, root_module['ns3::PointerChecker']) register_Ns3PointerValue_methods(root_module, root_module['ns3::PointerValue']) register_Ns3QueueItem_methods(root_module, root_module['ns3::QueueItem']) 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_Ns3UanChannel_methods(root_module, root_module['ns3::UanChannel']) register_Ns3UanModesListChecker_methods(root_module, root_module['ns3::UanModesListChecker']) register_Ns3UanModesListValue_methods(root_module, root_module['ns3::UanModesListValue']) register_Ns3UanNetDevice_methods(root_module, root_module['ns3::UanNetDevice']) register_Ns3UintegerValue_methods(root_module, root_module['ns3::UintegerValue']) register_Ns3Vector2DChecker_methods(root_module, root_module['ns3::Vector2DChecker']) register_Ns3Vector2DValue_methods(root_module, root_module['ns3::Vector2DValue']) register_Ns3Vector3DChecker_methods(root_module, root_module['ns3::Vector3DChecker']) register_Ns3Vector3DValue_methods(root_module, root_module['ns3::Vector3DValue']) register_Ns3AcousticModemEnergyModel_methods(root_module, root_module['ns3::AcousticModemEnergyModel']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation']) register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a']) register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32']) register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64']) register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetRemainingSize() const [member function] cls.add_method('GetRemainingSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function] cls.add_method('PeekU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function] cls.add_method('Read', 'void', [param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Adjust(int32_t adjustment) [member function] cls.add_method('Adjust', 'void', [param('int32_t', 'adjustment')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') return def register_Ns3DeviceEnergyModelContainer_methods(root_module, cls): ## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(ns3::DeviceEnergyModelContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::DeviceEnergyModelContainer const &', 'arg0')]) ## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer() [constructor] cls.add_constructor([]) ## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(ns3::Ptr<ns3::DeviceEnergyModel> model) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::DeviceEnergyModel >', 'model')]) ## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(std::string modelName) [constructor] cls.add_constructor([param('std::string', 'modelName')]) ## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(ns3::DeviceEnergyModelContainer const & a, ns3::DeviceEnergyModelContainer const & b) [constructor] cls.add_constructor([param('ns3::DeviceEnergyModelContainer const &', 'a'), param('ns3::DeviceEnergyModelContainer const &', 'b')]) ## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Add(ns3::DeviceEnergyModelContainer container) [member function] cls.add_method('Add', 'void', [param('ns3::DeviceEnergyModelContainer', 'container')]) ## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Add(ns3::Ptr<ns3::DeviceEnergyModel> model) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::DeviceEnergyModel >', 'model')]) ## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Add(std::string modelName) [member function] cls.add_method('Add', 'void', [param('std::string', 'modelName')]) ## device-energy-model-container.h (module 'energy'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::DeviceEnergyModel>*,std::vector<ns3::Ptr<ns3::DeviceEnergyModel>, std::allocator<ns3::Ptr<ns3::DeviceEnergyModel> > > > ns3::DeviceEnergyModelContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::DeviceEnergyModel > const, std::vector< ns3::Ptr< ns3::DeviceEnergyModel > > >', [], is_const=True) ## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Clear() [member function] cls.add_method('Clear', 'void', []) ## device-energy-model-container.h (module 'energy'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::DeviceEnergyModel>*,std::vector<ns3::Ptr<ns3::DeviceEnergyModel>, std::allocator<ns3::Ptr<ns3::DeviceEnergyModel> > > > ns3::DeviceEnergyModelContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::DeviceEnergyModel > const, std::vector< ns3::Ptr< ns3::DeviceEnergyModel > > >', [], is_const=True) ## device-energy-model-container.h (module 'energy'): ns3::Ptr<ns3::DeviceEnergyModel> ns3::DeviceEnergyModelContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::DeviceEnergyModel >', [param('uint32_t', 'i')], is_const=True) ## device-energy-model-container.h (module 'energy'): uint32_t ns3::DeviceEnergyModelContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3DeviceEnergyModelHelper_methods(root_module, cls): ## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelHelper::DeviceEnergyModelHelper() [constructor] cls.add_constructor([]) ## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelHelper::DeviceEnergyModelHelper(ns3::DeviceEnergyModelHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::DeviceEnergyModelHelper const &', 'arg0')]) ## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelContainer ns3::DeviceEnergyModelHelper::Install(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::EnergySource> source) const [member function] cls.add_method('Install', 'ns3::DeviceEnergyModelContainer', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::EnergySource >', 'source')], is_const=True) ## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelContainer ns3::DeviceEnergyModelHelper::Install(ns3::NetDeviceContainer deviceContainer, ns3::EnergySourceContainer sourceContainer) const [member function] cls.add_method('Install', 'ns3::DeviceEnergyModelContainer', [param('ns3::NetDeviceContainer', 'deviceContainer'), param('ns3::EnergySourceContainer', 'sourceContainer')], is_const=True) ## energy-model-helper.h (module 'energy'): void ns3::DeviceEnergyModelHelper::Set(std::string name, ns3::AttributeValue const & v) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')], is_pure_virtual=True, is_virtual=True) ## energy-model-helper.h (module 'energy'): ns3::Ptr<ns3::DeviceEnergyModel> ns3::DeviceEnergyModelHelper::DoInstall(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::EnergySource> source) const [member function] cls.add_method('DoInstall', 'ns3::Ptr< ns3::DeviceEnergyModel >', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::EnergySource >', 'source')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3EnergySourceHelper_methods(root_module, cls): ## energy-model-helper.h (module 'energy'): ns3::EnergySourceHelper::EnergySourceHelper() [constructor] cls.add_constructor([]) ## energy-model-helper.h (module 'energy'): ns3::EnergySourceHelper::EnergySourceHelper(ns3::EnergySourceHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::EnergySourceHelper const &', 'arg0')]) ## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'ns3::EnergySourceContainer', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'ns3::EnergySourceContainer', [param('ns3::NodeContainer', 'c')], is_const=True) ## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'ns3::EnergySourceContainer', [param('std::string', 'nodeName')], is_const=True) ## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::InstallAll() const [member function] cls.add_method('InstallAll', 'ns3::EnergySourceContainer', [], is_const=True) ## energy-model-helper.h (module 'energy'): void ns3::EnergySourceHelper::Set(std::string name, ns3::AttributeValue const & v) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')], is_pure_virtual=True, is_virtual=True) ## energy-model-helper.h (module 'energy'): ns3::Ptr<ns3::EnergySource> ns3::EnergySourceHelper::DoInstall(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('DoInstall', 'ns3::Ptr< ns3::EnergySource >', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('==') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hasher const &', 'arg0')]) ## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor] cls.add_constructor([]) ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function] cls.add_method('GetHash32', 'uint32_t', [param('std::string const', 's')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_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::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=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'): bool ns3::Ipv4Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', '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_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', [], deprecated=True, is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function] cls.add_method('IsDocumentation', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() const [member function] cls.add_method('IsIpv4MappedAddress', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] cls.add_method('IsLinkLocalMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] cls.add_method('MakeIpv4MappedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv4Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3Mac48Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac48Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv4Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv6Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] cls.add_method('GetMulticast6Prefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] cls.add_method('GetMulticastPrefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function] cls.add_method('IsGroup', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3NetDeviceContainer_methods(root_module, cls): ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor] cls.add_constructor([]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor] cls.add_constructor([param('std::string', 'devName')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NetDeviceContainer', 'other')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function] cls.add_method('Add', 'void', [param('std::string', 'deviceName')]) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True) ## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3NodeContainer_methods(root_module, cls): ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor] cls.add_constructor([]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor] cls.add_constructor([param('std::string', 'nodeName')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NodeContainer', 'other')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function] cls.add_method('Add', 'void', [param('std::string', 'nodeName')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n'), param('uint32_t', 'systemId')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function] cls.add_method('GetGlobal', 'ns3::NodeContainer', [], is_static=True) ## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function] cls.add_method('Replace', 'bool', [param('ns3::Tag &', 'tag')]) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 21 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3Reservation_methods(root_module, cls): ## uan-mac-rc.h (module 'uan'): ns3::Reservation::Reservation(ns3::Reservation const & arg0) [copy constructor] cls.add_constructor([param('ns3::Reservation const &', 'arg0')]) ## uan-mac-rc.h (module 'uan'): ns3::Reservation::Reservation() [constructor] cls.add_constructor([]) ## uan-mac-rc.h (module 'uan'): ns3::Reservation::Reservation(std::list<std::pair<ns3::Ptr<ns3::Packet>, ns3::UanAddress>, std::allocator<std::pair<ns3::Ptr<ns3::Packet>, ns3::UanAddress> > > & list, uint8_t frameNo, uint32_t maxPkts=0) [constructor] cls.add_constructor([param('std::list< std::pair< ns3::Ptr< ns3::Packet >, ns3::UanAddress > > &', 'list'), param('uint8_t', 'frameNo'), param('uint32_t', 'maxPkts', default_value='0')]) ## uan-mac-rc.h (module 'uan'): void ns3::Reservation::AddTimestamp(ns3::Time t) [member function] cls.add_method('AddTimestamp', 'void', [param('ns3::Time', 't')]) ## uan-mac-rc.h (module 'uan'): uint8_t ns3::Reservation::GetFrameNo() const [member function] cls.add_method('GetFrameNo', 'uint8_t', [], is_const=True) ## uan-mac-rc.h (module 'uan'): uint32_t ns3::Reservation::GetLength() const [member function] cls.add_method('GetLength', 'uint32_t', [], is_const=True) ## uan-mac-rc.h (module 'uan'): uint32_t ns3::Reservation::GetNoFrames() const [member function] cls.add_method('GetNoFrames', 'uint32_t', [], is_const=True) ## uan-mac-rc.h (module 'uan'): std::list<std::pair<ns3::Ptr<ns3::Packet>, ns3::UanAddress>, std::allocator<std::pair<ns3::Ptr<ns3::Packet>, ns3::UanAddress> > > const & ns3::Reservation::GetPktList() const [member function] cls.add_method('GetPktList', 'std::list< std::pair< ns3::Ptr< ns3::Packet >, ns3::UanAddress > > const &', [], is_const=True) ## uan-mac-rc.h (module 'uan'): uint8_t ns3::Reservation::GetRetryNo() const [member function] cls.add_method('GetRetryNo', 'uint8_t', [], is_const=True) ## uan-mac-rc.h (module 'uan'): ns3::Time ns3::Reservation::GetTimestamp(uint8_t n) const [member function] cls.add_method('GetTimestamp', 'ns3::Time', [param('uint8_t', 'n')], is_const=True) ## uan-mac-rc.h (module 'uan'): void ns3::Reservation::IncrementRetry() [member function] cls.add_method('IncrementRetry', 'void', []) ## uan-mac-rc.h (module 'uan'): bool ns3::Reservation::IsTransmitted() const [member function] cls.add_method('IsTransmitted', 'bool', [], is_const=True) ## uan-mac-rc.h (module 'uan'): void ns3::Reservation::SetFrameNo(uint8_t fn) [member function] cls.add_method('SetFrameNo', 'void', [param('uint8_t', 'fn')]) ## uan-mac-rc.h (module 'uan'): void ns3::Reservation::SetTransmitted(bool t=true) [member function] cls.add_method('SetTransmitted', 'void', [param('bool', 't', default_value='true')]) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Simulator_methods(root_module, cls): ## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Simulator const &', 'arg0')]) ## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function] cls.add_method('Cancel', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function] cls.add_method('Destroy', 'void', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function] cls.add_method('GetContext', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function] cls.add_method('GetImplementation', 'ns3::Ptr< ns3::SimulatorImpl >', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function] cls.add_method('GetMaximumSimulationTime', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function] cls.add_method('IsExpired', 'bool', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function] cls.add_method('IsFinished', 'bool', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function] cls.add_method('Now', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function] cls.add_method('Remove', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function] cls.add_method('SetImplementation', 'void', [param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function] cls.add_method('SetScheduler', 'void', [param('ns3::ObjectFactory', 'schedulerFactory')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function] cls.add_method('Stop', 'void', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & delay) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'delay')], is_static=True) return def register_Ns3Tag_methods(root_module, cls): ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] cls.add_constructor([]) ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor] cls.add_constructor([param('ns3::Tag const &', 'arg0')]) ## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_virtual=True) ## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TagBuffer_methods(root_module, cls): ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor] cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')]) ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor] cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function] cls.add_method('CopyFrom', 'void', [param('ns3::TagBuffer', 'o')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function] cls.add_method('ReadDouble', 'double', []) ## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function] cls.add_method('TrimAtEnd', 'void', [param('uint32_t', 'trim')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function] cls.add_method('WriteDouble', 'void', [param('double', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'v')]) return def register_Ns3Tap_methods(root_module, cls): ## uan-prop-model.h (module 'uan'): ns3::Tap::Tap(ns3::Tap const & arg0) [copy constructor] cls.add_constructor([param('ns3::Tap const &', 'arg0')]) ## uan-prop-model.h (module 'uan'): ns3::Tap::Tap() [constructor] cls.add_constructor([]) ## uan-prop-model.h (module 'uan'): ns3::Tap::Tap(ns3::Time delay, std::complex<double> amp) [constructor] cls.add_constructor([param('ns3::Time', 'delay'), param('std::complex< double >', 'amp')]) ## uan-prop-model.h (module 'uan'): std::complex<double> ns3::Tap::GetAmp() const [member function] cls.add_method('GetAmp', 'std::complex< double >', [], is_const=True) ## uan-prop-model.h (module 'uan'): ns3::Time ns3::Tap::GetDelay() const [member function] cls.add_method('GetDelay', 'ns3::Time', [], is_const=True) return def register_Ns3TimeWithUnit_methods(root_module, cls): cls.add_output_stream_operator() ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::TimeWithUnit const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeWithUnit const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::Time const time, ns3::Time::Unit const unit) [constructor] cls.add_constructor([param('ns3::Time const', 'time'), param('ns3::Time::Unit const', 'unit')]) return def register_Ns3TracedValue__Double_methods(root_module, cls): ## traced-value.h (module 'core'): ns3::TracedValue<double>::TracedValue() [constructor] cls.add_constructor([]) ## traced-value.h (module 'core'): ns3::TracedValue<double>::TracedValue(ns3::TracedValue<double> const & o) [copy constructor] cls.add_constructor([param('ns3::TracedValue< double > const &', 'o')]) ## traced-value.h (module 'core'): ns3::TracedValue<double>::TracedValue(double const & v) [constructor] cls.add_constructor([param('double const &', 'v')]) ## traced-value.h (module 'core'): void ns3::TracedValue<double>::Connect(ns3::CallbackBase const & cb, std::basic_string<char,std::char_traits<char>,std::allocator<char> > path) [member function] cls.add_method('Connect', 'void', [param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')]) ## traced-value.h (module 'core'): void ns3::TracedValue<double>::ConnectWithoutContext(ns3::CallbackBase const & cb) [member function] cls.add_method('ConnectWithoutContext', 'void', [param('ns3::CallbackBase const &', 'cb')]) ## traced-value.h (module 'core'): void ns3::TracedValue<double>::Disconnect(ns3::CallbackBase const & cb, std::basic_string<char,std::char_traits<char>,std::allocator<char> > path) [member function] cls.add_method('Disconnect', 'void', [param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')]) ## traced-value.h (module 'core'): void ns3::TracedValue<double>::DisconnectWithoutContext(ns3::CallbackBase const & cb) [member function] cls.add_method('DisconnectWithoutContext', 'void', [param('ns3::CallbackBase const &', 'cb')]) ## traced-value.h (module 'core'): double ns3::TracedValue<double>::Get() const [member function] cls.add_method('Get', 'double', [], is_const=True) ## traced-value.h (module 'core'): void ns3::TracedValue<double>::Set(double const & v) [member function] cls.add_method('Set', 'void', [param('double const &', 'v')]) 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, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [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'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## 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, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [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'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')], deprecated=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor, std::string callback, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor'), param('std::string', 'callback'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): std::size_t ns3::TypeId::GetSize() const [member function] cls.add_method('GetSize', 'std::size_t', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function] cls.add_method('LookupByHash', 'ns3::TypeId', [param('uint32_t', 'hash')], is_static=True) ## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function] cls.add_method('LookupByHashFailSafe', 'bool', [param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')], is_static=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name, ns3::TypeId::TraceSourceInformation * info) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name'), param('ns3::TypeId::TraceSourceInformation *', 'info')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetSize(std::size_t size) [member function] cls.add_method('SetSize', 'ns3::TypeId', [param('std::size_t', 'size')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t uid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'uid')]) 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) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportLevel [variable] cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportMsg [variable] cls.add_instance_attribute('supportMsg', 'std::string', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::callback [variable] cls.add_instance_attribute('callback', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportLevel [variable] cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportMsg [variable] cls.add_instance_attribute('supportMsg', 'std::string', is_const=False) return def register_Ns3UanAddress_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## uan-address.h (module 'uan'): ns3::UanAddress::UanAddress(ns3::UanAddress const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanAddress const &', 'arg0')]) ## uan-address.h (module 'uan'): ns3::UanAddress::UanAddress() [constructor] cls.add_constructor([]) ## uan-address.h (module 'uan'): ns3::UanAddress::UanAddress(uint8_t addr) [constructor] cls.add_constructor([param('uint8_t', 'addr')]) ## uan-address.h (module 'uan'): static ns3::UanAddress ns3::UanAddress::Allocate() [member function] cls.add_method('Allocate', 'ns3::UanAddress', [], is_static=True) ## uan-address.h (module 'uan'): static ns3::UanAddress ns3::UanAddress::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::UanAddress', [param('ns3::Address const &', 'address')], is_static=True) ## uan-address.h (module 'uan'): void ns3::UanAddress::CopyFrom(uint8_t const * pBuffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'pBuffer')]) ## uan-address.h (module 'uan'): void ns3::UanAddress::CopyTo(uint8_t * pBuffer) [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'pBuffer')]) ## uan-address.h (module 'uan'): uint8_t ns3::UanAddress::GetAsInt() const [member function] cls.add_method('GetAsInt', 'uint8_t', [], is_const=True) ## uan-address.h (module 'uan'): static ns3::UanAddress ns3::UanAddress::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::UanAddress', [], is_static=True) ## uan-address.h (module 'uan'): static bool ns3::UanAddress::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3UanHelper_methods(root_module, cls): ## uan-helper.h (module 'uan'): ns3::UanHelper::UanHelper(ns3::UanHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanHelper const &', 'arg0')]) ## uan-helper.h (module 'uan'): ns3::UanHelper::UanHelper() [constructor] cls.add_constructor([]) ## uan-helper.h (module 'uan'): int64_t ns3::UanHelper::AssignStreams(ns3::NetDeviceContainer c, int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('ns3::NetDeviceContainer', 'c'), param('int64_t', 'stream')]) ## uan-helper.h (module 'uan'): static void ns3::UanHelper::EnableAscii(std::ostream & os, uint32_t nodeid, uint32_t deviceid) [member function] cls.add_method('EnableAscii', 'void', [param('std::ostream &', 'os'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid')], is_static=True) ## uan-helper.h (module 'uan'): static void ns3::UanHelper::EnableAscii(std::ostream & os, ns3::NetDeviceContainer d) [member function] cls.add_method('EnableAscii', 'void', [param('std::ostream &', 'os'), param('ns3::NetDeviceContainer', 'd')], is_static=True) ## uan-helper.h (module 'uan'): static void ns3::UanHelper::EnableAscii(std::ostream & os, ns3::NodeContainer n) [member function] cls.add_method('EnableAscii', 'void', [param('std::ostream &', 'os'), param('ns3::NodeContainer', 'n')], is_static=True) ## uan-helper.h (module 'uan'): static void ns3::UanHelper::EnableAsciiAll(std::ostream & os) [member function] cls.add_method('EnableAsciiAll', 'void', [param('std::ostream &', 'os')], is_static=True) ## uan-helper.h (module 'uan'): ns3::NetDeviceContainer ns3::UanHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer', 'c')], is_const=True) ## uan-helper.h (module 'uan'): ns3::NetDeviceContainer ns3::UanHelper::Install(ns3::NodeContainer c, ns3::Ptr<ns3::UanChannel> channel) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer', 'c'), param('ns3::Ptr< ns3::UanChannel >', 'channel')], is_const=True) ## uan-helper.h (module 'uan'): ns3::Ptr<ns3::UanNetDevice> ns3::UanHelper::Install(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::UanChannel> channel) const [member function] cls.add_method('Install', 'ns3::Ptr< ns3::UanNetDevice >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::UanChannel >', 'channel')], is_const=True) ## uan-helper.h (module 'uan'): void ns3::UanHelper::SetMac(std::string type, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetMac', 'void', [param('std::string', 'type'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) ## uan-helper.h (module 'uan'): void ns3::UanHelper::SetPhy(std::string phyType, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetPhy', 'void', [param('std::string', 'phyType'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) ## uan-helper.h (module 'uan'): void ns3::UanHelper::SetTransducer(std::string type, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetTransducer', 'void', [param('std::string', 'type'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) return def register_Ns3UanModesList_methods(root_module, cls): cls.add_output_stream_operator() ## uan-tx-mode.h (module 'uan'): ns3::UanModesList::UanModesList(ns3::UanModesList const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanModesList const &', 'arg0')]) ## uan-tx-mode.h (module 'uan'): ns3::UanModesList::UanModesList() [constructor] cls.add_constructor([]) ## uan-tx-mode.h (module 'uan'): void ns3::UanModesList::AppendMode(ns3::UanTxMode mode) [member function] cls.add_method('AppendMode', 'void', [param('ns3::UanTxMode', 'mode')]) ## uan-tx-mode.h (module 'uan'): void ns3::UanModesList::DeleteMode(uint32_t num) [member function] cls.add_method('DeleteMode', 'void', [param('uint32_t', 'num')]) ## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanModesList::GetNModes() const [member function] cls.add_method('GetNModes', 'uint32_t', [], is_const=True) return def register_Ns3UanPacketArrival_methods(root_module, cls): ## uan-transducer.h (module 'uan'): ns3::UanPacketArrival::UanPacketArrival(ns3::UanPacketArrival const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanPacketArrival const &', 'arg0')]) ## uan-transducer.h (module 'uan'): ns3::UanPacketArrival::UanPacketArrival() [constructor] cls.add_constructor([]) ## uan-transducer.h (module 'uan'): ns3::UanPacketArrival::UanPacketArrival(ns3::Ptr<ns3::Packet> packet, double rxPowerDb, ns3::UanTxMode txMode, ns3::UanPdp pdp, ns3::Time arrTime) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'rxPowerDb'), param('ns3::UanTxMode', 'txMode'), param('ns3::UanPdp', 'pdp'), param('ns3::Time', 'arrTime')]) ## uan-transducer.h (module 'uan'): ns3::Time ns3::UanPacketArrival::GetArrivalTime() const [member function] cls.add_method('GetArrivalTime', 'ns3::Time', [], is_const=True) ## uan-transducer.h (module 'uan'): ns3::Ptr<ns3::Packet> ns3::UanPacketArrival::GetPacket() const [member function] cls.add_method('GetPacket', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## uan-transducer.h (module 'uan'): ns3::UanPdp ns3::UanPacketArrival::GetPdp() const [member function] cls.add_method('GetPdp', 'ns3::UanPdp', [], is_const=True) ## uan-transducer.h (module 'uan'): double ns3::UanPacketArrival::GetRxPowerDb() const [member function] cls.add_method('GetRxPowerDb', 'double', [], is_const=True) ## uan-transducer.h (module 'uan'): ns3::UanTxMode const & ns3::UanPacketArrival::GetTxMode() const [member function] cls.add_method('GetTxMode', 'ns3::UanTxMode const &', [], is_const=True) return def register_Ns3UanPdp_methods(root_module, cls): cls.add_output_stream_operator() ## uan-prop-model.h (module 'uan'): ns3::UanPdp::UanPdp(ns3::UanPdp const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanPdp const &', 'arg0')]) ## uan-prop-model.h (module 'uan'): ns3::UanPdp::UanPdp() [constructor] cls.add_constructor([]) ## uan-prop-model.h (module 'uan'): ns3::UanPdp::UanPdp(std::vector<ns3::Tap, std::allocator<ns3::Tap> > taps, ns3::Time resolution) [constructor] cls.add_constructor([param('std::vector< ns3::Tap >', 'taps'), param('ns3::Time', 'resolution')]) ## uan-prop-model.h (module 'uan'): ns3::UanPdp::UanPdp(std::vector<std::complex<double>,std::allocator<std::complex<double> > > arrivals, ns3::Time resolution) [constructor] cls.add_constructor([param('std::vector< std::complex< double > >', 'arrivals'), param('ns3::Time', 'resolution')]) ## uan-prop-model.h (module 'uan'): ns3::UanPdp::UanPdp(std::vector<double,std::allocator<double> > arrivals, ns3::Time resolution) [constructor] cls.add_constructor([param('std::vector< double >', 'arrivals'), param('ns3::Time', 'resolution')]) ## uan-prop-model.h (module 'uan'): static ns3::UanPdp ns3::UanPdp::CreateImpulsePdp() [member function] cls.add_method('CreateImpulsePdp', 'ns3::UanPdp', [], is_static=True) ## uan-prop-model.h (module 'uan'): __gnu_cxx::__normal_iterator<const ns3::Tap*,std::vector<ns3::Tap, std::allocator<ns3::Tap> > > ns3::UanPdp::GetBegin() const [member function] cls.add_method('GetBegin', '__gnu_cxx::__normal_iterator< ns3::Tap const *, std::vector< ns3::Tap > >', [], is_const=True) ## uan-prop-model.h (module 'uan'): __gnu_cxx::__normal_iterator<const ns3::Tap*,std::vector<ns3::Tap, std::allocator<ns3::Tap> > > ns3::UanPdp::GetEnd() const [member function] cls.add_method('GetEnd', '__gnu_cxx::__normal_iterator< ns3::Tap const *, std::vector< ns3::Tap > >', [], is_const=True) ## uan-prop-model.h (module 'uan'): uint32_t ns3::UanPdp::GetNTaps() const [member function] cls.add_method('GetNTaps', 'uint32_t', [], is_const=True) ## uan-prop-model.h (module 'uan'): ns3::Time ns3::UanPdp::GetResolution() const [member function] cls.add_method('GetResolution', 'ns3::Time', [], is_const=True) ## uan-prop-model.h (module 'uan'): ns3::Tap const & ns3::UanPdp::GetTap(uint32_t i) const [member function] cls.add_method('GetTap', 'ns3::Tap const &', [param('uint32_t', 'i')], is_const=True) ## uan-prop-model.h (module 'uan'): void ns3::UanPdp::SetNTaps(uint32_t nTaps) [member function] cls.add_method('SetNTaps', 'void', [param('uint32_t', 'nTaps')]) ## uan-prop-model.h (module 'uan'): void ns3::UanPdp::SetResolution(ns3::Time resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time', 'resolution')]) ## uan-prop-model.h (module 'uan'): void ns3::UanPdp::SetTap(std::complex<double> arrival, uint32_t index) [member function] cls.add_method('SetTap', 'void', [param('std::complex< double >', 'arrival'), param('uint32_t', 'index')]) ## uan-prop-model.h (module 'uan'): std::complex<double> ns3::UanPdp::SumTapsC(ns3::Time begin, ns3::Time end) const [member function] cls.add_method('SumTapsC', 'std::complex< double >', [param('ns3::Time', 'begin'), param('ns3::Time', 'end')], is_const=True) ## uan-prop-model.h (module 'uan'): std::complex<double> ns3::UanPdp::SumTapsFromMaxC(ns3::Time delay, ns3::Time duration) const [member function] cls.add_method('SumTapsFromMaxC', 'std::complex< double >', [param('ns3::Time', 'delay'), param('ns3::Time', 'duration')], is_const=True) ## uan-prop-model.h (module 'uan'): double ns3::UanPdp::SumTapsFromMaxNc(ns3::Time delay, ns3::Time duration) const [member function] cls.add_method('SumTapsFromMaxNc', 'double', [param('ns3::Time', 'delay'), param('ns3::Time', 'duration')], is_const=True) ## uan-prop-model.h (module 'uan'): double ns3::UanPdp::SumTapsNc(ns3::Time begin, ns3::Time end) const [member function] cls.add_method('SumTapsNc', 'double', [param('ns3::Time', 'begin'), param('ns3::Time', 'end')], is_const=True) return def register_Ns3UanPhyListener_methods(root_module, cls): ## uan-phy.h (module 'uan'): ns3::UanPhyListener::UanPhyListener() [constructor] cls.add_constructor([]) ## uan-phy.h (module 'uan'): ns3::UanPhyListener::UanPhyListener(ns3::UanPhyListener const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanPhyListener const &', 'arg0')]) ## uan-phy.h (module 'uan'): void ns3::UanPhyListener::NotifyCcaEnd() [member function] cls.add_method('NotifyCcaEnd', 'void', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhyListener::NotifyCcaStart() [member function] cls.add_method('NotifyCcaStart', 'void', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhyListener::NotifyRxEndError() [member function] cls.add_method('NotifyRxEndError', 'void', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhyListener::NotifyRxEndOk() [member function] cls.add_method('NotifyRxEndOk', 'void', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhyListener::NotifyRxStart() [member function] cls.add_method('NotifyRxStart', 'void', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhyListener::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_Ns3UanTxMode_methods(root_module, cls): cls.add_output_stream_operator() ## uan-tx-mode.h (module 'uan'): ns3::UanTxMode::UanTxMode(ns3::UanTxMode const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanTxMode const &', 'arg0')]) ## uan-tx-mode.h (module 'uan'): ns3::UanTxMode::UanTxMode() [constructor] cls.add_constructor([]) ## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanTxMode::GetBandwidthHz() const [member function] cls.add_method('GetBandwidthHz', 'uint32_t', [], is_const=True) ## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanTxMode::GetCenterFreqHz() const [member function] cls.add_method('GetCenterFreqHz', 'uint32_t', [], is_const=True) ## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanTxMode::GetConstellationSize() const [member function] cls.add_method('GetConstellationSize', 'uint32_t', [], is_const=True) ## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanTxMode::GetDataRateBps() const [member function] cls.add_method('GetDataRateBps', 'uint32_t', [], is_const=True) ## uan-tx-mode.h (module 'uan'): ns3::UanTxMode::ModulationType ns3::UanTxMode::GetModType() const [member function] cls.add_method('GetModType', 'ns3::UanTxMode::ModulationType', [], is_const=True) ## uan-tx-mode.h (module 'uan'): std::string ns3::UanTxMode::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanTxMode::GetPhyRateSps() const [member function] cls.add_method('GetPhyRateSps', 'uint32_t', [], is_const=True) ## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanTxMode::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) return def register_Ns3UanTxModeFactory_methods(root_module, cls): ## uan-tx-mode.h (module 'uan'): ns3::UanTxModeFactory::UanTxModeFactory(ns3::UanTxModeFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanTxModeFactory const &', 'arg0')]) ## uan-tx-mode.h (module 'uan'): ns3::UanTxModeFactory::UanTxModeFactory() [constructor] cls.add_constructor([]) ## uan-tx-mode.h (module 'uan'): static ns3::UanTxMode ns3::UanTxModeFactory::CreateMode(ns3::UanTxMode::ModulationType type, uint32_t dataRateBps, uint32_t phyRateSps, uint32_t cfHz, uint32_t bwHz, uint32_t constSize, std::string name) [member function] cls.add_method('CreateMode', 'ns3::UanTxMode', [param('ns3::UanTxMode::ModulationType', 'type'), param('uint32_t', 'dataRateBps'), param('uint32_t', 'phyRateSps'), param('uint32_t', 'cfHz'), param('uint32_t', 'bwHz'), param('uint32_t', 'constSize'), param('std::string', 'name')], is_static=True) ## uan-tx-mode.h (module 'uan'): static ns3::UanTxMode ns3::UanTxModeFactory::GetMode(std::string name) [member function] cls.add_method('GetMode', 'ns3::UanTxMode', [param('std::string', 'name')], is_static=True) ## uan-tx-mode.h (module 'uan'): static ns3::UanTxMode ns3::UanTxModeFactory::GetMode(uint32_t uid) [member function] cls.add_method('GetMode', 'ns3::UanTxMode', [param('uint32_t', 'uid')], is_static=True) return def register_Ns3Vector2D_methods(root_module, cls): cls.add_output_stream_operator() ## vector.h (module 'core'): ns3::Vector2D::Vector2D(ns3::Vector2D const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector2D const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector2D::Vector2D(double _x, double _y) [constructor] cls.add_constructor([param('double', '_x'), param('double', '_y')]) ## vector.h (module 'core'): ns3::Vector2D::Vector2D() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector2D::x [variable] cls.add_instance_attribute('x', 'double', is_const=False) ## vector.h (module 'core'): ns3::Vector2D::y [variable] cls.add_instance_attribute('y', 'double', is_const=False) return def register_Ns3Vector3D_methods(root_module, cls): cls.add_output_stream_operator() ## vector.h (module 'core'): ns3::Vector3D::Vector3D(ns3::Vector3D const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector3D const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector3D::Vector3D(double _x, double _y, double _z) [constructor] cls.add_constructor([param('double', '_x'), param('double', '_y'), param('double', '_z')]) ## vector.h (module 'core'): ns3::Vector3D::Vector3D() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector3D::x [variable] cls.add_instance_attribute('x', 'double', is_const=False) ## vector.h (module 'core'): ns3::Vector3D::y [variable] cls.add_instance_attribute('y', 'double', is_const=False) ## vector.h (module 'core'): ns3::Vector3D::z [variable] cls.add_instance_attribute('z', 'double', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long double v) [constructor] cls.add_constructor([param('long double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::implementation [variable] cls.add_static_attribute('implementation', 'ns3::int64x64_t::impl_type const', is_const=True) return def register_Ns3AcousticModemEnergyModelHelper_methods(root_module, cls): ## acoustic-modem-energy-model-helper.h (module 'uan'): ns3::AcousticModemEnergyModelHelper::AcousticModemEnergyModelHelper(ns3::AcousticModemEnergyModelHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::AcousticModemEnergyModelHelper const &', 'arg0')]) ## acoustic-modem-energy-model-helper.h (module 'uan'): ns3::AcousticModemEnergyModelHelper::AcousticModemEnergyModelHelper() [constructor] cls.add_constructor([]) ## acoustic-modem-energy-model-helper.h (module 'uan'): void ns3::AcousticModemEnergyModelHelper::Set(std::string name, ns3::AttributeValue const & v) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')], is_virtual=True) ## acoustic-modem-energy-model-helper.h (module 'uan'): void ns3::AcousticModemEnergyModelHelper::SetDepletionCallback(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('SetDepletionCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) ## acoustic-modem-energy-model-helper.h (module 'uan'): ns3::Ptr<ns3::DeviceEnergyModel> ns3::AcousticModemEnergyModelHelper::DoInstall(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::EnergySource> source) const [member function] cls.add_method('DoInstall', 'ns3::Ptr< ns3::DeviceEnergyModel >', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::EnergySource >', 'source')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Object_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::Object() [constructor] cls.add_constructor([]) ## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function] cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) ## object.h (module 'core'): void ns3::Object::Dispose() [member function] cls.add_method('Dispose', 'void', []) ## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function] cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) ## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object.h (module 'core'): void ns3::Object::Initialize() [member function] cls.add_method('Initialize', 'void', []) ## object.h (module 'core'): bool ns3::Object::IsInitialized() const [member function] cls.add_method('IsInitialized', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor] cls.add_constructor([param('ns3::Object const &', 'o')], visibility='protected') ## object.h (module 'core'): void ns3::Object::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectAggregateIterator_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')]) ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor] cls.add_constructor([]) ## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_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__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter< ns3::NetDeviceQueue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::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__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__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount(ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter< ns3::QueueItem > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::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_Ns3Time_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & v) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::TimeWithUnit ns3::Time::As(ns3::Time::Unit const unit) const [member function] cls.add_method('As', 'ns3::TimeWithUnit', [param('ns3::Time::Unit const', 'unit')], is_const=True) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value, ns3::Time::Unit unit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit unit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit unit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetDays() const [member function] cls.add_method('GetDays', 'double', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function] cls.add_method('GetFemtoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetHours() const [member function] cls.add_method('GetHours', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function] cls.add_method('GetInteger', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function] cls.add_method('GetMicroSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function] cls.add_method('GetMilliSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetMinutes() const [member function] cls.add_method('GetMinutes', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function] cls.add_method('GetNanoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function] cls.add_method('GetPicoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function] cls.add_method('GetResolution', 'ns3::Time::Unit', [], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function] cls.add_method('GetSeconds', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function] cls.add_method('GetTimeStep', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetYears() const [member function] cls.add_method('GetYears', 'double', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function] cls.add_method('IsNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function] cls.add_method('IsPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function] cls.add_method('IsStrictlyNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function] cls.add_method('IsStrictlyPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function] cls.add_method('IsZero', 'bool', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function] cls.add_method('Max', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function] cls.add_method('Min', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function] cls.add_method('StaticInit', 'bool', [], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit unit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit unit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit unit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_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_Ns3UanHeaderCommon_methods(root_module, cls): ## uan-header-common.h (module 'uan'): ns3::UanHeaderCommon::UanHeaderCommon(ns3::UanHeaderCommon const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanHeaderCommon const &', 'arg0')]) ## uan-header-common.h (module 'uan'): ns3::UanHeaderCommon::UanHeaderCommon() [constructor] cls.add_constructor([]) ## uan-header-common.h (module 'uan'): ns3::UanHeaderCommon::UanHeaderCommon(ns3::UanAddress const src, ns3::UanAddress const dest, uint8_t type) [constructor] cls.add_constructor([param('ns3::UanAddress const', 'src'), param('ns3::UanAddress const', 'dest'), param('uint8_t', 'type')]) ## uan-header-common.h (module 'uan'): uint32_t ns3::UanHeaderCommon::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## uan-header-common.h (module 'uan'): ns3::UanAddress ns3::UanHeaderCommon::GetDest() const [member function] cls.add_method('GetDest', 'ns3::UanAddress', [], is_const=True) ## uan-header-common.h (module 'uan'): ns3::TypeId ns3::UanHeaderCommon::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## uan-header-common.h (module 'uan'): uint32_t ns3::UanHeaderCommon::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## uan-header-common.h (module 'uan'): ns3::UanAddress ns3::UanHeaderCommon::GetSrc() const [member function] cls.add_method('GetSrc', 'ns3::UanAddress', [], is_const=True) ## uan-header-common.h (module 'uan'): uint8_t ns3::UanHeaderCommon::GetType() const [member function] cls.add_method('GetType', 'uint8_t', [], is_const=True) ## uan-header-common.h (module 'uan'): static ns3::TypeId ns3::UanHeaderCommon::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-header-common.h (module 'uan'): void ns3::UanHeaderCommon::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## uan-header-common.h (module 'uan'): void ns3::UanHeaderCommon::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## uan-header-common.h (module 'uan'): void ns3::UanHeaderCommon::SetDest(ns3::UanAddress dest) [member function] cls.add_method('SetDest', 'void', [param('ns3::UanAddress', 'dest')]) ## uan-header-common.h (module 'uan'): void ns3::UanHeaderCommon::SetSrc(ns3::UanAddress src) [member function] cls.add_method('SetSrc', 'void', [param('ns3::UanAddress', 'src')]) ## uan-header-common.h (module 'uan'): void ns3::UanHeaderCommon::SetType(uint8_t type) [member function] cls.add_method('SetType', 'void', [param('uint8_t', 'type')]) return def register_Ns3UanHeaderRcAck_methods(root_module, cls): ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcAck::UanHeaderRcAck(ns3::UanHeaderRcAck const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanHeaderRcAck const &', 'arg0')]) ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcAck::UanHeaderRcAck() [constructor] cls.add_constructor([]) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcAck::AddNackedFrame(uint8_t frame) [member function] cls.add_method('AddNackedFrame', 'void', [param('uint8_t', 'frame')]) ## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcAck::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcAck::GetFrameNo() const [member function] cls.add_method('GetFrameNo', 'uint8_t', [], is_const=True) ## uan-header-rc.h (module 'uan'): ns3::TypeId ns3::UanHeaderRcAck::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): std::set<unsigned char, std::less<unsigned char>, std::allocator<unsigned char> > const & ns3::UanHeaderRcAck::GetNackedFrames() const [member function] cls.add_method('GetNackedFrames', 'std::set< unsigned char > const &', [], is_const=True) ## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcAck::GetNoNacks() const [member function] cls.add_method('GetNoNacks', 'uint8_t', [], is_const=True) ## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcAck::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): static ns3::TypeId ns3::UanHeaderRcAck::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcAck::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcAck::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcAck::SetFrameNo(uint8_t frameNo) [member function] cls.add_method('SetFrameNo', 'void', [param('uint8_t', 'frameNo')]) return def register_Ns3UanHeaderRcCts_methods(root_module, cls): ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCts::UanHeaderRcCts(ns3::UanHeaderRcCts const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanHeaderRcCts const &', 'arg0')]) ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCts::UanHeaderRcCts() [constructor] cls.add_constructor([]) ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCts::UanHeaderRcCts(uint8_t frameNo, uint8_t retryNo, ns3::Time rtsTs, ns3::Time delay, ns3::UanAddress addr) [constructor] cls.add_constructor([param('uint8_t', 'frameNo'), param('uint8_t', 'retryNo'), param('ns3::Time', 'rtsTs'), param('ns3::Time', 'delay'), param('ns3::UanAddress', 'addr')]) ## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcCts::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## uan-header-rc.h (module 'uan'): ns3::UanAddress ns3::UanHeaderRcCts::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::UanAddress', [], is_const=True) ## uan-header-rc.h (module 'uan'): ns3::Time ns3::UanHeaderRcCts::GetDelayToTx() const [member function] cls.add_method('GetDelayToTx', 'ns3::Time', [], is_const=True) ## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcCts::GetFrameNo() const [member function] cls.add_method('GetFrameNo', 'uint8_t', [], is_const=True) ## uan-header-rc.h (module 'uan'): ns3::TypeId ns3::UanHeaderRcCts::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcCts::GetRetryNo() const [member function] cls.add_method('GetRetryNo', 'uint8_t', [], is_const=True) ## uan-header-rc.h (module 'uan'): ns3::Time ns3::UanHeaderRcCts::GetRtsTimeStamp() const [member function] cls.add_method('GetRtsTimeStamp', 'ns3::Time', [], is_const=True) ## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcCts::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): static ns3::TypeId ns3::UanHeaderRcCts::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::SetAddress(ns3::UanAddress addr) [member function] cls.add_method('SetAddress', 'void', [param('ns3::UanAddress', 'addr')]) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::SetDelayToTx(ns3::Time delay) [member function] cls.add_method('SetDelayToTx', 'void', [param('ns3::Time', 'delay')]) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::SetFrameNo(uint8_t frameNo) [member function] cls.add_method('SetFrameNo', 'void', [param('uint8_t', 'frameNo')]) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::SetRetryNo(uint8_t no) [member function] cls.add_method('SetRetryNo', 'void', [param('uint8_t', 'no')]) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::SetRtsTimeStamp(ns3::Time timeStamp) [member function] cls.add_method('SetRtsTimeStamp', 'void', [param('ns3::Time', 'timeStamp')]) return def register_Ns3UanHeaderRcCtsGlobal_methods(root_module, cls): ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCtsGlobal::UanHeaderRcCtsGlobal(ns3::UanHeaderRcCtsGlobal const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanHeaderRcCtsGlobal const &', 'arg0')]) ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCtsGlobal::UanHeaderRcCtsGlobal() [constructor] cls.add_constructor([]) ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCtsGlobal::UanHeaderRcCtsGlobal(ns3::Time wt, ns3::Time ts, uint16_t rate, uint16_t retryRate) [constructor] cls.add_constructor([param('ns3::Time', 'wt'), param('ns3::Time', 'ts'), param('uint16_t', 'rate'), param('uint16_t', 'retryRate')]) ## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcCtsGlobal::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## uan-header-rc.h (module 'uan'): ns3::TypeId ns3::UanHeaderRcCtsGlobal::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): uint16_t ns3::UanHeaderRcCtsGlobal::GetRateNum() const [member function] cls.add_method('GetRateNum', 'uint16_t', [], is_const=True) ## uan-header-rc.h (module 'uan'): uint16_t ns3::UanHeaderRcCtsGlobal::GetRetryRate() const [member function] cls.add_method('GetRetryRate', 'uint16_t', [], is_const=True) ## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcCtsGlobal::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): ns3::Time ns3::UanHeaderRcCtsGlobal::GetTxTimeStamp() const [member function] cls.add_method('GetTxTimeStamp', 'ns3::Time', [], is_const=True) ## uan-header-rc.h (module 'uan'): static ns3::TypeId ns3::UanHeaderRcCtsGlobal::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-header-rc.h (module 'uan'): ns3::Time ns3::UanHeaderRcCtsGlobal::GetWindowTime() const [member function] cls.add_method('GetWindowTime', 'ns3::Time', [], is_const=True) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCtsGlobal::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCtsGlobal::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCtsGlobal::SetRateNum(uint16_t rate) [member function] cls.add_method('SetRateNum', 'void', [param('uint16_t', 'rate')]) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCtsGlobal::SetRetryRate(uint16_t rate) [member function] cls.add_method('SetRetryRate', 'void', [param('uint16_t', 'rate')]) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCtsGlobal::SetTxTimeStamp(ns3::Time timeStamp) [member function] cls.add_method('SetTxTimeStamp', 'void', [param('ns3::Time', 'timeStamp')]) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCtsGlobal::SetWindowTime(ns3::Time t) [member function] cls.add_method('SetWindowTime', 'void', [param('ns3::Time', 't')]) return def register_Ns3UanHeaderRcData_methods(root_module, cls): ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcData::UanHeaderRcData(ns3::UanHeaderRcData const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanHeaderRcData const &', 'arg0')]) ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcData::UanHeaderRcData() [constructor] cls.add_constructor([]) ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcData::UanHeaderRcData(uint8_t frameNum, ns3::Time propDelay) [constructor] cls.add_constructor([param('uint8_t', 'frameNum'), param('ns3::Time', 'propDelay')]) ## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcData::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcData::GetFrameNo() const [member function] cls.add_method('GetFrameNo', 'uint8_t', [], is_const=True) ## uan-header-rc.h (module 'uan'): ns3::TypeId ns3::UanHeaderRcData::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): ns3::Time ns3::UanHeaderRcData::GetPropDelay() const [member function] cls.add_method('GetPropDelay', 'ns3::Time', [], is_const=True) ## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcData::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): static ns3::TypeId ns3::UanHeaderRcData::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcData::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcData::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcData::SetFrameNo(uint8_t frameNum) [member function] cls.add_method('SetFrameNo', 'void', [param('uint8_t', 'frameNum')]) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcData::SetPropDelay(ns3::Time propDelay) [member function] cls.add_method('SetPropDelay', 'void', [param('ns3::Time', 'propDelay')]) return def register_Ns3UanHeaderRcRts_methods(root_module, cls): ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcRts::UanHeaderRcRts(ns3::UanHeaderRcRts const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanHeaderRcRts const &', 'arg0')]) ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcRts::UanHeaderRcRts() [constructor] cls.add_constructor([]) ## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcRts::UanHeaderRcRts(uint8_t frameNo, uint8_t retryNo, uint8_t noFrames, uint16_t length, ns3::Time ts) [constructor] cls.add_constructor([param('uint8_t', 'frameNo'), param('uint8_t', 'retryNo'), param('uint8_t', 'noFrames'), param('uint16_t', 'length'), param('ns3::Time', 'ts')]) ## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcRts::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcRts::GetFrameNo() const [member function] cls.add_method('GetFrameNo', 'uint8_t', [], is_const=True) ## uan-header-rc.h (module 'uan'): ns3::TypeId ns3::UanHeaderRcRts::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): uint16_t ns3::UanHeaderRcRts::GetLength() const [member function] cls.add_method('GetLength', 'uint16_t', [], is_const=True) ## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcRts::GetNoFrames() const [member function] cls.add_method('GetNoFrames', 'uint8_t', [], is_const=True) ## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcRts::GetRetryNo() const [member function] cls.add_method('GetRetryNo', 'uint8_t', [], is_const=True) ## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcRts::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): ns3::Time ns3::UanHeaderRcRts::GetTimeStamp() const [member function] cls.add_method('GetTimeStamp', 'ns3::Time', [], is_const=True) ## uan-header-rc.h (module 'uan'): static ns3::TypeId ns3::UanHeaderRcRts::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::SetFrameNo(uint8_t fno) [member function] cls.add_method('SetFrameNo', 'void', [param('uint8_t', 'fno')]) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::SetLength(uint16_t length) [member function] cls.add_method('SetLength', 'void', [param('uint16_t', 'length')]) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::SetNoFrames(uint8_t no) [member function] cls.add_method('SetNoFrames', 'void', [param('uint8_t', 'no')]) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::SetRetryNo(uint8_t no) [member function] cls.add_method('SetRetryNo', 'void', [param('uint8_t', 'no')]) ## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::SetTimeStamp(ns3::Time timeStamp) [member function] cls.add_method('SetTimeStamp', 'void', [param('ns3::Time', 'timeStamp')]) return def register_Ns3UanMac_methods(root_module, cls): ## uan-mac.h (module 'uan'): ns3::UanMac::UanMac() [constructor] cls.add_constructor([]) ## uan-mac.h (module 'uan'): ns3::UanMac::UanMac(ns3::UanMac const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanMac const &', 'arg0')]) ## uan-mac.h (module 'uan'): int64_t ns3::UanMac::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_pure_virtual=True, is_virtual=True) ## uan-mac.h (module 'uan'): void ns3::UanMac::AttachPhy(ns3::Ptr<ns3::UanPhy> phy) [member function] cls.add_method('AttachPhy', 'void', [param('ns3::Ptr< ns3::UanPhy >', 'phy')], is_pure_virtual=True, is_virtual=True) ## uan-mac.h (module 'uan'): void ns3::UanMac::Clear() [member function] cls.add_method('Clear', 'void', [], is_pure_virtual=True, is_virtual=True) ## uan-mac.h (module 'uan'): bool ns3::UanMac::Enqueue(ns3::Ptr<ns3::Packet> pkt, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## uan-mac.h (module 'uan'): ns3::Address ns3::UanMac::GetAddress() [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_pure_virtual=True, is_virtual=True) ## uan-mac.h (module 'uan'): ns3::Address ns3::UanMac::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## uan-mac.h (module 'uan'): static ns3::TypeId ns3::UanMac::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-mac.h (module 'uan'): void ns3::UanMac::SetAddress(ns3::UanAddress addr) [member function] cls.add_method('SetAddress', 'void', [param('ns3::UanAddress', 'addr')], is_pure_virtual=True, is_virtual=True) ## uan-mac.h (module 'uan'): void ns3::UanMac::SetForwardUpCb(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::UanAddress const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetForwardUpCb', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::UanAddress const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) return def register_Ns3UanMacAloha_methods(root_module, cls): ## uan-mac-aloha.h (module 'uan'): ns3::UanMacAloha::UanMacAloha(ns3::UanMacAloha const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanMacAloha const &', 'arg0')]) ## uan-mac-aloha.h (module 'uan'): ns3::UanMacAloha::UanMacAloha() [constructor] cls.add_constructor([]) ## uan-mac-aloha.h (module 'uan'): int64_t ns3::UanMacAloha::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True) ## uan-mac-aloha.h (module 'uan'): void ns3::UanMacAloha::AttachPhy(ns3::Ptr<ns3::UanPhy> phy) [member function] cls.add_method('AttachPhy', 'void', [param('ns3::Ptr< ns3::UanPhy >', 'phy')], is_virtual=True) ## uan-mac-aloha.h (module 'uan'): void ns3::UanMacAloha::Clear() [member function] cls.add_method('Clear', 'void', [], is_virtual=True) ## uan-mac-aloha.h (module 'uan'): bool ns3::UanMacAloha::Enqueue(ns3::Ptr<ns3::Packet> pkt, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_virtual=True) ## uan-mac-aloha.h (module 'uan'): ns3::Address ns3::UanMacAloha::GetAddress() [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_virtual=True) ## uan-mac-aloha.h (module 'uan'): ns3::Address ns3::UanMacAloha::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## uan-mac-aloha.h (module 'uan'): static ns3::TypeId ns3::UanMacAloha::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-mac-aloha.h (module 'uan'): void ns3::UanMacAloha::SetAddress(ns3::UanAddress addr) [member function] cls.add_method('SetAddress', 'void', [param('ns3::UanAddress', 'addr')], is_virtual=True) ## uan-mac-aloha.h (module 'uan'): void ns3::UanMacAloha::SetForwardUpCb(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::UanAddress const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetForwardUpCb', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::UanAddress const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## uan-mac-aloha.h (module 'uan'): void ns3::UanMacAloha::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3UanMacCw_methods(root_module, cls): ## uan-mac-cw.h (module 'uan'): ns3::UanMacCw::UanMacCw(ns3::UanMacCw const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanMacCw const &', 'arg0')]) ## uan-mac-cw.h (module 'uan'): ns3::UanMacCw::UanMacCw() [constructor] cls.add_constructor([]) ## uan-mac-cw.h (module 'uan'): int64_t ns3::UanMacCw::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True) ## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::AttachPhy(ns3::Ptr<ns3::UanPhy> phy) [member function] cls.add_method('AttachPhy', 'void', [param('ns3::Ptr< ns3::UanPhy >', 'phy')], is_virtual=True) ## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::Clear() [member function] cls.add_method('Clear', 'void', [], is_virtual=True) ## uan-mac-cw.h (module 'uan'): bool ns3::UanMacCw::Enqueue(ns3::Ptr<ns3::Packet> pkt, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_virtual=True) ## uan-mac-cw.h (module 'uan'): ns3::Address ns3::UanMacCw::GetAddress() [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_virtual=True) ## uan-mac-cw.h (module 'uan'): ns3::Address ns3::UanMacCw::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## uan-mac-cw.h (module 'uan'): uint32_t ns3::UanMacCw::GetCw() [member function] cls.add_method('GetCw', 'uint32_t', [], is_virtual=True) ## uan-mac-cw.h (module 'uan'): ns3::Time ns3::UanMacCw::GetSlotTime() [member function] cls.add_method('GetSlotTime', 'ns3::Time', [], is_virtual=True) ## uan-mac-cw.h (module 'uan'): static ns3::TypeId ns3::UanMacCw::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::NotifyCcaEnd() [member function] cls.add_method('NotifyCcaEnd', 'void', [], is_virtual=True) ## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::NotifyCcaStart() [member function] cls.add_method('NotifyCcaStart', 'void', [], is_virtual=True) ## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::NotifyRxEndError() [member function] cls.add_method('NotifyRxEndError', 'void', [], is_virtual=True) ## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::NotifyRxEndOk() [member function] cls.add_method('NotifyRxEndOk', 'void', [], is_virtual=True) ## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::NotifyRxStart() [member function] cls.add_method('NotifyRxStart', 'void', [], is_virtual=True) ## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::NotifyTxStart(ns3::Time duration) [member function] cls.add_method('NotifyTxStart', 'void', [param('ns3::Time', 'duration')], is_virtual=True) ## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::SetAddress(ns3::UanAddress addr) [member function] cls.add_method('SetAddress', 'void', [param('ns3::UanAddress', 'addr')], is_virtual=True) ## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::SetCw(uint32_t cw) [member function] cls.add_method('SetCw', 'void', [param('uint32_t', 'cw')], is_virtual=True) ## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::SetForwardUpCb(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::UanAddress const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetForwardUpCb', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::UanAddress const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::SetSlotTime(ns3::Time duration) [member function] cls.add_method('SetSlotTime', 'void', [param('ns3::Time', 'duration')], is_virtual=True) ## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3UanMacRc_methods(root_module, cls): ## uan-mac-rc.h (module 'uan'): ns3::UanMacRc::UanMacRc(ns3::UanMacRc const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanMacRc const &', 'arg0')]) ## uan-mac-rc.h (module 'uan'): ns3::UanMacRc::UanMacRc() [constructor] cls.add_constructor([]) ## uan-mac-rc.h (module 'uan'): int64_t ns3::UanMacRc::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True) ## uan-mac-rc.h (module 'uan'): void ns3::UanMacRc::AttachPhy(ns3::Ptr<ns3::UanPhy> phy) [member function] cls.add_method('AttachPhy', 'void', [param('ns3::Ptr< ns3::UanPhy >', 'phy')], is_virtual=True) ## uan-mac-rc.h (module 'uan'): void ns3::UanMacRc::Clear() [member function] cls.add_method('Clear', 'void', [], is_virtual=True) ## uan-mac-rc.h (module 'uan'): bool ns3::UanMacRc::Enqueue(ns3::Ptr<ns3::Packet> pkt, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_virtual=True) ## uan-mac-rc.h (module 'uan'): ns3::Address ns3::UanMacRc::GetAddress() [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_virtual=True) ## uan-mac-rc.h (module 'uan'): ns3::Address ns3::UanMacRc::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## uan-mac-rc.h (module 'uan'): static ns3::TypeId ns3::UanMacRc::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-mac-rc.h (module 'uan'): void ns3::UanMacRc::SetAddress(ns3::UanAddress addr) [member function] cls.add_method('SetAddress', 'void', [param('ns3::UanAddress', 'addr')], is_virtual=True) ## uan-mac-rc.h (module 'uan'): void ns3::UanMacRc::SetForwardUpCb(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::UanAddress const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetForwardUpCb', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::UanAddress const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## uan-mac-rc.h (module 'uan'): void ns3::UanMacRc::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3UanMacRcGw_methods(root_module, cls): ## uan-mac-rc-gw.h (module 'uan'): ns3::UanMacRcGw::UanMacRcGw(ns3::UanMacRcGw const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanMacRcGw const &', 'arg0')]) ## uan-mac-rc-gw.h (module 'uan'): ns3::UanMacRcGw::UanMacRcGw() [constructor] cls.add_constructor([]) ## uan-mac-rc-gw.h (module 'uan'): int64_t ns3::UanMacRcGw::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True) ## uan-mac-rc-gw.h (module 'uan'): void ns3::UanMacRcGw::AttachPhy(ns3::Ptr<ns3::UanPhy> phy) [member function] cls.add_method('AttachPhy', 'void', [param('ns3::Ptr< ns3::UanPhy >', 'phy')], is_virtual=True) ## uan-mac-rc-gw.h (module 'uan'): void ns3::UanMacRcGw::Clear() [member function] cls.add_method('Clear', 'void', [], is_virtual=True) ## uan-mac-rc-gw.h (module 'uan'): bool ns3::UanMacRcGw::Enqueue(ns3::Ptr<ns3::Packet> pkt, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_virtual=True) ## uan-mac-rc-gw.h (module 'uan'): ns3::Address ns3::UanMacRcGw::GetAddress() [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_virtual=True) ## uan-mac-rc-gw.h (module 'uan'): ns3::Address ns3::UanMacRcGw::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## uan-mac-rc-gw.h (module 'uan'): static ns3::TypeId ns3::UanMacRcGw::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-mac-rc-gw.h (module 'uan'): void ns3::UanMacRcGw::SetAddress(ns3::UanAddress addr) [member function] cls.add_method('SetAddress', 'void', [param('ns3::UanAddress', 'addr')], is_virtual=True) ## uan-mac-rc-gw.h (module 'uan'): void ns3::UanMacRcGw::SetForwardUpCb(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::UanAddress const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetForwardUpCb', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::UanAddress const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## uan-mac-rc-gw.h (module 'uan'): void ns3::UanMacRcGw::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3UanNoiseModel_methods(root_module, cls): ## uan-noise-model.h (module 'uan'): ns3::UanNoiseModel::UanNoiseModel() [constructor] cls.add_constructor([]) ## uan-noise-model.h (module 'uan'): ns3::UanNoiseModel::UanNoiseModel(ns3::UanNoiseModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanNoiseModel const &', 'arg0')]) ## uan-noise-model.h (module 'uan'): void ns3::UanNoiseModel::Clear() [member function] cls.add_method('Clear', 'void', [], is_virtual=True) ## uan-noise-model.h (module 'uan'): void ns3::UanNoiseModel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## uan-noise-model.h (module 'uan'): double ns3::UanNoiseModel::GetNoiseDbHz(double fKhz) const [member function] cls.add_method('GetNoiseDbHz', 'double', [param('double', 'fKhz')], is_pure_virtual=True, is_const=True, is_virtual=True) ## uan-noise-model.h (module 'uan'): static ns3::TypeId ns3::UanNoiseModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3UanNoiseModelDefault_methods(root_module, cls): ## uan-noise-model-default.h (module 'uan'): ns3::UanNoiseModelDefault::UanNoiseModelDefault(ns3::UanNoiseModelDefault const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanNoiseModelDefault const &', 'arg0')]) ## uan-noise-model-default.h (module 'uan'): ns3::UanNoiseModelDefault::UanNoiseModelDefault() [constructor] cls.add_constructor([]) ## uan-noise-model-default.h (module 'uan'): double ns3::UanNoiseModelDefault::GetNoiseDbHz(double fKhz) const [member function] cls.add_method('GetNoiseDbHz', 'double', [param('double', 'fKhz')], is_const=True, is_virtual=True) ## uan-noise-model-default.h (module 'uan'): static ns3::TypeId ns3::UanNoiseModelDefault::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3UanPhy_methods(root_module, cls): ## uan-phy.h (module 'uan'): ns3::UanPhy::UanPhy() [constructor] cls.add_constructor([]) ## uan-phy.h (module 'uan'): ns3::UanPhy::UanPhy(ns3::UanPhy const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanPhy const &', 'arg0')]) ## uan-phy.h (module 'uan'): int64_t ns3::UanPhy::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::Clear() [member function] cls.add_method('Clear', 'void', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::EnergyDepletionHandler() [member function] cls.add_method('EnergyDepletionHandler', 'void', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::EnergyRechargeHandler() [member function] cls.add_method('EnergyRechargeHandler', 'void', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): double ns3::UanPhy::GetCcaThresholdDb() [member function] cls.add_method('GetCcaThresholdDb', 'double', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): ns3::Ptr<ns3::UanChannel> ns3::UanPhy::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::UanChannel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## uan-phy.h (module 'uan'): ns3::Ptr<ns3::UanNetDevice> ns3::UanPhy::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::UanNetDevice >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## uan-phy.h (module 'uan'): ns3::UanTxMode ns3::UanPhy::GetMode(uint32_t n) [member function] cls.add_method('GetMode', 'ns3::UanTxMode', [param('uint32_t', 'n')], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): uint32_t ns3::UanPhy::GetNModes() [member function] cls.add_method('GetNModes', 'uint32_t', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): ns3::Ptr<ns3::Packet> ns3::UanPhy::GetPacketRx() const [member function] cls.add_method('GetPacketRx', 'ns3::Ptr< ns3::Packet >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## uan-phy.h (module 'uan'): double ns3::UanPhy::GetRxGainDb() [member function] cls.add_method('GetRxGainDb', 'double', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): double ns3::UanPhy::GetRxThresholdDb() [member function] cls.add_method('GetRxThresholdDb', 'double', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): ns3::Ptr<ns3::UanTransducer> ns3::UanPhy::GetTransducer() [member function] cls.add_method('GetTransducer', 'ns3::Ptr< ns3::UanTransducer >', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): double ns3::UanPhy::GetTxPowerDb() [member function] cls.add_method('GetTxPowerDb', 'double', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): static ns3::TypeId ns3::UanPhy::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-phy.h (module 'uan'): bool ns3::UanPhy::IsStateBusy() [member function] cls.add_method('IsStateBusy', 'bool', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): bool ns3::UanPhy::IsStateCcaBusy() [member function] cls.add_method('IsStateCcaBusy', 'bool', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): bool ns3::UanPhy::IsStateIdle() [member function] cls.add_method('IsStateIdle', 'bool', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): bool ns3::UanPhy::IsStateRx() [member function] cls.add_method('IsStateRx', 'bool', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): bool ns3::UanPhy::IsStateSleep() [member function] cls.add_method('IsStateSleep', 'bool', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): bool ns3::UanPhy::IsStateTx() [member function] cls.add_method('IsStateTx', 'bool', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::NotifyIntChange() [member function] cls.add_method('NotifyIntChange', 'void', [], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::NotifyRxBegin(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('NotifyRxBegin', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## uan-phy.h (module 'uan'): void ns3::UanPhy::NotifyRxDrop(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('NotifyRxDrop', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## uan-phy.h (module 'uan'): void ns3::UanPhy::NotifyRxEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('NotifyRxEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## uan-phy.h (module 'uan'): void ns3::UanPhy::NotifyTransStartTx(ns3::Ptr<ns3::Packet> packet, double txPowerDb, ns3::UanTxMode txMode) [member function] cls.add_method('NotifyTransStartTx', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txMode')], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::NotifyTxBegin(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('NotifyTxBegin', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## uan-phy.h (module 'uan'): void ns3::UanPhy::NotifyTxDrop(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('NotifyTxDrop', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## uan-phy.h (module 'uan'): void ns3::UanPhy::NotifyTxEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('NotifyTxEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## uan-phy.h (module 'uan'): void ns3::UanPhy::RegisterListener(ns3::UanPhyListener * listener) [member function] cls.add_method('RegisterListener', 'void', [param('ns3::UanPhyListener *', 'listener')], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::SendPacket(ns3::Ptr<ns3::Packet> pkt, uint32_t modeNum) [member function] cls.add_method('SendPacket', 'void', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('uint32_t', 'modeNum')], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::SetCcaThresholdDb(double thresh) [member function] cls.add_method('SetCcaThresholdDb', 'void', [param('double', 'thresh')], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::SetChannel(ns3::Ptr<ns3::UanChannel> channel) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::UanChannel >', 'channel')], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::SetDevice(ns3::Ptr<ns3::UanNetDevice> device) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::UanNetDevice >', 'device')], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::SetEnergyModelCallback(ns3::Callback<void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('SetEnergyModelCallback', 'void', [param('ns3::Callback< void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::SetMac(ns3::Ptr<ns3::UanMac> mac) [member function] cls.add_method('SetMac', 'void', [param('ns3::Ptr< ns3::UanMac >', 'mac')], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::SetReceiveErrorCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetReceiveErrorCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::SetReceiveOkCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetReceiveOkCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::SetRxGainDb(double gain) [member function] cls.add_method('SetRxGainDb', 'void', [param('double', 'gain')], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::SetRxThresholdDb(double thresh) [member function] cls.add_method('SetRxThresholdDb', 'void', [param('double', 'thresh')], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::SetSleepMode(bool sleep) [member function] cls.add_method('SetSleepMode', 'void', [param('bool', 'sleep')], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::SetTransducer(ns3::Ptr<ns3::UanTransducer> trans) [member function] cls.add_method('SetTransducer', 'void', [param('ns3::Ptr< ns3::UanTransducer >', 'trans')], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::SetTxPowerDb(double txpwr) [member function] cls.add_method('SetTxPowerDb', 'void', [param('double', 'txpwr')], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhy::StartRxPacket(ns3::Ptr<ns3::Packet> pkt, double rxPowerDb, ns3::UanTxMode txMode, ns3::UanPdp pdp) [member function] cls.add_method('StartRxPacket', 'void', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'rxPowerDb'), param('ns3::UanTxMode', 'txMode'), param('ns3::UanPdp', 'pdp')], is_pure_virtual=True, is_virtual=True) return def register_Ns3UanPhyCalcSinr_methods(root_module, cls): ## uan-phy.h (module 'uan'): ns3::UanPhyCalcSinr::UanPhyCalcSinr() [constructor] cls.add_constructor([]) ## uan-phy.h (module 'uan'): ns3::UanPhyCalcSinr::UanPhyCalcSinr(ns3::UanPhyCalcSinr const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanPhyCalcSinr const &', 'arg0')]) ## uan-phy.h (module 'uan'): double ns3::UanPhyCalcSinr::CalcSinrDb(ns3::Ptr<ns3::Packet> pkt, ns3::Time arrTime, double rxPowerDb, double ambNoiseDb, ns3::UanTxMode mode, ns3::UanPdp pdp, std::list<ns3::UanPacketArrival, std::allocator<ns3::UanPacketArrival> > const & arrivalList) const [member function] cls.add_method('CalcSinrDb', 'double', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Time', 'arrTime'), param('double', 'rxPowerDb'), param('double', 'ambNoiseDb'), param('ns3::UanTxMode', 'mode'), param('ns3::UanPdp', 'pdp'), param('std::list< ns3::UanPacketArrival > const &', 'arrivalList')], is_pure_virtual=True, is_const=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhyCalcSinr::Clear() [member function] cls.add_method('Clear', 'void', [], is_virtual=True) ## uan-phy.h (module 'uan'): double ns3::UanPhyCalcSinr::DbToKp(double db) const [member function] cls.add_method('DbToKp', 'double', [param('double', 'db')], is_const=True) ## uan-phy.h (module 'uan'): static ns3::TypeId ns3::UanPhyCalcSinr::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-phy.h (module 'uan'): double ns3::UanPhyCalcSinr::KpToDb(double kp) const [member function] cls.add_method('KpToDb', 'double', [param('double', 'kp')], is_const=True) ## uan-phy.h (module 'uan'): void ns3::UanPhyCalcSinr::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3UanPhyCalcSinrDefault_methods(root_module, cls): ## uan-phy-gen.h (module 'uan'): ns3::UanPhyCalcSinrDefault::UanPhyCalcSinrDefault(ns3::UanPhyCalcSinrDefault const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanPhyCalcSinrDefault const &', 'arg0')]) ## uan-phy-gen.h (module 'uan'): ns3::UanPhyCalcSinrDefault::UanPhyCalcSinrDefault() [constructor] cls.add_constructor([]) ## uan-phy-gen.h (module 'uan'): double ns3::UanPhyCalcSinrDefault::CalcSinrDb(ns3::Ptr<ns3::Packet> pkt, ns3::Time arrTime, double rxPowerDb, double ambNoiseDb, ns3::UanTxMode mode, ns3::UanPdp pdp, std::list<ns3::UanPacketArrival, std::allocator<ns3::UanPacketArrival> > const & arrivalList) const [member function] cls.add_method('CalcSinrDb', 'double', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Time', 'arrTime'), param('double', 'rxPowerDb'), param('double', 'ambNoiseDb'), param('ns3::UanTxMode', 'mode'), param('ns3::UanPdp', 'pdp'), param('std::list< ns3::UanPacketArrival > const &', 'arrivalList')], is_const=True, is_virtual=True) ## uan-phy-gen.h (module 'uan'): static ns3::TypeId ns3::UanPhyCalcSinrDefault::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3UanPhyCalcSinrDual_methods(root_module, cls): ## uan-phy-dual.h (module 'uan'): ns3::UanPhyCalcSinrDual::UanPhyCalcSinrDual(ns3::UanPhyCalcSinrDual const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanPhyCalcSinrDual const &', 'arg0')]) ## uan-phy-dual.h (module 'uan'): ns3::UanPhyCalcSinrDual::UanPhyCalcSinrDual() [constructor] cls.add_constructor([]) ## uan-phy-dual.h (module 'uan'): double ns3::UanPhyCalcSinrDual::CalcSinrDb(ns3::Ptr<ns3::Packet> pkt, ns3::Time arrTime, double rxPowerDb, double ambNoiseDb, ns3::UanTxMode mode, ns3::UanPdp pdp, std::list<ns3::UanPacketArrival, std::allocator<ns3::UanPacketArrival> > const & arrivalList) const [member function] cls.add_method('CalcSinrDb', 'double', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Time', 'arrTime'), param('double', 'rxPowerDb'), param('double', 'ambNoiseDb'), param('ns3::UanTxMode', 'mode'), param('ns3::UanPdp', 'pdp'), param('std::list< ns3::UanPacketArrival > const &', 'arrivalList')], is_const=True, is_virtual=True) ## uan-phy-dual.h (module 'uan'): static ns3::TypeId ns3::UanPhyCalcSinrDual::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3UanPhyCalcSinrFhFsk_methods(root_module, cls): ## uan-phy-gen.h (module 'uan'): ns3::UanPhyCalcSinrFhFsk::UanPhyCalcSinrFhFsk(ns3::UanPhyCalcSinrFhFsk const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanPhyCalcSinrFhFsk const &', 'arg0')]) ## uan-phy-gen.h (module 'uan'): ns3::UanPhyCalcSinrFhFsk::UanPhyCalcSinrFhFsk() [constructor] cls.add_constructor([]) ## uan-phy-gen.h (module 'uan'): double ns3::UanPhyCalcSinrFhFsk::CalcSinrDb(ns3::Ptr<ns3::Packet> pkt, ns3::Time arrTime, double rxPowerDb, double ambNoiseDb, ns3::UanTxMode mode, ns3::UanPdp pdp, std::list<ns3::UanPacketArrival, std::allocator<ns3::UanPacketArrival> > const & arrivalList) const [member function] cls.add_method('CalcSinrDb', 'double', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Time', 'arrTime'), param('double', 'rxPowerDb'), param('double', 'ambNoiseDb'), param('ns3::UanTxMode', 'mode'), param('ns3::UanPdp', 'pdp'), param('std::list< ns3::UanPacketArrival > const &', 'arrivalList')], is_const=True, is_virtual=True) ## uan-phy-gen.h (module 'uan'): static ns3::TypeId ns3::UanPhyCalcSinrFhFsk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3UanPhyDual_methods(root_module, cls): ## uan-phy-dual.h (module 'uan'): ns3::UanPhyDual::UanPhyDual(ns3::UanPhyDual const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanPhyDual const &', 'arg0')]) ## uan-phy-dual.h (module 'uan'): ns3::UanPhyDual::UanPhyDual() [constructor] cls.add_constructor([]) ## uan-phy-dual.h (module 'uan'): int64_t ns3::UanPhyDual::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::Clear() [member function] cls.add_method('Clear', 'void', [], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::EnergyDepletionHandler() [member function] cls.add_method('EnergyDepletionHandler', 'void', [], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::EnergyRechargeHandler() [member function] cls.add_method('EnergyRechargeHandler', 'void', [], is_virtual=True) ## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetCcaThresholdDb() [member function] cls.add_method('GetCcaThresholdDb', 'double', [], is_virtual=True) ## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetCcaThresholdPhy1() const [member function] cls.add_method('GetCcaThresholdPhy1', 'double', [], is_const=True) ## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetCcaThresholdPhy2() const [member function] cls.add_method('GetCcaThresholdPhy2', 'double', [], is_const=True) ## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanChannel> ns3::UanPhyDual::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::UanChannel >', [], is_const=True, is_virtual=True) ## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanNetDevice> ns3::UanPhyDual::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::UanNetDevice >', [], is_const=True, is_virtual=True) ## uan-phy-dual.h (module 'uan'): ns3::UanTxMode ns3::UanPhyDual::GetMode(uint32_t n) [member function] cls.add_method('GetMode', 'ns3::UanTxMode', [param('uint32_t', 'n')], is_virtual=True) ## uan-phy-dual.h (module 'uan'): ns3::UanModesList ns3::UanPhyDual::GetModesPhy1() const [member function] cls.add_method('GetModesPhy1', 'ns3::UanModesList', [], is_const=True) ## uan-phy-dual.h (module 'uan'): ns3::UanModesList ns3::UanPhyDual::GetModesPhy2() const [member function] cls.add_method('GetModesPhy2', 'ns3::UanModesList', [], is_const=True) ## uan-phy-dual.h (module 'uan'): uint32_t ns3::UanPhyDual::GetNModes() [member function] cls.add_method('GetNModes', 'uint32_t', [], is_virtual=True) ## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::Packet> ns3::UanPhyDual::GetPacketRx() const [member function] cls.add_method('GetPacketRx', 'ns3::Ptr< ns3::Packet >', [], is_const=True, is_virtual=True) ## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanPhyPer> ns3::UanPhyDual::GetPerModelPhy1() const [member function] cls.add_method('GetPerModelPhy1', 'ns3::Ptr< ns3::UanPhyPer >', [], is_const=True) ## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanPhyPer> ns3::UanPhyDual::GetPerModelPhy2() const [member function] cls.add_method('GetPerModelPhy2', 'ns3::Ptr< ns3::UanPhyPer >', [], is_const=True) ## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::Packet> ns3::UanPhyDual::GetPhy1PacketRx() const [member function] cls.add_method('GetPhy1PacketRx', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::Packet> ns3::UanPhyDual::GetPhy2PacketRx() const [member function] cls.add_method('GetPhy2PacketRx', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetRxGainDb() [member function] cls.add_method('GetRxGainDb', 'double', [], is_virtual=True) ## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetRxGainDbPhy1() const [member function] cls.add_method('GetRxGainDbPhy1', 'double', [], is_const=True) ## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetRxGainDbPhy2() const [member function] cls.add_method('GetRxGainDbPhy2', 'double', [], is_const=True) ## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetRxThresholdDb() [member function] cls.add_method('GetRxThresholdDb', 'double', [], is_virtual=True) ## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanPhyCalcSinr> ns3::UanPhyDual::GetSinrModelPhy1() const [member function] cls.add_method('GetSinrModelPhy1', 'ns3::Ptr< ns3::UanPhyCalcSinr >', [], is_const=True) ## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanPhyCalcSinr> ns3::UanPhyDual::GetSinrModelPhy2() const [member function] cls.add_method('GetSinrModelPhy2', 'ns3::Ptr< ns3::UanPhyCalcSinr >', [], is_const=True) ## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanTransducer> ns3::UanPhyDual::GetTransducer() [member function] cls.add_method('GetTransducer', 'ns3::Ptr< ns3::UanTransducer >', [], is_virtual=True) ## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetTxPowerDb() [member function] cls.add_method('GetTxPowerDb', 'double', [], is_virtual=True) ## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetTxPowerDbPhy1() const [member function] cls.add_method('GetTxPowerDbPhy1', 'double', [], is_const=True) ## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetTxPowerDbPhy2() const [member function] cls.add_method('GetTxPowerDbPhy2', 'double', [], is_const=True) ## uan-phy-dual.h (module 'uan'): static ns3::TypeId ns3::UanPhyDual::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsPhy1Idle() [member function] cls.add_method('IsPhy1Idle', 'bool', []) ## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsPhy1Rx() [member function] cls.add_method('IsPhy1Rx', 'bool', []) ## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsPhy1Tx() [member function] cls.add_method('IsPhy1Tx', 'bool', []) ## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsPhy2Idle() [member function] cls.add_method('IsPhy2Idle', 'bool', []) ## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsPhy2Rx() [member function] cls.add_method('IsPhy2Rx', 'bool', []) ## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsPhy2Tx() [member function] cls.add_method('IsPhy2Tx', 'bool', []) ## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsStateBusy() [member function] cls.add_method('IsStateBusy', 'bool', [], is_virtual=True) ## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsStateCcaBusy() [member function] cls.add_method('IsStateCcaBusy', 'bool', [], is_virtual=True) ## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsStateIdle() [member function] cls.add_method('IsStateIdle', 'bool', [], is_virtual=True) ## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsStateRx() [member function] cls.add_method('IsStateRx', 'bool', [], is_virtual=True) ## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsStateSleep() [member function] cls.add_method('IsStateSleep', 'bool', [], is_virtual=True) ## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsStateTx() [member function] cls.add_method('IsStateTx', 'bool', [], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::NotifyIntChange() [member function] cls.add_method('NotifyIntChange', 'void', [], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::NotifyTransStartTx(ns3::Ptr<ns3::Packet> packet, double txPowerDb, ns3::UanTxMode txMode) [member function] cls.add_method('NotifyTransStartTx', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txMode')], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::RegisterListener(ns3::UanPhyListener * listener) [member function] cls.add_method('RegisterListener', 'void', [param('ns3::UanPhyListener *', 'listener')], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SendPacket(ns3::Ptr<ns3::Packet> pkt, uint32_t modeNum) [member function] cls.add_method('SendPacket', 'void', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('uint32_t', 'modeNum')], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetCcaThresholdDb(double thresh) [member function] cls.add_method('SetCcaThresholdDb', 'void', [param('double', 'thresh')], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetCcaThresholdPhy1(double thresh) [member function] cls.add_method('SetCcaThresholdPhy1', 'void', [param('double', 'thresh')]) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetCcaThresholdPhy2(double thresh) [member function] cls.add_method('SetCcaThresholdPhy2', 'void', [param('double', 'thresh')]) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetChannel(ns3::Ptr<ns3::UanChannel> channel) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::UanChannel >', 'channel')], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetDevice(ns3::Ptr<ns3::UanNetDevice> device) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::UanNetDevice >', 'device')], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetEnergyModelCallback(ns3::Callback<void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('SetEnergyModelCallback', 'void', [param('ns3::Callback< void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetMac(ns3::Ptr<ns3::UanMac> mac) [member function] cls.add_method('SetMac', 'void', [param('ns3::Ptr< ns3::UanMac >', 'mac')], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetModesPhy1(ns3::UanModesList modes) [member function] cls.add_method('SetModesPhy1', 'void', [param('ns3::UanModesList', 'modes')]) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetModesPhy2(ns3::UanModesList modes) [member function] cls.add_method('SetModesPhy2', 'void', [param('ns3::UanModesList', 'modes')]) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetPerModelPhy1(ns3::Ptr<ns3::UanPhyPer> per) [member function] cls.add_method('SetPerModelPhy1', 'void', [param('ns3::Ptr< ns3::UanPhyPer >', 'per')]) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetPerModelPhy2(ns3::Ptr<ns3::UanPhyPer> per) [member function] cls.add_method('SetPerModelPhy2', 'void', [param('ns3::Ptr< ns3::UanPhyPer >', 'per')]) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetReceiveErrorCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetReceiveErrorCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetReceiveOkCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetReceiveOkCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetRxGainDb(double gain) [member function] cls.add_method('SetRxGainDb', 'void', [param('double', 'gain')], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetRxGainDbPhy1(double gain) [member function] cls.add_method('SetRxGainDbPhy1', 'void', [param('double', 'gain')]) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetRxGainDbPhy2(double gain) [member function] cls.add_method('SetRxGainDbPhy2', 'void', [param('double', 'gain')]) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetRxThresholdDb(double thresh) [member function] cls.add_method('SetRxThresholdDb', 'void', [param('double', 'thresh')], deprecated=True, is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetSinrModelPhy1(ns3::Ptr<ns3::UanPhyCalcSinr> calcSinr) [member function] cls.add_method('SetSinrModelPhy1', 'void', [param('ns3::Ptr< ns3::UanPhyCalcSinr >', 'calcSinr')]) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetSinrModelPhy2(ns3::Ptr<ns3::UanPhyCalcSinr> calcSinr) [member function] cls.add_method('SetSinrModelPhy2', 'void', [param('ns3::Ptr< ns3::UanPhyCalcSinr >', 'calcSinr')]) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetSleepMode(bool sleep) [member function] cls.add_method('SetSleepMode', 'void', [param('bool', 'sleep')], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetTransducer(ns3::Ptr<ns3::UanTransducer> trans) [member function] cls.add_method('SetTransducer', 'void', [param('ns3::Ptr< ns3::UanTransducer >', 'trans')], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetTxPowerDb(double txpwr) [member function] cls.add_method('SetTxPowerDb', 'void', [param('double', 'txpwr')], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetTxPowerDbPhy1(double txpwr) [member function] cls.add_method('SetTxPowerDbPhy1', 'void', [param('double', 'txpwr')]) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetTxPowerDbPhy2(double txpwr) [member function] cls.add_method('SetTxPowerDbPhy2', 'void', [param('double', 'txpwr')]) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::StartRxPacket(ns3::Ptr<ns3::Packet> pkt, double rxPowerDb, ns3::UanTxMode txMode, ns3::UanPdp pdp) [member function] cls.add_method('StartRxPacket', 'void', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'rxPowerDb'), param('ns3::UanTxMode', 'txMode'), param('ns3::UanPdp', 'pdp')], is_virtual=True) ## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3UanPhyGen_methods(root_module, cls): ## uan-phy-gen.h (module 'uan'): ns3::UanPhyGen::UanPhyGen(ns3::UanPhyGen const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanPhyGen const &', 'arg0')]) ## uan-phy-gen.h (module 'uan'): ns3::UanPhyGen::UanPhyGen() [constructor] cls.add_constructor([]) ## uan-phy-gen.h (module 'uan'): int64_t ns3::UanPhyGen::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::Clear() [member function] cls.add_method('Clear', 'void', [], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::EnergyDepletionHandler() [member function] cls.add_method('EnergyDepletionHandler', 'void', [], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::EnergyRechargeHandler() [member function] cls.add_method('EnergyRechargeHandler', 'void', [], is_virtual=True) ## uan-phy-gen.h (module 'uan'): double ns3::UanPhyGen::GetCcaThresholdDb() [member function] cls.add_method('GetCcaThresholdDb', 'double', [], is_virtual=True) ## uan-phy-gen.h (module 'uan'): ns3::Ptr<ns3::UanChannel> ns3::UanPhyGen::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::UanChannel >', [], is_const=True, is_virtual=True) ## uan-phy-gen.h (module 'uan'): static ns3::UanModesList ns3::UanPhyGen::GetDefaultModes() [member function] cls.add_method('GetDefaultModes', 'ns3::UanModesList', [], is_static=True) ## uan-phy-gen.h (module 'uan'): ns3::Ptr<ns3::UanNetDevice> ns3::UanPhyGen::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::UanNetDevice >', [], is_const=True, is_virtual=True) ## uan-phy-gen.h (module 'uan'): ns3::UanTxMode ns3::UanPhyGen::GetMode(uint32_t n) [member function] cls.add_method('GetMode', 'ns3::UanTxMode', [param('uint32_t', 'n')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): uint32_t ns3::UanPhyGen::GetNModes() [member function] cls.add_method('GetNModes', 'uint32_t', [], is_virtual=True) ## uan-phy-gen.h (module 'uan'): ns3::Ptr<ns3::Packet> ns3::UanPhyGen::GetPacketRx() const [member function] cls.add_method('GetPacketRx', 'ns3::Ptr< ns3::Packet >', [], is_const=True, is_virtual=True) ## uan-phy-gen.h (module 'uan'): double ns3::UanPhyGen::GetRxGainDb() [member function] cls.add_method('GetRxGainDb', 'double', [], is_virtual=True) ## uan-phy-gen.h (module 'uan'): double ns3::UanPhyGen::GetRxThresholdDb() [member function] cls.add_method('GetRxThresholdDb', 'double', [], is_virtual=True) ## uan-phy-gen.h (module 'uan'): ns3::Ptr<ns3::UanTransducer> ns3::UanPhyGen::GetTransducer() [member function] cls.add_method('GetTransducer', 'ns3::Ptr< ns3::UanTransducer >', [], is_virtual=True) ## uan-phy-gen.h (module 'uan'): double ns3::UanPhyGen::GetTxPowerDb() [member function] cls.add_method('GetTxPowerDb', 'double', [], is_virtual=True) ## uan-phy-gen.h (module 'uan'): static ns3::TypeId ns3::UanPhyGen::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-phy-gen.h (module 'uan'): bool ns3::UanPhyGen::IsStateBusy() [member function] cls.add_method('IsStateBusy', 'bool', [], is_virtual=True) ## uan-phy-gen.h (module 'uan'): bool ns3::UanPhyGen::IsStateCcaBusy() [member function] cls.add_method('IsStateCcaBusy', 'bool', [], is_virtual=True) ## uan-phy-gen.h (module 'uan'): bool ns3::UanPhyGen::IsStateIdle() [member function] cls.add_method('IsStateIdle', 'bool', [], is_virtual=True) ## uan-phy-gen.h (module 'uan'): bool ns3::UanPhyGen::IsStateRx() [member function] cls.add_method('IsStateRx', 'bool', [], is_virtual=True) ## uan-phy-gen.h (module 'uan'): bool ns3::UanPhyGen::IsStateSleep() [member function] cls.add_method('IsStateSleep', 'bool', [], is_virtual=True) ## uan-phy-gen.h (module 'uan'): bool ns3::UanPhyGen::IsStateTx() [member function] cls.add_method('IsStateTx', 'bool', [], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::NotifyIntChange() [member function] cls.add_method('NotifyIntChange', 'void', [], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::NotifyTransStartTx(ns3::Ptr<ns3::Packet> packet, double txPowerDb, ns3::UanTxMode txMode) [member function] cls.add_method('NotifyTransStartTx', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txMode')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::RegisterListener(ns3::UanPhyListener * listener) [member function] cls.add_method('RegisterListener', 'void', [param('ns3::UanPhyListener *', 'listener')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SendPacket(ns3::Ptr<ns3::Packet> pkt, uint32_t modeNum) [member function] cls.add_method('SendPacket', 'void', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('uint32_t', 'modeNum')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetCcaThresholdDb(double thresh) [member function] cls.add_method('SetCcaThresholdDb', 'void', [param('double', 'thresh')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetChannel(ns3::Ptr<ns3::UanChannel> channel) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::UanChannel >', 'channel')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetDevice(ns3::Ptr<ns3::UanNetDevice> device) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::UanNetDevice >', 'device')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetEnergyModelCallback(ns3::Callback<void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetEnergyModelCallback', 'void', [param('ns3::Callback< void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetMac(ns3::Ptr<ns3::UanMac> mac) [member function] cls.add_method('SetMac', 'void', [param('ns3::Ptr< ns3::UanMac >', 'mac')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetReceiveErrorCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetReceiveErrorCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetReceiveOkCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetReceiveOkCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetRxGainDb(double gain) [member function] cls.add_method('SetRxGainDb', 'void', [param('double', 'gain')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetRxThresholdDb(double thresh) [member function] cls.add_method('SetRxThresholdDb', 'void', [param('double', 'thresh')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetSleepMode(bool sleep) [member function] cls.add_method('SetSleepMode', 'void', [param('bool', 'sleep')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetTransducer(ns3::Ptr<ns3::UanTransducer> trans) [member function] cls.add_method('SetTransducer', 'void', [param('ns3::Ptr< ns3::UanTransducer >', 'trans')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetTxPowerDb(double txpwr) [member function] cls.add_method('SetTxPowerDb', 'void', [param('double', 'txpwr')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::StartRxPacket(ns3::Ptr<ns3::Packet> pkt, double rxPowerDb, ns3::UanTxMode txMode, ns3::UanPdp pdp) [member function] cls.add_method('StartRxPacket', 'void', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'rxPowerDb'), param('ns3::UanTxMode', 'txMode'), param('ns3::UanPdp', 'pdp')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3UanPhyPer_methods(root_module, cls): ## uan-phy.h (module 'uan'): ns3::UanPhyPer::UanPhyPer() [constructor] cls.add_constructor([]) ## uan-phy.h (module 'uan'): ns3::UanPhyPer::UanPhyPer(ns3::UanPhyPer const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanPhyPer const &', 'arg0')]) ## uan-phy.h (module 'uan'): double ns3::UanPhyPer::CalcPer(ns3::Ptr<ns3::Packet> pkt, double sinrDb, ns3::UanTxMode mode) [member function] cls.add_method('CalcPer', 'double', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'sinrDb'), param('ns3::UanTxMode', 'mode')], is_pure_virtual=True, is_virtual=True) ## uan-phy.h (module 'uan'): void ns3::UanPhyPer::Clear() [member function] cls.add_method('Clear', 'void', [], is_virtual=True) ## uan-phy.h (module 'uan'): static ns3::TypeId ns3::UanPhyPer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-phy.h (module 'uan'): void ns3::UanPhyPer::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3UanPhyPerGenDefault_methods(root_module, cls): ## uan-phy-gen.h (module 'uan'): ns3::UanPhyPerGenDefault::UanPhyPerGenDefault(ns3::UanPhyPerGenDefault const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanPhyPerGenDefault const &', 'arg0')]) ## uan-phy-gen.h (module 'uan'): ns3::UanPhyPerGenDefault::UanPhyPerGenDefault() [constructor] cls.add_constructor([]) ## uan-phy-gen.h (module 'uan'): double ns3::UanPhyPerGenDefault::CalcPer(ns3::Ptr<ns3::Packet> pkt, double sinrDb, ns3::UanTxMode mode) [member function] cls.add_method('CalcPer', 'double', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'sinrDb'), param('ns3::UanTxMode', 'mode')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): static ns3::TypeId ns3::UanPhyPerGenDefault::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3UanPhyPerUmodem_methods(root_module, cls): ## uan-phy-gen.h (module 'uan'): ns3::UanPhyPerUmodem::UanPhyPerUmodem(ns3::UanPhyPerUmodem const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanPhyPerUmodem const &', 'arg0')]) ## uan-phy-gen.h (module 'uan'): ns3::UanPhyPerUmodem::UanPhyPerUmodem() [constructor] cls.add_constructor([]) ## uan-phy-gen.h (module 'uan'): double ns3::UanPhyPerUmodem::CalcPer(ns3::Ptr<ns3::Packet> pkt, double sinrDb, ns3::UanTxMode mode) [member function] cls.add_method('CalcPer', 'double', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'sinrDb'), param('ns3::UanTxMode', 'mode')], is_virtual=True) ## uan-phy-gen.h (module 'uan'): static ns3::TypeId ns3::UanPhyPerUmodem::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3UanPropModel_methods(root_module, cls): ## uan-prop-model.h (module 'uan'): ns3::UanPropModel::UanPropModel() [constructor] cls.add_constructor([]) ## uan-prop-model.h (module 'uan'): ns3::UanPropModel::UanPropModel(ns3::UanPropModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanPropModel const &', 'arg0')]) ## uan-prop-model.h (module 'uan'): void ns3::UanPropModel::Clear() [member function] cls.add_method('Clear', 'void', [], is_virtual=True) ## uan-prop-model.h (module 'uan'): void ns3::UanPropModel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## uan-prop-model.h (module 'uan'): ns3::Time ns3::UanPropModel::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function] cls.add_method('GetDelay', 'ns3::Time', [param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')], is_pure_virtual=True, is_virtual=True) ## uan-prop-model.h (module 'uan'): double ns3::UanPropModel::GetPathLossDb(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode txMode) [member function] cls.add_method('GetPathLossDb', 'double', [param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'txMode')], is_pure_virtual=True, is_virtual=True) ## uan-prop-model.h (module 'uan'): ns3::UanPdp ns3::UanPropModel::GetPdp(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function] cls.add_method('GetPdp', 'ns3::UanPdp', [param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')], is_pure_virtual=True, is_virtual=True) ## uan-prop-model.h (module 'uan'): static ns3::TypeId ns3::UanPropModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3UanPropModelIdeal_methods(root_module, cls): ## uan-prop-model-ideal.h (module 'uan'): ns3::UanPropModelIdeal::UanPropModelIdeal(ns3::UanPropModelIdeal const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanPropModelIdeal const &', 'arg0')]) ## uan-prop-model-ideal.h (module 'uan'): ns3::UanPropModelIdeal::UanPropModelIdeal() [constructor] cls.add_constructor([]) ## uan-prop-model-ideal.h (module 'uan'): ns3::Time ns3::UanPropModelIdeal::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function] cls.add_method('GetDelay', 'ns3::Time', [param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')], is_virtual=True) ## uan-prop-model-ideal.h (module 'uan'): double ns3::UanPropModelIdeal::GetPathLossDb(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function] cls.add_method('GetPathLossDb', 'double', [param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')], is_virtual=True) ## uan-prop-model-ideal.h (module 'uan'): ns3::UanPdp ns3::UanPropModelIdeal::GetPdp(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function] cls.add_method('GetPdp', 'ns3::UanPdp', [param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')], is_virtual=True) ## uan-prop-model-ideal.h (module 'uan'): static ns3::TypeId ns3::UanPropModelIdeal::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3UanPropModelThorp_methods(root_module, cls): ## uan-prop-model-thorp.h (module 'uan'): ns3::UanPropModelThorp::UanPropModelThorp(ns3::UanPropModelThorp const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanPropModelThorp const &', 'arg0')]) ## uan-prop-model-thorp.h (module 'uan'): ns3::UanPropModelThorp::UanPropModelThorp() [constructor] cls.add_constructor([]) ## uan-prop-model-thorp.h (module 'uan'): ns3::Time ns3::UanPropModelThorp::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function] cls.add_method('GetDelay', 'ns3::Time', [param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')], is_virtual=True) ## uan-prop-model-thorp.h (module 'uan'): double ns3::UanPropModelThorp::GetPathLossDb(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function] cls.add_method('GetPathLossDb', 'double', [param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')], is_virtual=True) ## uan-prop-model-thorp.h (module 'uan'): ns3::UanPdp ns3::UanPropModelThorp::GetPdp(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function] cls.add_method('GetPdp', 'ns3::UanPdp', [param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')], is_virtual=True) ## uan-prop-model-thorp.h (module 'uan'): static ns3::TypeId ns3::UanPropModelThorp::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3UanTransducer_methods(root_module, cls): ## uan-transducer.h (module 'uan'): ns3::UanTransducer::UanTransducer() [constructor] cls.add_constructor([]) ## uan-transducer.h (module 'uan'): ns3::UanTransducer::UanTransducer(ns3::UanTransducer const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanTransducer const &', 'arg0')]) ## uan-transducer.h (module 'uan'): void ns3::UanTransducer::AddPhy(ns3::Ptr<ns3::UanPhy> phy) [member function] cls.add_method('AddPhy', 'void', [param('ns3::Ptr< ns3::UanPhy >', 'phy')], is_pure_virtual=True, is_virtual=True) ## uan-transducer.h (module 'uan'): void ns3::UanTransducer::Clear() [member function] cls.add_method('Clear', 'void', [], is_pure_virtual=True, is_virtual=True) ## uan-transducer.h (module 'uan'): std::list<ns3::UanPacketArrival, std::allocator<ns3::UanPacketArrival> > const & ns3::UanTransducer::GetArrivalList() const [member function] cls.add_method('GetArrivalList', 'std::list< ns3::UanPacketArrival > const &', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## uan-transducer.h (module 'uan'): ns3::Ptr<ns3::UanChannel> ns3::UanTransducer::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::UanChannel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## uan-transducer.h (module 'uan'): std::list<ns3::Ptr<ns3::UanPhy>, std::allocator<ns3::Ptr<ns3::UanPhy> > > const & ns3::UanTransducer::GetPhyList() const [member function] cls.add_method('GetPhyList', 'std::list< ns3::Ptr< ns3::UanPhy > > const &', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## uan-transducer.h (module 'uan'): ns3::UanTransducer::State ns3::UanTransducer::GetState() const [member function] cls.add_method('GetState', 'ns3::UanTransducer::State', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## uan-transducer.h (module 'uan'): static ns3::TypeId ns3::UanTransducer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-transducer.h (module 'uan'): bool ns3::UanTransducer::IsRx() const [member function] cls.add_method('IsRx', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## uan-transducer.h (module 'uan'): bool ns3::UanTransducer::IsTx() const [member function] cls.add_method('IsTx', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## uan-transducer.h (module 'uan'): void ns3::UanTransducer::Receive(ns3::Ptr<ns3::Packet> packet, double rxPowerDb, ns3::UanTxMode txMode, ns3::UanPdp pdp) [member function] cls.add_method('Receive', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'rxPowerDb'), param('ns3::UanTxMode', 'txMode'), param('ns3::UanPdp', 'pdp')], is_pure_virtual=True, is_virtual=True) ## uan-transducer.h (module 'uan'): void ns3::UanTransducer::SetChannel(ns3::Ptr<ns3::UanChannel> chan) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::UanChannel >', 'chan')], is_pure_virtual=True, is_virtual=True) ## uan-transducer.h (module 'uan'): void ns3::UanTransducer::Transmit(ns3::Ptr<ns3::UanPhy> src, ns3::Ptr<ns3::Packet> packet, double txPowerDb, ns3::UanTxMode txMode) [member function] cls.add_method('Transmit', 'void', [param('ns3::Ptr< ns3::UanPhy >', 'src'), param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txMode')], is_pure_virtual=True, is_virtual=True) return def register_Ns3UanTransducerHd_methods(root_module, cls): ## uan-transducer-hd.h (module 'uan'): ns3::UanTransducerHd::UanTransducerHd(ns3::UanTransducerHd const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanTransducerHd const &', 'arg0')]) ## uan-transducer-hd.h (module 'uan'): ns3::UanTransducerHd::UanTransducerHd() [constructor] cls.add_constructor([]) ## uan-transducer-hd.h (module 'uan'): void ns3::UanTransducerHd::AddPhy(ns3::Ptr<ns3::UanPhy> arg0) [member function] cls.add_method('AddPhy', 'void', [param('ns3::Ptr< ns3::UanPhy >', 'arg0')], is_virtual=True) ## uan-transducer-hd.h (module 'uan'): void ns3::UanTransducerHd::Clear() [member function] cls.add_method('Clear', 'void', [], is_virtual=True) ## uan-transducer-hd.h (module 'uan'): std::list<ns3::UanPacketArrival, std::allocator<ns3::UanPacketArrival> > const & ns3::UanTransducerHd::GetArrivalList() const [member function] cls.add_method('GetArrivalList', 'std::list< ns3::UanPacketArrival > const &', [], is_const=True, is_virtual=True) ## uan-transducer-hd.h (module 'uan'): ns3::Ptr<ns3::UanChannel> ns3::UanTransducerHd::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::UanChannel >', [], is_const=True, is_virtual=True) ## uan-transducer-hd.h (module 'uan'): std::list<ns3::Ptr<ns3::UanPhy>, std::allocator<ns3::Ptr<ns3::UanPhy> > > const & ns3::UanTransducerHd::GetPhyList() const [member function] cls.add_method('GetPhyList', 'std::list< ns3::Ptr< ns3::UanPhy > > const &', [], is_const=True, is_virtual=True) ## uan-transducer-hd.h (module 'uan'): ns3::UanTransducer::State ns3::UanTransducerHd::GetState() const [member function] cls.add_method('GetState', 'ns3::UanTransducer::State', [], is_const=True, is_virtual=True) ## uan-transducer-hd.h (module 'uan'): static ns3::TypeId ns3::UanTransducerHd::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-transducer-hd.h (module 'uan'): bool ns3::UanTransducerHd::IsRx() const [member function] cls.add_method('IsRx', 'bool', [], is_const=True, is_virtual=True) ## uan-transducer-hd.h (module 'uan'): bool ns3::UanTransducerHd::IsTx() const [member function] cls.add_method('IsTx', 'bool', [], is_const=True, is_virtual=True) ## uan-transducer-hd.h (module 'uan'): void ns3::UanTransducerHd::Receive(ns3::Ptr<ns3::Packet> packet, double rxPowerDb, ns3::UanTxMode txMode, ns3::UanPdp pdp) [member function] cls.add_method('Receive', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'rxPowerDb'), param('ns3::UanTxMode', 'txMode'), param('ns3::UanPdp', 'pdp')], is_virtual=True) ## uan-transducer-hd.h (module 'uan'): void ns3::UanTransducerHd::SetChannel(ns3::Ptr<ns3::UanChannel> chan) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::UanChannel >', 'chan')], is_virtual=True) ## uan-transducer-hd.h (module 'uan'): void ns3::UanTransducerHd::Transmit(ns3::Ptr<ns3::UanPhy> src, ns3::Ptr<ns3::Packet> packet, double txPowerDb, ns3::UanTxMode txMode) [member function] cls.add_method('Transmit', 'void', [param('ns3::Ptr< ns3::UanPhy >', 'src'), param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txMode')], is_virtual=True) ## uan-transducer-hd.h (module 'uan'): void ns3::UanTransducerHd::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', 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_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_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_Ns3BooleanChecker_methods(root_module, cls): ## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker() [constructor] cls.add_constructor([]) ## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker(ns3::BooleanChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::BooleanChecker const &', 'arg0')]) return def register_Ns3BooleanValue_methods(root_module, cls): cls.add_output_stream_operator() ## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(ns3::BooleanValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::BooleanValue const &', 'arg0')]) ## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue() [constructor] cls.add_constructor([]) ## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(bool value) [constructor] cls.add_constructor([param('bool', 'value')]) ## boolean.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::BooleanValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## boolean.h (module 'core'): bool ns3::BooleanValue::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) ## boolean.h (module 'core'): bool ns3::BooleanValue::Get() const [member function] cls.add_method('Get', 'bool', [], is_const=True) ## boolean.h (module 'core'): std::string ns3::BooleanValue::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) ## boolean.h (module 'core'): void ns3::BooleanValue::Set(bool value) [member function] cls.add_method('Set', 'void', [param('bool', 'value')]) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')]) return def register_Ns3CallbackImplBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) ## callback.h (module 'core'): std::string ns3::CallbackImplBase::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_Ns3Channel_methods(root_module, cls): ## channel.h (module 'network'): ns3::Channel::Channel(ns3::Channel const & arg0) [copy constructor] cls.add_constructor([param('ns3::Channel const &', 'arg0')]) ## channel.h (module 'network'): ns3::Channel::Channel() [constructor] cls.add_constructor([]) ## channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Channel::GetDevice(uint32_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): static ns3::TypeId ns3::Channel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_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_Ns3DeviceEnergyModel_methods(root_module, cls): ## device-energy-model.h (module 'energy'): ns3::DeviceEnergyModel::DeviceEnergyModel(ns3::DeviceEnergyModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::DeviceEnergyModel const &', 'arg0')]) ## device-energy-model.h (module 'energy'): ns3::DeviceEnergyModel::DeviceEnergyModel() [constructor] cls.add_constructor([]) ## device-energy-model.h (module 'energy'): void ns3::DeviceEnergyModel::ChangeState(int newState) [member function] cls.add_method('ChangeState', 'void', [param('int', 'newState')], is_pure_virtual=True, is_virtual=True) ## device-energy-model.h (module 'energy'): double ns3::DeviceEnergyModel::GetCurrentA() const [member function] cls.add_method('GetCurrentA', 'double', [], is_const=True) ## device-energy-model.h (module 'energy'): double ns3::DeviceEnergyModel::GetTotalEnergyConsumption() const [member function] cls.add_method('GetTotalEnergyConsumption', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## device-energy-model.h (module 'energy'): static ns3::TypeId ns3::DeviceEnergyModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## device-energy-model.h (module 'energy'): void ns3::DeviceEnergyModel::HandleEnergyDepletion() [member function] cls.add_method('HandleEnergyDepletion', 'void', [], is_pure_virtual=True, is_virtual=True) ## device-energy-model.h (module 'energy'): void ns3::DeviceEnergyModel::HandleEnergyRecharged() [member function] cls.add_method('HandleEnergyRecharged', 'void', [], is_pure_virtual=True, is_virtual=True) ## device-energy-model.h (module 'energy'): void ns3::DeviceEnergyModel::SetEnergySource(ns3::Ptr<ns3::EnergySource> source) [member function] cls.add_method('SetEnergySource', 'void', [param('ns3::Ptr< ns3::EnergySource >', 'source')], is_pure_virtual=True, is_virtual=True) ## device-energy-model.h (module 'energy'): double ns3::DeviceEnergyModel::DoGetCurrentA() const [member function] cls.add_method('DoGetCurrentA', 'double', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3DoubleValue_methods(root_module, cls): ## double.h (module 'core'): ns3::DoubleValue::DoubleValue() [constructor] cls.add_constructor([]) ## double.h (module 'core'): ns3::DoubleValue::DoubleValue(ns3::DoubleValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::DoubleValue const &', 'arg0')]) ## double.h (module 'core'): ns3::DoubleValue::DoubleValue(double const & value) [constructor] cls.add_constructor([param('double const &', 'value')]) ## double.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::DoubleValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## double.h (module 'core'): bool ns3::DoubleValue::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) ## double.h (module 'core'): double ns3::DoubleValue::Get() const [member function] cls.add_method('Get', 'double', [], is_const=True) ## double.h (module 'core'): std::string ns3::DoubleValue::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) ## double.h (module 'core'): void ns3::DoubleValue::Set(double const & value) [member function] cls.add_method('Set', 'void', [param('double const &', 'value')]) 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 c1, double c2, double v1, double v2, double r) [member function] cls.add_method('Interpolate', 'double', [param('double', 'c1'), param('double', 'c2'), param('double', 'v1'), param('double', 'v2'), param('double', 'r')], 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_Ns3EmptyAttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor(ns3::EmptyAttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::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_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object'), param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) return def register_Ns3EmptyAttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker(ns3::EmptyAttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::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_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_const=True, 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_Ns3EnergyHarvester_methods(root_module, cls): ## energy-harvester.h (module 'energy'): ns3::EnergyHarvester::EnergyHarvester(ns3::EnergyHarvester const & arg0) [copy constructor] cls.add_constructor([param('ns3::EnergyHarvester const &', 'arg0')]) ## energy-harvester.h (module 'energy'): ns3::EnergyHarvester::EnergyHarvester() [constructor] cls.add_constructor([]) ## energy-harvester.h (module 'energy'): ns3::Ptr<ns3::EnergySource> ns3::EnergyHarvester::GetEnergySource() const [member function] cls.add_method('GetEnergySource', 'ns3::Ptr< ns3::EnergySource >', [], is_const=True) ## energy-harvester.h (module 'energy'): ns3::Ptr<ns3::Node> ns3::EnergyHarvester::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True) ## energy-harvester.h (module 'energy'): double ns3::EnergyHarvester::GetPower() const [member function] cls.add_method('GetPower', 'double', [], is_const=True) ## energy-harvester.h (module 'energy'): static ns3::TypeId ns3::EnergyHarvester::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## energy-harvester.h (module 'energy'): void ns3::EnergyHarvester::SetEnergySource(ns3::Ptr<ns3::EnergySource> source) [member function] cls.add_method('SetEnergySource', 'void', [param('ns3::Ptr< ns3::EnergySource >', 'source')]) ## energy-harvester.h (module 'energy'): void ns3::EnergyHarvester::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## energy-harvester.h (module 'energy'): void ns3::EnergyHarvester::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## energy-harvester.h (module 'energy'): double ns3::EnergyHarvester::DoGetPower() const [member function] cls.add_method('DoGetPower', 'double', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3EnergySource_methods(root_module, cls): ## energy-source.h (module 'energy'): ns3::EnergySource::EnergySource(ns3::EnergySource const & arg0) [copy constructor] cls.add_constructor([param('ns3::EnergySource const &', 'arg0')]) ## energy-source.h (module 'energy'): ns3::EnergySource::EnergySource() [constructor] cls.add_constructor([]) ## energy-source.h (module 'energy'): void ns3::EnergySource::AppendDeviceEnergyModel(ns3::Ptr<ns3::DeviceEnergyModel> deviceEnergyModelPtr) [member function] cls.add_method('AppendDeviceEnergyModel', 'void', [param('ns3::Ptr< ns3::DeviceEnergyModel >', 'deviceEnergyModelPtr')]) ## energy-source.h (module 'energy'): void ns3::EnergySource::ConnectEnergyHarvester(ns3::Ptr<ns3::EnergyHarvester> energyHarvesterPtr) [member function] cls.add_method('ConnectEnergyHarvester', 'void', [param('ns3::Ptr< ns3::EnergyHarvester >', 'energyHarvesterPtr')]) ## energy-source.h (module 'energy'): void ns3::EnergySource::DisposeDeviceModels() [member function] cls.add_method('DisposeDeviceModels', 'void', []) ## energy-source.h (module 'energy'): ns3::DeviceEnergyModelContainer ns3::EnergySource::FindDeviceEnergyModels(ns3::TypeId tid) [member function] cls.add_method('FindDeviceEnergyModels', 'ns3::DeviceEnergyModelContainer', [param('ns3::TypeId', 'tid')]) ## energy-source.h (module 'energy'): ns3::DeviceEnergyModelContainer ns3::EnergySource::FindDeviceEnergyModels(std::string name) [member function] cls.add_method('FindDeviceEnergyModels', 'ns3::DeviceEnergyModelContainer', [param('std::string', 'name')]) ## energy-source.h (module 'energy'): double ns3::EnergySource::GetEnergyFraction() [member function] cls.add_method('GetEnergyFraction', 'double', [], is_pure_virtual=True, is_virtual=True) ## energy-source.h (module 'energy'): double ns3::EnergySource::GetInitialEnergy() const [member function] cls.add_method('GetInitialEnergy', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## energy-source.h (module 'energy'): ns3::Ptr<ns3::Node> ns3::EnergySource::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True) ## energy-source.h (module 'energy'): double ns3::EnergySource::GetRemainingEnergy() [member function] cls.add_method('GetRemainingEnergy', 'double', [], is_pure_virtual=True, is_virtual=True) ## energy-source.h (module 'energy'): double ns3::EnergySource::GetSupplyVoltage() const [member function] cls.add_method('GetSupplyVoltage', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## energy-source.h (module 'energy'): static ns3::TypeId ns3::EnergySource::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## energy-source.h (module 'energy'): void ns3::EnergySource::InitializeDeviceModels() [member function] cls.add_method('InitializeDeviceModels', 'void', []) ## energy-source.h (module 'energy'): void ns3::EnergySource::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## energy-source.h (module 'energy'): void ns3::EnergySource::UpdateEnergySource() [member function] cls.add_method('UpdateEnergySource', 'void', [], is_pure_virtual=True, is_virtual=True) ## energy-source.h (module 'energy'): void ns3::EnergySource::BreakDeviceEnergyModelRefCycle() [member function] cls.add_method('BreakDeviceEnergyModelRefCycle', 'void', [], visibility='protected') ## energy-source.h (module 'energy'): double ns3::EnergySource::CalculateTotalCurrent() [member function] cls.add_method('CalculateTotalCurrent', 'double', [], visibility='protected') ## energy-source.h (module 'energy'): void ns3::EnergySource::NotifyEnergyDrained() [member function] cls.add_method('NotifyEnergyDrained', 'void', [], visibility='protected') ## energy-source.h (module 'energy'): void ns3::EnergySource::NotifyEnergyRecharged() [member function] cls.add_method('NotifyEnergyRecharged', 'void', [], visibility='protected') ## energy-source.h (module 'energy'): void ns3::EnergySource::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3EnergySourceContainer_methods(root_module, cls): ## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer(ns3::EnergySourceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::EnergySourceContainer const &', 'arg0')]) ## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer() [constructor] cls.add_constructor([]) ## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer(ns3::Ptr<ns3::EnergySource> source) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EnergySource >', 'source')]) ## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer(std::string sourceName) [constructor] cls.add_constructor([param('std::string', 'sourceName')]) ## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer(ns3::EnergySourceContainer const & a, ns3::EnergySourceContainer const & b) [constructor] cls.add_constructor([param('ns3::EnergySourceContainer const &', 'a'), param('ns3::EnergySourceContainer const &', 'b')]) ## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::Add(ns3::EnergySourceContainer container) [member function] cls.add_method('Add', 'void', [param('ns3::EnergySourceContainer', 'container')]) ## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::Add(ns3::Ptr<ns3::EnergySource> source) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::EnergySource >', 'source')]) ## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::Add(std::string sourceName) [member function] cls.add_method('Add', 'void', [param('std::string', 'sourceName')]) ## energy-source-container.h (module 'energy'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::EnergySource>*,std::vector<ns3::Ptr<ns3::EnergySource>, std::allocator<ns3::Ptr<ns3::EnergySource> > > > ns3::EnergySourceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::EnergySource > const, std::vector< ns3::Ptr< ns3::EnergySource > > >', [], is_const=True) ## energy-source-container.h (module 'energy'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::EnergySource>*,std::vector<ns3::Ptr<ns3::EnergySource>, std::allocator<ns3::Ptr<ns3::EnergySource> > > > ns3::EnergySourceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::EnergySource > const, std::vector< ns3::Ptr< ns3::EnergySource > > >', [], is_const=True) ## energy-source-container.h (module 'energy'): ns3::Ptr<ns3::EnergySource> ns3::EnergySourceContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::EnergySource >', [param('uint32_t', 'i')], is_const=True) ## energy-source-container.h (module 'energy'): uint32_t ns3::EnergySourceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## energy-source-container.h (module 'energy'): static ns3::TypeId ns3::EnergySourceContainer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], 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 value, std::string name) [member function] cls.add_method('Add', 'void', [param('int', 'value'), param('std::string', 'name')]) ## enum.h (module 'core'): void ns3::EnumChecker::AddDefault(int value, std::string name) [member function] cls.add_method('AddDefault', 'void', [param('int', 'value'), 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 value) [constructor] cls.add_constructor([param('int', 'value')]) ## 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 value) [member function] cls.add_method('Set', 'void', [param('int', 'value')]) 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_Ns3IntegerValue_methods(root_module, cls): ## integer.h (module 'core'): ns3::IntegerValue::IntegerValue() [constructor] cls.add_constructor([]) ## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(ns3::IntegerValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntegerValue const &', 'arg0')]) ## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(int64_t const & value) [constructor] cls.add_constructor([param('int64_t const &', 'value')]) ## integer.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::IntegerValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## integer.h (module 'core'): bool ns3::IntegerValue::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) ## integer.h (module 'core'): int64_t ns3::IntegerValue::Get() const [member function] cls.add_method('Get', 'int64_t', [], is_const=True) ## integer.h (module 'core'): std::string ns3::IntegerValue::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) ## integer.h (module 'core'): void ns3::IntegerValue::Set(int64_t const & value) [member function] cls.add_method('Set', 'void', [param('int64_t const &', 'value')]) return def register_Ns3Ipv4AddressChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')]) return def register_Ns3Ipv4AddressValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Address const &', 'value')]) return def register_Ns3Ipv4MaskChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')]) return def register_Ns3Ipv4MaskValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Mask const &', 'value')]) return def register_Ns3Ipv6AddressChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')]) return def register_Ns3Ipv6AddressValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Address const &', 'value')]) return def register_Ns3Ipv6PrefixChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')]) return def register_Ns3Ipv6PrefixValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Prefix const &', 'value')]) return def register_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_Ns3MobilityModel_methods(root_module, cls): ## mobility-model.h (module 'mobility'): ns3::MobilityModel::MobilityModel(ns3::MobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::MobilityModel const &', 'arg0')]) ## mobility-model.h (module 'mobility'): ns3::MobilityModel::MobilityModel() [constructor] cls.add_constructor([]) ## mobility-model.h (module 'mobility'): int64_t ns3::MobilityModel::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## mobility-model.h (module 'mobility'): double ns3::MobilityModel::GetDistanceFrom(ns3::Ptr<const ns3::MobilityModel> position) const [member function] cls.add_method('GetDistanceFrom', 'double', [param('ns3::Ptr< ns3::MobilityModel const >', 'position')], is_const=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetPosition() const [member function] cls.add_method('GetPosition', 'ns3::Vector', [], is_const=True) ## mobility-model.h (module 'mobility'): double ns3::MobilityModel::GetRelativeSpeed(ns3::Ptr<const ns3::MobilityModel> other) const [member function] cls.add_method('GetRelativeSpeed', 'double', [param('ns3::Ptr< ns3::MobilityModel const >', 'other')], is_const=True) ## mobility-model.h (module 'mobility'): static ns3::TypeId ns3::MobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetVelocity() const [member function] cls.add_method('GetVelocity', 'ns3::Vector', [], is_const=True) ## mobility-model.h (module 'mobility'): void ns3::MobilityModel::SetPosition(ns3::Vector const & position) [member function] cls.add_method('SetPosition', 'void', [param('ns3::Vector const &', 'position')]) ## mobility-model.h (module 'mobility'): void ns3::MobilityModel::NotifyCourseChange() const [member function] cls.add_method('NotifyCourseChange', 'void', [], is_const=True, visibility='protected') ## mobility-model.h (module 'mobility'): int64_t ns3::MobilityModel::DoAssignStreams(int64_t start) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'start')], visibility='private', is_virtual=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## mobility-model.h (module 'mobility'): void ns3::MobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], is_pure_virtual=True, visibility='private', is_virtual=True) 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<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3NetDeviceQueue_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue(ns3::NetDeviceQueue const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceQueue const &', 'arg0')]) ## net-device.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::Ptr<ns3::QueueLimits> ns3::NetDeviceQueue::GetQueueLimits() [member function] cls.add_method('GetQueueLimits', 'ns3::Ptr< ns3::QueueLimits >', []) ## net-device.h (module 'network'): bool ns3::NetDeviceQueue::IsStopped() const [member function] cls.add_method('IsStopped', 'bool', [], is_const=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::NotifyQueuedBytes(uint32_t bytes) [member function] cls.add_method('NotifyQueuedBytes', 'void', [param('uint32_t', 'bytes')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::NotifyTransmittedBytes(uint32_t bytes) [member function] cls.add_method('NotifyTransmittedBytes', 'void', [param('uint32_t', 'bytes')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::ResetQueueLimits() [member function] cls.add_method('ResetQueueLimits', 'void', []) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::SetQueueLimits(ns3::Ptr<ns3::QueueLimits> ql) [member function] cls.add_method('SetQueueLimits', 'void', [param('ns3::Ptr< ns3::QueueLimits >', 'ql')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::SetWakeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetWakeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Start() [member function] cls.add_method('Start', 'void', [], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Stop() [member function] cls.add_method('Stop', 'void', [], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Wake() [member function] cls.add_method('Wake', 'void', [], is_virtual=True) return def register_Ns3NetDeviceQueueInterface_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface(ns3::NetDeviceQueueInterface const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceQueueInterface const &', 'arg0')]) ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::CreateTxQueues() [member function] cls.add_method('CreateTxQueues', 'void', []) ## net-device.h (module 'network'): uint8_t ns3::NetDeviceQueueInterface::GetNTxQueues() const [member function] cls.add_method('GetNTxQueues', 'uint8_t', [], is_const=True) ## net-device.h (module 'network'): ns3::Callback<unsigned char, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::NetDeviceQueueInterface::GetSelectQueueCallback() const [member function] cls.add_method('GetSelectQueueCallback', 'ns3::Callback< unsigned char, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::NetDeviceQueue> ns3::NetDeviceQueueInterface::GetTxQueue(uint8_t i) const [member function] cls.add_method('GetTxQueue', 'ns3::Ptr< ns3::NetDeviceQueue >', [param('uint8_t', 'i')], is_const=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDeviceQueueInterface::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::SetSelectQueueCallback(ns3::Callback<unsigned char, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetSelectQueueCallback', 'void', [param('ns3::Callback< unsigned char, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::SetTxQueuesN(uint8_t numTxQueues) [member function] cls.add_method('SetTxQueuesN', 'void', [param('uint8_t', 'numTxQueues')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', 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'): ns3::Time ns3::Node::GetLocalTime() const [member function] cls.add_method('GetLocalTime', 'ns3::Time', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('RegisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('UnregisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_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_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor] cls.add_constructor([param('ns3::Packet const &', 'o')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] cls.add_constructor([param('uint32_t', 'size')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] cls.add_method('AddByteTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header')]) ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] cls.add_method('AddPacketTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer')]) ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] cls.add_method('EnablePrinting', 'void', [], is_static=True) ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] cls.add_method('FindFirstMatchingByteTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] cls.add_method('GetByteTagIterator', 'ns3::ByteTagIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function] cls.add_method('GetNixVector', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] cls.add_method('GetPacketTagIterator', 'ns3::PacketTagIterator', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function] cls.add_method('ReplacePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> nixVector) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'nixVector')]) ## packet.h (module 'network'): std::string ns3::Packet::ToString() const [member function] cls.add_method('ToString', 'std::string', [], is_const=True) return def register_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_Ns3PointerChecker_methods(root_module, cls): ## pointer.h (module 'core'): ns3::PointerChecker::PointerChecker() [constructor] cls.add_constructor([]) ## pointer.h (module 'core'): ns3::PointerChecker::PointerChecker(ns3::PointerChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::PointerChecker const &', 'arg0')]) ## pointer.h (module 'core'): ns3::TypeId ns3::PointerChecker::GetPointeeTypeId() const [member function] cls.add_method('GetPointeeTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3PointerValue_methods(root_module, cls): ## pointer.h (module 'core'): ns3::PointerValue::PointerValue(ns3::PointerValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::PointerValue const &', 'arg0')]) ## pointer.h (module 'core'): ns3::PointerValue::PointerValue() [constructor] cls.add_constructor([]) ## pointer.h (module 'core'): ns3::PointerValue::PointerValue(ns3::Ptr<ns3::Object> object) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Object >', 'object')]) ## pointer.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::PointerValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## pointer.h (module 'core'): bool ns3::PointerValue::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) ## pointer.h (module 'core'): ns3::Ptr<ns3::Object> ns3::PointerValue::GetObject() const [member function] cls.add_method('GetObject', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## pointer.h (module 'core'): std::string ns3::PointerValue::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) ## pointer.h (module 'core'): void ns3::PointerValue::SetObject(ns3::Ptr<ns3::Object> object) [member function] cls.add_method('SetObject', 'void', [param('ns3::Ptr< ns3::Object >', 'object')]) return def register_Ns3QueueItem_methods(root_module, cls): cls.add_output_stream_operator() ## net-device.h (module 'network'): ns3::QueueItem::QueueItem(ns3::Ptr<ns3::Packet> p) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Packet >', 'p')]) ## net-device.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::QueueItem::GetPacket() const [member function] cls.add_method('GetPacket', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## net-device.h (module 'network'): uint32_t ns3::QueueItem::GetPacketSize() const [member function] cls.add_method('GetPacketSize', 'uint32_t', [], is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::QueueItem::GetUint8Value(ns3::QueueItem::Uint8Values field, uint8_t & value) const [member function] cls.add_method('GetUint8Value', 'bool', [param('ns3::QueueItem::Uint8Values', 'field'), param('uint8_t &', 'value')], is_const=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::QueueItem::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) return def register_Ns3TimeValue_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor] cls.add_constructor([param('ns3::Time const &', 'value')]) ## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function] cls.add_method('Get', 'ns3::Time', [], is_const=True) ## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Time const &', 'value')]) return def register_Ns3TypeIdChecker_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')]) return def register_Ns3TypeIdValue_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function] cls.add_method('Get', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function] cls.add_method('Set', 'void', [param('ns3::TypeId const &', 'value')]) return def register_Ns3UanChannel_methods(root_module, cls): ## uan-channel.h (module 'uan'): ns3::UanChannel::UanChannel(ns3::UanChannel const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanChannel const &', 'arg0')]) ## uan-channel.h (module 'uan'): ns3::UanChannel::UanChannel() [constructor] cls.add_constructor([]) ## uan-channel.h (module 'uan'): void ns3::UanChannel::AddDevice(ns3::Ptr<ns3::UanNetDevice> dev, ns3::Ptr<ns3::UanTransducer> trans) [member function] cls.add_method('AddDevice', 'void', [param('ns3::Ptr< ns3::UanNetDevice >', 'dev'), param('ns3::Ptr< ns3::UanTransducer >', 'trans')]) ## uan-channel.h (module 'uan'): void ns3::UanChannel::Clear() [member function] cls.add_method('Clear', 'void', []) ## uan-channel.h (module 'uan'): ns3::Ptr<ns3::NetDevice> ns3::UanChannel::GetDevice(uint32_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## uan-channel.h (module 'uan'): uint32_t ns3::UanChannel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True, is_virtual=True) ## uan-channel.h (module 'uan'): double ns3::UanChannel::GetNoiseDbHz(double fKhz) [member function] cls.add_method('GetNoiseDbHz', 'double', [param('double', 'fKhz')]) ## uan-channel.h (module 'uan'): static ns3::TypeId ns3::UanChannel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-channel.h (module 'uan'): void ns3::UanChannel::SetNoiseModel(ns3::Ptr<ns3::UanNoiseModel> noise) [member function] cls.add_method('SetNoiseModel', 'void', [param('ns3::Ptr< ns3::UanNoiseModel >', 'noise')]) ## uan-channel.h (module 'uan'): void ns3::UanChannel::SetPropagationModel(ns3::Ptr<ns3::UanPropModel> prop) [member function] cls.add_method('SetPropagationModel', 'void', [param('ns3::Ptr< ns3::UanPropModel >', 'prop')]) ## uan-channel.h (module 'uan'): void ns3::UanChannel::TxPacket(ns3::Ptr<ns3::UanTransducer> src, ns3::Ptr<ns3::Packet> packet, double txPowerDb, ns3::UanTxMode txmode) [member function] cls.add_method('TxPacket', 'void', [param('ns3::Ptr< ns3::UanTransducer >', 'src'), param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txmode')]) ## uan-channel.h (module 'uan'): void ns3::UanChannel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3UanModesListChecker_methods(root_module, cls): ## uan-tx-mode.h (module 'uan'): ns3::UanModesListChecker::UanModesListChecker() [constructor] cls.add_constructor([]) ## uan-tx-mode.h (module 'uan'): ns3::UanModesListChecker::UanModesListChecker(ns3::UanModesListChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanModesListChecker const &', 'arg0')]) return def register_Ns3UanModesListValue_methods(root_module, cls): ## uan-tx-mode.h (module 'uan'): ns3::UanModesListValue::UanModesListValue() [constructor] cls.add_constructor([]) ## uan-tx-mode.h (module 'uan'): ns3::UanModesListValue::UanModesListValue(ns3::UanModesListValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanModesListValue const &', 'arg0')]) ## uan-tx-mode.h (module 'uan'): ns3::UanModesListValue::UanModesListValue(ns3::UanModesList const & value) [constructor] cls.add_constructor([param('ns3::UanModesList const &', 'value')]) ## uan-tx-mode.h (module 'uan'): ns3::Ptr<ns3::AttributeValue> ns3::UanModesListValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## uan-tx-mode.h (module 'uan'): bool ns3::UanModesListValue::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) ## uan-tx-mode.h (module 'uan'): ns3::UanModesList ns3::UanModesListValue::Get() const [member function] cls.add_method('Get', 'ns3::UanModesList', [], is_const=True) ## uan-tx-mode.h (module 'uan'): std::string ns3::UanModesListValue::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) ## uan-tx-mode.h (module 'uan'): void ns3::UanModesListValue::Set(ns3::UanModesList const & value) [member function] cls.add_method('Set', 'void', [param('ns3::UanModesList const &', 'value')]) return def register_Ns3UanNetDevice_methods(root_module, cls): ## uan-net-device.h (module 'uan'): ns3::UanNetDevice::UanNetDevice(ns3::UanNetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::UanNetDevice const &', 'arg0')]) ## uan-net-device.h (module 'uan'): ns3::UanNetDevice::UanNetDevice() [constructor] cls.add_constructor([]) ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_virtual=True) ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::Clear() [member function] cls.add_method('Clear', 'void', []) ## uan-net-device.h (module 'uan'): ns3::Address ns3::UanNetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True, is_virtual=True) ## uan-net-device.h (module 'uan'): ns3::Address ns3::UanNetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## uan-net-device.h (module 'uan'): ns3::Ptr<ns3::Channel> ns3::UanNetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_const=True, is_virtual=True) ## uan-net-device.h (module 'uan'): uint32_t ns3::UanNetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_const=True, is_virtual=True) ## uan-net-device.h (module 'uan'): ns3::Ptr<ns3::UanMac> ns3::UanNetDevice::GetMac() const [member function] cls.add_method('GetMac', 'ns3::Ptr< ns3::UanMac >', [], is_const=True) ## uan-net-device.h (module 'uan'): uint16_t ns3::UanNetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_const=True, is_virtual=True) ## uan-net-device.h (module 'uan'): ns3::Address ns3::UanNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_const=True, is_virtual=True) ## uan-net-device.h (module 'uan'): ns3::Address ns3::UanNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_const=True, is_virtual=True) ## uan-net-device.h (module 'uan'): ns3::Ptr<ns3::Node> ns3::UanNetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## uan-net-device.h (module 'uan'): ns3::Ptr<ns3::UanPhy> ns3::UanNetDevice::GetPhy() const [member function] cls.add_method('GetPhy', 'ns3::Ptr< ns3::UanPhy >', [], is_const=True) ## uan-net-device.h (module 'uan'): ns3::Ptr<ns3::UanTransducer> ns3::UanNetDevice::GetTransducer() const [member function] cls.add_method('GetTransducer', 'ns3::Ptr< ns3::UanTransducer >', [], is_const=True) ## uan-net-device.h (module 'uan'): static ns3::TypeId ns3::UanNetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_const=True, is_virtual=True) ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True, is_virtual=True) ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_const=True, is_virtual=True) ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True, is_virtual=True) ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_const=True, is_virtual=True) ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_const=True, is_virtual=True) ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_virtual=True) ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_virtual=True) ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_virtual=True) ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetChannel(ns3::Ptr<ns3::UanChannel> channel) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::UanChannel >', 'channel')]) ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_virtual=True) ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetMac(ns3::Ptr<ns3::UanMac> mac) [member function] cls.add_method('SetMac', 'void', [param('ns3::Ptr< ns3::UanMac >', 'mac')]) ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_virtual=True) ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_virtual=True) ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetPhy(ns3::Ptr<ns3::UanPhy> phy) [member function] cls.add_method('SetPhy', 'void', [param('ns3::Ptr< ns3::UanPhy >', 'phy')]) ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::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_virtual=True) ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetSleepMode(bool sleep) [member function] cls.add_method('SetSleepMode', 'void', [param('bool', 'sleep')]) ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetTransducer(ns3::Ptr<ns3::UanTransducer> trans) [member function] cls.add_method('SetTransducer', 'void', [param('ns3::Ptr< ns3::UanTransducer >', 'trans')]) ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::ForwardUp(ns3::Ptr<ns3::Packet> pkt, ns3::UanAddress const & src) [member function] cls.add_method('ForwardUp', 'void', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::UanAddress const &', 'src')], visibility='private', 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_Ns3Vector2DChecker_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker(ns3::Vector2DChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector2DChecker const &', 'arg0')]) return def register_Ns3Vector2DValue_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2DValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector2DValue const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2D const & value) [constructor] cls.add_constructor([param('ns3::Vector2D const &', 'value')]) ## vector.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::Vector2DValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## vector.h (module 'core'): bool ns3::Vector2DValue::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) ## vector.h (module 'core'): ns3::Vector2D ns3::Vector2DValue::Get() const [member function] cls.add_method('Get', 'ns3::Vector2D', [], is_const=True) ## vector.h (module 'core'): std::string ns3::Vector2DValue::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) ## vector.h (module 'core'): void ns3::Vector2DValue::Set(ns3::Vector2D const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Vector2D const &', 'value')]) return def register_Ns3Vector3DChecker_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker(ns3::Vector3DChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector3DChecker const &', 'arg0')]) return def register_Ns3Vector3DValue_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3DValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector3DValue const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3D const & value) [constructor] cls.add_constructor([param('ns3::Vector3D const &', 'value')]) ## vector.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::Vector3DValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## vector.h (module 'core'): bool ns3::Vector3DValue::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) ## vector.h (module 'core'): ns3::Vector3D ns3::Vector3DValue::Get() const [member function] cls.add_method('Get', 'ns3::Vector3D', [], is_const=True) ## vector.h (module 'core'): std::string ns3::Vector3DValue::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) ## vector.h (module 'core'): void ns3::Vector3DValue::Set(ns3::Vector3D const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Vector3D const &', 'value')]) return def register_Ns3AcousticModemEnergyModel_methods(root_module, cls): ## acoustic-modem-energy-model.h (module 'uan'): ns3::AcousticModemEnergyModel::AcousticModemEnergyModel(ns3::AcousticModemEnergyModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::AcousticModemEnergyModel const &', 'arg0')]) ## acoustic-modem-energy-model.h (module 'uan'): ns3::AcousticModemEnergyModel::AcousticModemEnergyModel() [constructor] cls.add_constructor([]) ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::ChangeState(int newState) [member function] cls.add_method('ChangeState', 'void', [param('int', 'newState')], is_virtual=True) ## acoustic-modem-energy-model.h (module 'uan'): int ns3::AcousticModemEnergyModel::GetCurrentState() const [member function] cls.add_method('GetCurrentState', 'int', [], is_const=True) ## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetIdlePowerW() const [member function] cls.add_method('GetIdlePowerW', 'double', [], is_const=True) ## acoustic-modem-energy-model.h (module 'uan'): ns3::Ptr<ns3::Node> ns3::AcousticModemEnergyModel::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetRxPowerW() const [member function] cls.add_method('GetRxPowerW', 'double', [], is_const=True) ## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetSleepPowerW() const [member function] cls.add_method('GetSleepPowerW', 'double', [], is_const=True) ## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetTotalEnergyConsumption() const [member function] cls.add_method('GetTotalEnergyConsumption', 'double', [], is_const=True, is_virtual=True) ## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetTxPowerW() const [member function] cls.add_method('GetTxPowerW', 'double', [], is_const=True) ## acoustic-modem-energy-model.h (module 'uan'): static ns3::TypeId ns3::AcousticModemEnergyModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::HandleEnergyDepletion() [member function] cls.add_method('HandleEnergyDepletion', 'void', [], is_virtual=True) ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::HandleEnergyRecharged() [member function] cls.add_method('HandleEnergyRecharged', 'void', [], is_virtual=True) ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetEnergyDepletionCallback(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('SetEnergyDepletionCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetEnergyRechargeCallback(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('SetEnergyRechargeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetEnergySource(ns3::Ptr<ns3::EnergySource> source) [member function] cls.add_method('SetEnergySource', 'void', [param('ns3::Ptr< ns3::EnergySource >', 'source')], is_virtual=True) ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetIdlePowerW(double idlePowerW) [member function] cls.add_method('SetIdlePowerW', 'void', [param('double', 'idlePowerW')]) ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_virtual=True) ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetRxPowerW(double rxPowerW) [member function] cls.add_method('SetRxPowerW', 'void', [param('double', 'rxPowerW')]) ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetSleepPowerW(double sleepPowerW) [member function] cls.add_method('SetSleepPowerW', 'void', [param('double', 'sleepPowerW')]) ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetTxPowerW(double txPowerW) [member function] cls.add_method('SetTxPowerW', 'void', [param('double', 'txPowerW')]) ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::DoGetCurrentA() const [member function] cls.add_method('DoGetCurrentA', 'double', [], is_const=True, visibility='private', is_virtual=True) 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_Ns3HashImplementation_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Implementation const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation() [constructor] cls.add_constructor([]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Implementation::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_pure_virtual=True, is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Implementation::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Implementation::clear() [member function] cls.add_method('clear', 'void', [], is_pure_virtual=True, is_virtual=True) return def register_Ns3HashFunctionFnv1a_methods(root_module, cls): ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a(ns3::Hash::Function::Fnv1a const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')]) ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a() [constructor] cls.add_constructor([]) ## hash-fnv.h (module 'core'): uint32_t ns3::Hash::Function::Fnv1a::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): uint64_t ns3::Hash::Function::Fnv1a::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): void ns3::Hash::Function::Fnv1a::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash32_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Function::Hash32 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash32 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Hash32Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash32Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash32::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash32::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash64_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Function::Hash64 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash64 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Hash64Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash64Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash64::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash64::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionMurmur3_methods(root_module, cls): ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3(ns3::Hash::Function::Murmur3 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')]) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor] cls.add_constructor([]) ## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_functions(root_module): module = root_module ## uan-tx-mode.h (module 'uan'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeUanModesListChecker() [free function] module.add_function('MakeUanModesListChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_Hash(module.get_submodule('Hash'), root_module) register_functions_ns3_TracedValueCallback(module.get_submodule('TracedValueCallback'), root_module) register_functions_ns3_internal(module.get_submodule('internal'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_Hash(module, root_module): register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module) return def register_functions_ns3_Hash_Function(module, root_module): return def register_functions_ns3_TracedValueCallback(module, root_module): return def 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-3.0
Plain-Andy-legacy/android_external_chromium_org
native_client_sdk/src/build_tools/sdk_tools/command/info.py
160
1162
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import command_common import logging import manifest_util def Info(manifest, bundle_names): valid_bundles, invalid_bundles = command_common.GetValidBundles(manifest, bundle_names) if invalid_bundles: logging.warn('Unknown bundle(s): %s\n' % (', '.join(invalid_bundles))) if not valid_bundles: logging.warn('No valid bundles given.') return for bundle_name in valid_bundles: bundle = manifest.GetBundle(bundle_name) print bundle.name for key in sorted(bundle.iterkeys()): value = bundle[key] if key == manifest_util.ARCHIVES_KEY: for archive in bundle.GetArchives(): print ' Archive:' if archive: for archive_key in sorted(archive.iterkeys()): print ' %s: %s' % (archive_key, archive[archive_key]) elif key not in (manifest_util.ARCHIVES_KEY, manifest_util.NAME_KEY): print ' %s: %s' % (key, value) print
bsd-3-clause
fw1121/luigi
sitecustomize.py
56
1375
import os import sys def patch_process_for_coverage(): # patch multiprocessing module to get coverage # https://bitbucket.org/ned/coveragepy/issue/117/enable-coverage-measurement-of-code-run-by from coverage.collector import Collector from coverage import coverage import multiprocessing # detect if coverage was running in forked process if sys.version_info >= (3, 4): klass = multiprocessing.process.BaseProcess else: klass = multiprocessing.Process if Collector._collectors: original = multiprocessing.Process._bootstrap class ProcessWithCoverage(multiprocessing.Process): def _bootstrap(self): cov = coverage( data_suffix=True, config_file=os.getenv('COVERAGE_PROCESS_START', True) ) cov.start() try: return original(self) finally: cov.stop() cov.save() if sys.version_info >= (3, 4): klass._bootstrap = ProcessWithCoverage._bootstrap else: multiprocessing.Process = ProcessWithCoverage if os.getenv('FULL_COVERAGE', 'false') == 'true': try: import coverage coverage.process_startup() patch_process_for_coverage() except ImportError: pass
apache-2.0
fernandog/Sick-Beard
lib/unidecode/x004.py
249
4071
data = ( 'Ie', # 0x00 'Io', # 0x01 'Dj', # 0x02 'Gj', # 0x03 'Ie', # 0x04 'Dz', # 0x05 'I', # 0x06 'Yi', # 0x07 'J', # 0x08 'Lj', # 0x09 'Nj', # 0x0a 'Tsh', # 0x0b 'Kj', # 0x0c 'I', # 0x0d 'U', # 0x0e 'Dzh', # 0x0f 'A', # 0x10 'B', # 0x11 'V', # 0x12 'G', # 0x13 'D', # 0x14 'E', # 0x15 'Zh', # 0x16 'Z', # 0x17 'I', # 0x18 'I', # 0x19 'K', # 0x1a 'L', # 0x1b 'M', # 0x1c 'N', # 0x1d 'O', # 0x1e 'P', # 0x1f 'R', # 0x20 'S', # 0x21 'T', # 0x22 'U', # 0x23 'F', # 0x24 'Kh', # 0x25 'Ts', # 0x26 'Ch', # 0x27 'Sh', # 0x28 'Shch', # 0x29 '\'', # 0x2a 'Y', # 0x2b '\'', # 0x2c 'E', # 0x2d 'Iu', # 0x2e 'Ia', # 0x2f 'a', # 0x30 'b', # 0x31 'v', # 0x32 'g', # 0x33 'd', # 0x34 'e', # 0x35 'zh', # 0x36 'z', # 0x37 'i', # 0x38 'i', # 0x39 'k', # 0x3a 'l', # 0x3b 'm', # 0x3c 'n', # 0x3d 'o', # 0x3e 'p', # 0x3f 'r', # 0x40 's', # 0x41 't', # 0x42 'u', # 0x43 'f', # 0x44 'kh', # 0x45 'ts', # 0x46 'ch', # 0x47 'sh', # 0x48 'shch', # 0x49 '\'', # 0x4a 'y', # 0x4b '\'', # 0x4c 'e', # 0x4d 'iu', # 0x4e 'ia', # 0x4f 'ie', # 0x50 'io', # 0x51 'dj', # 0x52 'gj', # 0x53 'ie', # 0x54 'dz', # 0x55 'i', # 0x56 'yi', # 0x57 'j', # 0x58 'lj', # 0x59 'nj', # 0x5a 'tsh', # 0x5b 'kj', # 0x5c 'i', # 0x5d 'u', # 0x5e 'dzh', # 0x5f 'O', # 0x60 'o', # 0x61 'E', # 0x62 'e', # 0x63 'Ie', # 0x64 'ie', # 0x65 'E', # 0x66 'e', # 0x67 'Ie', # 0x68 'ie', # 0x69 'O', # 0x6a 'o', # 0x6b 'Io', # 0x6c 'io', # 0x6d 'Ks', # 0x6e 'ks', # 0x6f 'Ps', # 0x70 'ps', # 0x71 'F', # 0x72 'f', # 0x73 'Y', # 0x74 'y', # 0x75 'Y', # 0x76 'y', # 0x77 'u', # 0x78 'u', # 0x79 'O', # 0x7a 'o', # 0x7b 'O', # 0x7c 'o', # 0x7d 'Ot', # 0x7e 'ot', # 0x7f 'Q', # 0x80 'q', # 0x81 '*1000*', # 0x82 '', # 0x83 '', # 0x84 '', # 0x85 '', # 0x86 '[?]', # 0x87 '*100.000*', # 0x88 '*1.000.000*', # 0x89 '[?]', # 0x8a '[?]', # 0x8b '"', # 0x8c '"', # 0x8d 'R\'', # 0x8e 'r\'', # 0x8f 'G\'', # 0x90 'g\'', # 0x91 'G\'', # 0x92 'g\'', # 0x93 'G\'', # 0x94 'g\'', # 0x95 'Zh\'', # 0x96 'zh\'', # 0x97 'Z\'', # 0x98 'z\'', # 0x99 'K\'', # 0x9a 'k\'', # 0x9b 'K\'', # 0x9c 'k\'', # 0x9d 'K\'', # 0x9e 'k\'', # 0x9f 'K\'', # 0xa0 'k\'', # 0xa1 'N\'', # 0xa2 'n\'', # 0xa3 'Ng', # 0xa4 'ng', # 0xa5 'P\'', # 0xa6 'p\'', # 0xa7 'Kh', # 0xa8 'kh', # 0xa9 'S\'', # 0xaa 's\'', # 0xab 'T\'', # 0xac 't\'', # 0xad 'U', # 0xae 'u', # 0xaf 'U\'', # 0xb0 'u\'', # 0xb1 'Kh\'', # 0xb2 'kh\'', # 0xb3 'Tts', # 0xb4 'tts', # 0xb5 'Ch\'', # 0xb6 'ch\'', # 0xb7 'Ch\'', # 0xb8 'ch\'', # 0xb9 'H', # 0xba 'h', # 0xbb 'Ch', # 0xbc 'ch', # 0xbd 'Ch\'', # 0xbe 'ch\'', # 0xbf '`', # 0xc0 'Zh', # 0xc1 'zh', # 0xc2 'K\'', # 0xc3 'k\'', # 0xc4 '[?]', # 0xc5 '[?]', # 0xc6 'N\'', # 0xc7 'n\'', # 0xc8 '[?]', # 0xc9 '[?]', # 0xca 'Ch', # 0xcb 'ch', # 0xcc '[?]', # 0xcd '[?]', # 0xce '[?]', # 0xcf 'a', # 0xd0 'a', # 0xd1 'A', # 0xd2 'a', # 0xd3 'Ae', # 0xd4 'ae', # 0xd5 'Ie', # 0xd6 'ie', # 0xd7 '@', # 0xd8 '@', # 0xd9 '@', # 0xda '@', # 0xdb 'Zh', # 0xdc 'zh', # 0xdd 'Z', # 0xde 'z', # 0xdf 'Dz', # 0xe0 'dz', # 0xe1 'I', # 0xe2 'i', # 0xe3 'I', # 0xe4 'i', # 0xe5 'O', # 0xe6 'o', # 0xe7 'O', # 0xe8 'o', # 0xe9 'O', # 0xea 'o', # 0xeb 'E', # 0xec 'e', # 0xed 'U', # 0xee 'u', # 0xef 'U', # 0xf0 'u', # 0xf1 'U', # 0xf2 'u', # 0xf3 'Ch', # 0xf4 'ch', # 0xf5 '[?]', # 0xf6 '[?]', # 0xf7 'Y', # 0xf8 'y', # 0xf9 '[?]', # 0xfa '[?]', # 0xfb '[?]', # 0xfc '[?]', # 0xfd '[?]', # 0xfe )
gpl-3.0
SpaceKatt/CSPLN
apps/scaffolding/mac/web2py/web2py.app/Contents/Resources/gluon/tests/test_tools.py
13
2558
#!/bin/python # -*- coding: utf-8 -*- """ Unit tests for gluon.tools """ import os import sys if sys.version < "2.7": import unittest2 as unittest else: import unittest from fix_path import fix_sys_path fix_sys_path(__file__) DEFAULT_URI = os.getenv('DB', 'sqlite:memory') from gluon.dal import DAL, Field from pydal.objects import Table from tools import Auth from gluon.globals import Request, Response, Session from storage import Storage from languages import translator from gluon.http import HTTP python_version = sys.version[:3] IS_IMAP = "imap" in DEFAULT_URI @unittest.skipIf(IS_IMAP, "TODO: Imap raises 'Connection refused'") class testAuth(unittest.TestCase): def testRun(self): # setup request = Request(env={}) request.application = 'a' request.controller = 'c' request.function = 'f' request.folder = 'applications/admin' response = Response() session = Session() T = translator('', 'en') session.connect(request, response) from gluon.globals import current current.request = request current.response = response current.session = session current.T = T db = DAL(DEFAULT_URI, check_reserved=['all']) auth = Auth(db) auth.define_tables(username=True, signature=False) self.assertTrue('auth_user' in db) self.assertTrue('auth_group' in db) self.assertTrue('auth_membership' in db) self.assertTrue('auth_permission' in db) self.assertTrue('auth_event' in db) db.define_table('t0', Field('tt'), auth.signature) auth.enable_record_versioning(db) self.assertTrue('t0_archive' in db) for f in ['login', 'register', 'retrieve_password', 'retrieve_username']: html_form = getattr(auth, f)().xml() self.assertTrue('name="_formkey"' in html_form) for f in ['logout', 'verify_email', 'reset_password', 'change_password', 'profile', 'groups']: self.assertRaisesRegexp(HTTP, "303*", getattr(auth, f)) self.assertRaisesRegexp(HTTP, "401*", auth.impersonate) try: for t in ['t0_archive', 't0', 'auth_cas', 'auth_event', 'auth_membership', 'auth_permission', 'auth_group', 'auth_user']: db[t].drop() except SyntaxError as e: # GAE doesn't support drop pass return if __name__ == '__main__': unittest.main()
gpl-3.0
MichaelAquilina/restructured-preview
lib/pygments/lexers/make.py
72
7247
# -*- coding: utf-8 -*- """ pygments.lexers.make ~~~~~~~~~~~~~~~~~~~~ Lexers for Makefiles and similar. :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import Lexer, RegexLexer, include, bygroups, \ do_insertions, using from pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Punctuation from pygments.lexers.shell import BashLexer __all__ = ['MakefileLexer', 'BaseMakefileLexer', 'CMakeLexer'] class MakefileLexer(Lexer): """ Lexer for BSD and GNU make extensions (lenient enough to handle both in the same file even). *Rewritten in Pygments 0.10.* """ name = 'Makefile' aliases = ['make', 'makefile', 'mf', 'bsdmake'] filenames = ['*.mak', '*.mk', 'Makefile', 'makefile', 'Makefile.*', 'GNUmakefile'] mimetypes = ['text/x-makefile'] r_special = re.compile( r'^(?:' # BSD Make r'\.\s*(include|undef|error|warning|if|else|elif|endif|for|endfor)|' # GNU Make r'\s*(ifeq|ifneq|ifdef|ifndef|else|endif|-?include|define|endef|:|vpath)|' # GNU Automake r'\s*(if|else|endif))(?=\s)') r_comment = re.compile(r'^\s*@?#') def get_tokens_unprocessed(self, text): ins = [] lines = text.splitlines(True) done = '' lex = BaseMakefileLexer(**self.options) backslashflag = False for line in lines: if self.r_special.match(line) or backslashflag: ins.append((len(done), [(0, Comment.Preproc, line)])) backslashflag = line.strip().endswith('\\') elif self.r_comment.match(line): ins.append((len(done), [(0, Comment, line)])) else: done += line for item in do_insertions(ins, lex.get_tokens_unprocessed(done)): yield item def analyse_text(text): # Many makefiles have $(BIG_CAPS) style variables if re.search(r'\$\([A-Z_]+\)', text): return 0.1 class BaseMakefileLexer(RegexLexer): """ Lexer for simple Makefiles (no preprocessing). .. versionadded:: 0.10 """ name = 'Base Makefile' aliases = ['basemake'] filenames = [] mimetypes = [] tokens = { 'root': [ # recipes (need to allow spaces because of expandtabs) (r'^(?:[\t ]+.*\n|\n)+', using(BashLexer)), # special variables (r'\$[<@$+%?|*]', Keyword), (r'\s+', Text), (r'#.*?\n', Comment), (r'(export)(\s+)(?=[\w${}\t -]+\n)', bygroups(Keyword, Text), 'export'), (r'export\s+', Keyword), # assignment (r'([\w${}.-]+)(\s*)([!?:+]?=)([ \t]*)((?:.*\\\n)+|.*\n)', bygroups(Name.Variable, Text, Operator, Text, using(BashLexer))), # strings (r'(?s)"(\\\\|\\.|[^"\\])*"', String.Double), (r"(?s)'(\\\\|\\.|[^'\\])*'", String.Single), # targets (r'([^\n:]+)(:+)([ \t]*)', bygroups(Name.Function, Operator, Text), 'block-header'), # expansions (r'\$\(', Keyword, 'expansion'), ], 'expansion': [ (r'[^$a-zA-Z_)]+', Text), (r'[a-zA-Z_]+', Name.Variable), (r'\$', Keyword), (r'\(', Keyword, '#push'), (r'\)', Keyword, '#pop'), ], 'export': [ (r'[\w${}-]+', Name.Variable), (r'\n', Text, '#pop'), (r'\s+', Text), ], 'block-header': [ (r'[,|]', Punctuation), (r'#.*?\n', Comment, '#pop'), (r'\\\n', Text), # line continuation (r'\$\(', Keyword, 'expansion'), (r'[a-zA-Z_]+', Name), (r'\n', Text, '#pop'), (r'.', Text), ], } class CMakeLexer(RegexLexer): """ Lexer for `CMake <http://cmake.org/Wiki/CMake>`_ files. .. versionadded:: 1.2 """ name = 'CMake' aliases = ['cmake'] filenames = ['*.cmake', 'CMakeLists.txt'] mimetypes = ['text/x-cmake'] tokens = { 'root': [ # (r'(ADD_CUSTOM_COMMAND|ADD_CUSTOM_TARGET|ADD_DEFINITIONS|' # r'ADD_DEPENDENCIES|ADD_EXECUTABLE|ADD_LIBRARY|ADD_SUBDIRECTORY|' # r'ADD_TEST|AUX_SOURCE_DIRECTORY|BUILD_COMMAND|BUILD_NAME|' # r'CMAKE_MINIMUM_REQUIRED|CONFIGURE_FILE|CREATE_TEST_SOURCELIST|' # r'ELSE|ELSEIF|ENABLE_LANGUAGE|ENABLE_TESTING|ENDFOREACH|' # r'ENDFUNCTION|ENDIF|ENDMACRO|ENDWHILE|EXEC_PROGRAM|' # r'EXECUTE_PROCESS|EXPORT_LIBRARY_DEPENDENCIES|FILE|FIND_FILE|' # r'FIND_LIBRARY|FIND_PACKAGE|FIND_PATH|FIND_PROGRAM|FLTK_WRAP_UI|' # r'FOREACH|FUNCTION|GET_CMAKE_PROPERTY|GET_DIRECTORY_PROPERTY|' # r'GET_FILENAME_COMPONENT|GET_SOURCE_FILE_PROPERTY|' # r'GET_TARGET_PROPERTY|GET_TEST_PROPERTY|IF|INCLUDE|' # r'INCLUDE_DIRECTORIES|INCLUDE_EXTERNAL_MSPROJECT|' # r'INCLUDE_REGULAR_EXPRESSION|INSTALL|INSTALL_FILES|' # r'INSTALL_PROGRAMS|INSTALL_TARGETS|LINK_DIRECTORIES|' # r'LINK_LIBRARIES|LIST|LOAD_CACHE|LOAD_COMMAND|MACRO|' # r'MAKE_DIRECTORY|MARK_AS_ADVANCED|MATH|MESSAGE|OPTION|' # r'OUTPUT_REQUIRED_FILES|PROJECT|QT_WRAP_CPP|QT_WRAP_UI|REMOVE|' # r'REMOVE_DEFINITIONS|SEPARATE_ARGUMENTS|SET|' # r'SET_DIRECTORY_PROPERTIES|SET_SOURCE_FILES_PROPERTIES|' # r'SET_TARGET_PROPERTIES|SET_TESTS_PROPERTIES|SITE_NAME|' # r'SOURCE_GROUP|STRING|SUBDIR_DEPENDS|SUBDIRS|' # r'TARGET_LINK_LIBRARIES|TRY_COMPILE|TRY_RUN|UNSET|' # r'USE_MANGLED_MESA|UTILITY_SOURCE|VARIABLE_REQUIRES|' # r'VTK_MAKE_INSTANTIATOR|VTK_WRAP_JAVA|VTK_WRAP_PYTHON|' # r'VTK_WRAP_TCL|WHILE|WRITE_FILE|' # r'COUNTARGS)\b', Name.Builtin, 'args'), (r'\b(\w+)([ \t]*)(\()', bygroups(Name.Builtin, Text, Punctuation), 'args'), include('keywords'), include('ws') ], 'args': [ (r'\(', Punctuation, '#push'), (r'\)', Punctuation, '#pop'), (r'(\$\{)(.+?)(\})', bygroups(Operator, Name.Variable, Operator)), (r'(\$<)(.+?)(>)', bygroups(Operator, Name.Variable, Operator)), (r'(?s)".*?"', String.Double), (r'\\\S+', String), (r'[^)$"# \t\n]+', String), (r'\n', Text), # explicitly legal include('keywords'), include('ws') ], 'string': [ ], 'keywords': [ (r'\b(WIN32|UNIX|APPLE|CYGWIN|BORLAND|MINGW|MSVC|MSVC_IDE|MSVC60|' r'MSVC70|MSVC71|MSVC80|MSVC90)\b', Keyword), ], 'ws': [ (r'[ \t]+', Text), (r'#.*\n', Comment), ] } def analyse_text(text): exp = r'^ *CMAKE_MINIMUM_REQUIRED *\( *VERSION *\d(\.\d)* *( FATAL_ERROR)? *\) *$' if re.search(exp, text, flags=re.MULTILINE | re.IGNORECASE): return 0.8 return 0.0
mit
DiptoDas8/Biponi
lib/python2.7/site-packages/django/conf/locale/el/formats.py
120
1477
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # from __future__ import unicode_literals # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'd/m/Y' TIME_FORMAT = 'P' DATETIME_FORMAT = 'd/m/Y P' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y P' FIRST_DAY_OF_WEEK = 0 # Sunday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%d/%m/%Y', '%d/%m/%y', '%Y-%m-%d', # '25/10/2006', '25/10/06', '2006-10-25', ) DATETIME_INPUT_FORMATS = ( '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M:%S.%f', # '25/10/2006 14:30:59.000200' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%Y', # '25/10/2006' '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59' '%d/%m/%y %H:%M:%S.%f', # '25/10/06 14:30:59.000200' '%d/%m/%y %H:%M', # '25/10/06 14:30' '%d/%m/%y', # '25/10/06' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3
mit
a1ezzz/wasp-general
tests/wasp_general_network_messenger_proto_test.py
1
3944
# -*- coding: utf-8 -*- import pytest from wasp_general.network.messenger.proto import WMessengerOnionProto, WMessengerEnvelopeProto from wasp_general.network.messenger.proto import WMessengerOnionSessionProto, WMessengerOnionLayerProto from wasp_general.network.messenger.proto import WMessengerOnionSessionFlowProto def test_abstract(): pytest.raises(TypeError, WMessengerOnionProto) pytest.raises(NotImplementedError, WMessengerOnionProto.layer, None, '') pytest.raises(NotImplementedError, WMessengerOnionProto.layers_names, None) pytest.raises(TypeError, WMessengerEnvelopeProto) pytest.raises(NotImplementedError, WMessengerEnvelopeProto.message, None) pytest.raises(TypeError, WMessengerOnionSessionProto) pytest.raises(NotImplementedError, WMessengerOnionSessionProto.onion, None) pytest.raises(NotImplementedError, WMessengerOnionSessionProto.process, None, None) envelope = TestEnvelopeProto.Envelope() session = TestWMessengerOnionSessionProto.Session() pytest.raises(TypeError, WMessengerOnionLayerProto) pytest.raises(NotImplementedError, WMessengerOnionLayerProto.process, None, envelope, session) pytest.raises(TypeError, WMessengerOnionSessionFlowProto) pytest.raises(NotImplementedError, WMessengerOnionSessionFlowProto.iterator, None, envelope) class TestEnvelopeProto: class Envelope(WMessengerEnvelopeProto): def message(self): return def test(self): e = TestEnvelopeProto.Envelope() assert(isinstance(e, TestEnvelopeProto.Envelope) is True) assert(isinstance(e, WMessengerEnvelopeProto) is True) assert(e.meta() == {}) class TestWMessengerOnionProto: class Onion(WMessengerOnionProto): def __init__(self): self.layers_storage = {} for l in [ TestWMessengerOnionLayerProto.Layer('first_layer'), TestWMessengerOnionLayerProto.Layer('l2'), TestWMessengerOnionLayerProto.Layer('last') ]: self.layers_storage[l] = l def layer(self, layer_name): return self.layers_storage[layer_name] def layers_names(self): return list(self.layers_storage.values()) class TestWMessengerOnionSessionProto: class Session(WMessengerOnionSessionProto): def onion(self): return TestWMessengerOnionProto.Onion() def process(self, envelope): return class TestWMessengerOnionLayerProto: class Layer(WMessengerOnionLayerProto): def process(self, envelope, session, **kwargs): e = TestEnvelopeProto.Envelope() e.message = lambda: '::' + self.name() + '::' + envelope.message() + '::' return e def test(self): pytest.raises(TypeError, WMessengerOnionLayerProto) l = TestWMessengerOnionLayerProto.Layer('layer_name') assert(isinstance(l, WMessengerOnionLayerProto) is True) assert(l.name() == 'layer_name') l = TestWMessengerOnionLayerProto.Layer('l2') assert(l.name() == 'l2') envelope = TestEnvelopeProto.Envelope() envelope.message = lambda: 'msg' session = TestWMessengerOnionSessionProto.Session() r = l.process(envelope, session) assert(isinstance(r, WMessengerEnvelopeProto) is True) assert(r.message() == '::l2::msg::') class TestWMessengerOnionSessionFlow: def test(self): pytest.raises(TypeError, WMessengerOnionSessionFlowProto.IteratorInfo, 'ln', 4.) ii = WMessengerOnionSessionFlowProto.IteratorInfo('layer_name', a=1, b='code') assert(ii.layer_name() == 'layer_name') assert(ii.layer_args() == {'a': 1, 'b': 'code'}) pytest.raises( TypeError, WMessengerOnionSessionFlowProto.Iterator, 'ln', 7 ) envelope = TestEnvelopeProto.Envelope() i1 = WMessengerOnionSessionFlowProto.Iterator('layer') assert(isinstance(i1, WMessengerOnionSessionFlowProto.Iterator) is True) assert(isinstance(i1, WMessengerOnionSessionFlowProto.IteratorInfo) is True) assert(i1.layer_name() == 'layer') assert(i1.next(envelope) is None) i2 = WMessengerOnionSessionFlowProto.Iterator('layer2', next_iterator=i1) assert(i2.layer_name() == 'layer2') assert(i2.next(envelope) == i1)
lgpl-3.0
dimdung/boto
boto/ec2/regioninfo.py
152
1568
# Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/ # Copyright (c) 2010, Eucalyptus Systems, Inc. # All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. from boto.regioninfo import RegionInfo class EC2RegionInfo(RegionInfo): """ Represents an EC2 Region """ def __init__(self, connection=None, name=None, endpoint=None, connection_cls=None): from boto.ec2.connection import EC2Connection super(EC2RegionInfo, self).__init__(connection, name, endpoint, EC2Connection)
mit
Arcanemagus/plexpy
lib/tqdm/_tqdm_notebook.py
3
8426
""" IPython/Jupyter Notebook progressbar decorator for iterators. Includes a default (x)range iterator printing to stderr. Usage: >>> from tqdm_notebook import tnrange[, tqdm_notebook] >>> for i in tnrange(10): #same as: for i in tqdm_notebook(xrange(10)) ... ... """ # future division is important to divide integers and get as # a result precise floating numbers (instead of truncated int) from __future__ import division, absolute_import # import compatibility functions and utilities import sys from ._utils import _range # to inherit from the tqdm class from ._tqdm import tqdm if True: # pragma: no cover # import IPython/Jupyter base widget and display utilities try: # IPython 4.x import ipywidgets IPY = 4 except ImportError: # IPython 3.x / 2.x IPY = 32 import warnings with warnings.catch_warnings(): ipy_deprecation_msg = "The `IPython.html` package" \ " has been deprecated" warnings.filterwarnings('error', message=".*" + ipy_deprecation_msg + ".*") try: import IPython.html.widgets as ipywidgets except Warning as e: if ipy_deprecation_msg not in str(e): raise warnings.simplefilter('ignore') try: import IPython.html.widgets as ipywidgets # NOQA except ImportError: pass except ImportError: pass try: # IPython 4.x / 3.x if IPY == 32: from IPython.html.widgets import IntProgress, HBox, HTML IPY = 3 else: from ipywidgets import IntProgress, HBox, HTML except ImportError: try: # IPython 2.x from IPython.html.widgets import IntProgressWidget as IntProgress from IPython.html.widgets import ContainerWidget as HBox from IPython.html.widgets import HTML IPY = 2 except ImportError: IPY = 0 try: from IPython.display import display # , clear_output except ImportError: pass # HTML encoding try: # Py3 from html import escape except ImportError: # Py2 from cgi import escape __author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]} __all__ = ['tqdm_notebook', 'tnrange'] class tqdm_notebook(tqdm): """ Experimental IPython/Jupyter Notebook widget using tqdm! """ @staticmethod def status_printer(_, total=None, desc=None): """ Manage the printing of an IPython/Jupyter Notebook progress bar widget. """ # Fallback to text bar if there's no total # DEPRECATED: replaced with an 'info' style bar # if not total: # return super(tqdm_notebook, tqdm_notebook).status_printer(file) # fp = file # Prepare IPython progress bar if total: pbar = IntProgress(min=0, max=total) else: # No total? Show info style bar with no progress tqdm status pbar = IntProgress(min=0, max=1) pbar.value = 1 pbar.bar_style = 'info' if desc: pbar.description = desc # Prepare status text ptext = HTML() # Only way to place text to the right of the bar is to use a container container = HBox(children=[pbar, ptext]) display(container) def print_status(s='', close=False, bar_style=None, desc=None): # Note: contrary to native tqdm, s='' does NOT clear bar # goal is to keep all infos if error happens so user knows # at which iteration the loop failed. # Clear previous output (really necessary?) # clear_output(wait=1) # Get current iteration value from format_meter string if total: # n = None if s: npos = s.find(r'/|/') # cause we use bar_format=r'{n}|...' # Check that n can be found in s (else n > total) if npos >= 0: n = int(s[:npos]) # get n from string s = s[npos + 3:] # remove from string # Update bar with current n value if n is not None: pbar.value = n # Print stats if s: # never clear the bar (signal: s='') s = s.replace('||', '') # remove inesthetical pipes s = escape(s) # html escape special characters (like '?') ptext.value = s # Change bar style if bar_style: # Hack-ish way to avoid the danger bar_style being overriden by # success because the bar gets closed after the error... if not (pbar.bar_style == 'danger' and bar_style == 'success'): pbar.bar_style = bar_style # Special signal to close the bar if close and pbar.bar_style != 'danger': # hide only if no error try: container.close() except AttributeError: container.visible = False # Update description if desc: pbar.description = desc return print_status def __init__(self, *args, **kwargs): # Setup default output if kwargs.get('file', sys.stderr) is sys.stderr: kwargs['file'] = sys.stdout # avoid the red block in IPython # Remove the bar from the printed string, only print stats if not kwargs.get('bar_format', None): kwargs['bar_format'] = r'{n}/|/{l_bar}{r_bar}' # Initialize parent class + avoid printing by using gui=True kwargs['gui'] = True super(tqdm_notebook, self).__init__(*args, **kwargs) if self.disable or not kwargs['gui']: return # Delete first pbar generated from super() (wrong total and text) # DEPRECATED by using gui=True # self.sp('', close=True) # Replace with IPython progress bar display (with correct total) self.sp = self.status_printer(self.fp, self.total, self.desc) self.desc = None # trick to place description before the bar # Print initial bar state if not self.disable: self.sp(self.__repr__()) # same as self.refresh without clearing def __iter__(self, *args, **kwargs): try: for obj in super(tqdm_notebook, self).__iter__(*args, **kwargs): # return super(tqdm...) will not catch exception yield obj # NB: except ... [ as ...] breaks IPython async KeyboardInterrupt except: self.sp(bar_style='danger') raise def update(self, *args, **kwargs): try: super(tqdm_notebook, self).update(*args, **kwargs) except Exception as exc: # cannot catch KeyboardInterrupt when using manual tqdm # as the interrupt will most likely happen on another statement self.sp(bar_style='danger') raise exc def close(self, *args, **kwargs): super(tqdm_notebook, self).close(*args, **kwargs) # If it was not run in a notebook, sp is not assigned, check for it if hasattr(self, 'sp'): # Try to detect if there was an error or KeyboardInterrupt # in manual mode: if n < total, things probably got wrong if self.total and self.n < self.total: self.sp(bar_style='danger') else: if self.leave: self.sp(bar_style='success') else: self.sp(close=True) def moveto(self, *args, **kwargs): # void -> avoid extraneous `\n` in IPython output cell return def set_description(self, desc=None, **_): """ Set/modify description of the progress bar. Parameters ---------- desc : str, optional """ self.sp(desc=desc) def tnrange(*args, **kwargs): """ A shortcut for tqdm_notebook(xrange(*args), **kwargs). On Python3+ range is used instead of xrange. """ return tqdm_notebook(_range(*args), **kwargs)
gpl-3.0
mrbox/django
tests/delete_regress/models.py
325
3172
from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation, ) from django.contrib.contenttypes.models import ContentType from django.db import models class Award(models.Model): name = models.CharField(max_length=25) object_id = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType, models.CASCADE) content_object = GenericForeignKey() class AwardNote(models.Model): award = models.ForeignKey(Award, models.CASCADE) note = models.CharField(max_length=100) class Person(models.Model): name = models.CharField(max_length=25) awards = GenericRelation(Award) class Book(models.Model): pagecount = models.IntegerField() class Toy(models.Model): name = models.CharField(max_length=50) class Child(models.Model): name = models.CharField(max_length=50) toys = models.ManyToManyField(Toy, through='PlayedWith') class PlayedWith(models.Model): child = models.ForeignKey(Child, models.CASCADE) toy = models.ForeignKey(Toy, models.CASCADE) date = models.DateField(db_column='date_col') class PlayedWithNote(models.Model): played = models.ForeignKey(PlayedWith, models.CASCADE) note = models.TextField() class Contact(models.Model): label = models.CharField(max_length=100) class Email(Contact): email_address = models.EmailField(max_length=100) class Researcher(models.Model): contacts = models.ManyToManyField(Contact, related_name="research_contacts") class Food(models.Model): name = models.CharField(max_length=20, unique=True) class Eaten(models.Model): food = models.ForeignKey(Food, models.CASCADE, to_field="name") meal = models.CharField(max_length=20) # Models for #15776 class Policy(models.Model): policy_number = models.CharField(max_length=10) class Version(models.Model): policy = models.ForeignKey(Policy, models.CASCADE) class Location(models.Model): version = models.ForeignKey(Version, models.SET_NULL, blank=True, null=True) class Item(models.Model): version = models.ForeignKey(Version, models.CASCADE) location = models.ForeignKey(Location, models.SET_NULL, blank=True, null=True) # Models for #16128 class File(models.Model): pass class Image(File): class Meta: proxy = True class Photo(Image): class Meta: proxy = True class FooImage(models.Model): my_image = models.ForeignKey(Image, models.CASCADE) class FooFile(models.Model): my_file = models.ForeignKey(File, models.CASCADE) class FooPhoto(models.Model): my_photo = models.ForeignKey(Photo, models.CASCADE) class FooFileProxy(FooFile): class Meta: proxy = True class OrgUnit(models.Model): name = models.CharField(max_length=64, unique=True) class Login(models.Model): description = models.CharField(max_length=32) orgunit = models.ForeignKey(OrgUnit, models.CASCADE) class House(models.Model): address = models.CharField(max_length=32) class OrderedPerson(models.Model): name = models.CharField(max_length=32) lives_in = models.ForeignKey(House, models.CASCADE) class Meta: ordering = ['name']
bsd-3-clause
onecloud/neutron
neutron/openstack/common/service.py
15
15623
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # 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. """Generic Node base class for all workers that run on hosts.""" import errno import logging as std_logging import os import random import signal import sys import time try: # Importing just the symbol here because the io module does not # exist in Python 2.6. from io import UnsupportedOperation # noqa except ImportError: # Python 2.6 UnsupportedOperation = None import eventlet from eventlet import event from oslo.config import cfg from neutron.openstack.common import eventlet_backdoor from neutron.openstack.common.gettextutils import _LE, _LI, _LW from neutron.openstack.common import importutils from neutron.openstack.common import log as logging from neutron.openstack.common import systemd from neutron.openstack.common import threadgroup rpc = importutils.try_import('neutron.openstack.common.rpc') CONF = cfg.CONF LOG = logging.getLogger(__name__) def _sighup_supported(): return hasattr(signal, 'SIGHUP') def _is_daemon(): # The process group for a foreground process will match the # process group of the controlling terminal. If those values do # not match, or ioctl() fails on the stdout file handle, we assume # the process is running in the background as a daemon. # http://www.gnu.org/software/bash/manual/bashref.html#Job-Control-Basics try: is_daemon = os.getpgrp() != os.tcgetpgrp(sys.stdout.fileno()) except OSError as err: if err.errno == errno.ENOTTY: # Assume we are a daemon because there is no terminal. is_daemon = True else: raise except UnsupportedOperation: # Could not get the fileno for stdout, so we must be a daemon. is_daemon = True return is_daemon def _is_sighup_and_daemon(signo): if not (_sighup_supported() and signo == signal.SIGHUP): # Avoid checking if we are a daemon, because the signal isn't # SIGHUP. return False return _is_daemon() def _signo_to_signame(signo): signals = {signal.SIGTERM: 'SIGTERM', signal.SIGINT: 'SIGINT'} if _sighup_supported(): signals[signal.SIGHUP] = 'SIGHUP' return signals[signo] def _set_signals_handler(handler): signal.signal(signal.SIGTERM, handler) signal.signal(signal.SIGINT, handler) if _sighup_supported(): signal.signal(signal.SIGHUP, handler) class Launcher(object): """Launch one or more services and wait for them to complete.""" def __init__(self): """Initialize the service launcher. :returns: None """ self.services = Services() self.backdoor_port = eventlet_backdoor.initialize_if_enabled() def launch_service(self, service): """Load and start the given service. :param service: The service you would like to start. :returns: None """ service.backdoor_port = self.backdoor_port self.services.add(service) def stop(self): """Stop all services which are currently running. :returns: None """ self.services.stop() def wait(self): """Waits until all services have been stopped, and then returns. :returns: None """ self.services.wait() def restart(self): """Reload config files and restart service. :returns: None """ cfg.CONF.reload_config_files() self.services.restart() class SignalExit(SystemExit): def __init__(self, signo, exccode=1): super(SignalExit, self).__init__(exccode) self.signo = signo class ServiceLauncher(Launcher): def _handle_signal(self, signo, frame): # Allow the process to be killed again and die from natural causes _set_signals_handler(signal.SIG_DFL) raise SignalExit(signo) def handle_signal(self): _set_signals_handler(self._handle_signal) def _wait_for_exit_or_signal(self, ready_callback=None): status = None signo = 0 LOG.debug('Full set of CONF:') CONF.log_opt_values(LOG, std_logging.DEBUG) try: if ready_callback: ready_callback() super(ServiceLauncher, self).wait() except SignalExit as exc: signame = _signo_to_signame(exc.signo) LOG.info(_LI('Caught %s, exiting'), signame) status = exc.code signo = exc.signo except SystemExit as exc: status = exc.code finally: self.stop() if rpc: try: rpc.cleanup() except Exception: # We're shutting down, so it doesn't matter at this point. LOG.exception(_LE('Exception during rpc cleanup.')) return status, signo def wait(self, ready_callback=None): systemd.notify_once() while True: self.handle_signal() status, signo = self._wait_for_exit_or_signal(ready_callback) if not _is_sighup_and_daemon(signo): return status self.restart() class ServiceWrapper(object): def __init__(self, service, workers): self.service = service self.workers = workers self.children = set() self.forktimes = [] class ProcessLauncher(object): def __init__(self, wait_interval=0.01): """Constructor. :param wait_interval: The interval to sleep for between checks of child process exit. """ self.children = {} self.sigcaught = None self.running = True self.wait_interval = wait_interval rfd, self.writepipe = os.pipe() self.readpipe = eventlet.greenio.GreenPipe(rfd, 'r') self.handle_signal() def handle_signal(self): _set_signals_handler(self._handle_signal) def _handle_signal(self, signo, frame): self.sigcaught = signo self.running = False # Allow the process to be killed again and die from natural causes _set_signals_handler(signal.SIG_DFL) def _pipe_watcher(self): # This will block until the write end is closed when the parent # dies unexpectedly self.readpipe.read() LOG.info(_LI('Parent process has died unexpectedly, exiting')) sys.exit(1) def _child_process_handle_signal(self): # Setup child signal handlers differently def _sigterm(*args): signal.signal(signal.SIGTERM, signal.SIG_DFL) raise SignalExit(signal.SIGTERM) def _sighup(*args): signal.signal(signal.SIGHUP, signal.SIG_DFL) raise SignalExit(signal.SIGHUP) signal.signal(signal.SIGTERM, _sigterm) if _sighup_supported(): signal.signal(signal.SIGHUP, _sighup) # Block SIGINT and let the parent send us a SIGTERM signal.signal(signal.SIGINT, signal.SIG_IGN) def _child_wait_for_exit_or_signal(self, launcher): status = 0 signo = 0 # NOTE(johannes): All exceptions are caught to ensure this # doesn't fallback into the loop spawning children. It would # be bad for a child to spawn more children. try: launcher.wait() except SignalExit as exc: signame = _signo_to_signame(exc.signo) LOG.info(_LI('Child caught %s, exiting'), signame) status = exc.code signo = exc.signo except SystemExit as exc: status = exc.code except BaseException: LOG.exception(_LE('Unhandled exception')) status = 2 finally: launcher.stop() return status, signo def _child_process(self, service): self._child_process_handle_signal() # Reopen the eventlet hub to make sure we don't share an epoll # fd with parent and/or siblings, which would be bad eventlet.hubs.use_hub() # Close write to ensure only parent has it open os.close(self.writepipe) # Create greenthread to watch for parent to close pipe eventlet.spawn_n(self._pipe_watcher) # Reseed random number generator random.seed() launcher = Launcher() launcher.launch_service(service) return launcher def _start_child(self, wrap): if len(wrap.forktimes) > wrap.workers: # Limit ourselves to one process a second (over the period of # number of workers * 1 second). This will allow workers to # start up quickly but ensure we don't fork off children that # die instantly too quickly. if time.time() - wrap.forktimes[0] < wrap.workers: LOG.info(_LI('Forking too fast, sleeping')) time.sleep(1) wrap.forktimes.pop(0) wrap.forktimes.append(time.time()) pid = os.fork() if pid == 0: launcher = self._child_process(wrap.service) while True: self._child_process_handle_signal() status, signo = self._child_wait_for_exit_or_signal(launcher) if not _is_sighup_and_daemon(signo): break launcher.restart() os._exit(status) LOG.info(_LI('Started child %d'), pid) wrap.children.add(pid) self.children[pid] = wrap return pid def launch_service(self, service, workers=1): wrap = ServiceWrapper(service, workers) LOG.info(_LI('Starting %d workers'), wrap.workers) while self.running and len(wrap.children) < wrap.workers: self._start_child(wrap) def _wait_child(self): try: # Don't block if no child processes have exited pid, status = os.waitpid(0, os.WNOHANG) if not pid: return None except OSError as exc: if exc.errno not in (errno.EINTR, errno.ECHILD): raise return None if os.WIFSIGNALED(status): sig = os.WTERMSIG(status) LOG.info(_LI('Child %(pid)d killed by signal %(sig)d'), dict(pid=pid, sig=sig)) else: code = os.WEXITSTATUS(status) LOG.info(_LI('Child %(pid)s exited with status %(code)d'), dict(pid=pid, code=code)) if pid not in self.children: LOG.warning(_LW('pid %d not in child list'), pid) return None wrap = self.children.pop(pid) wrap.children.remove(pid) return wrap def _respawn_children(self): while self.running: wrap = self._wait_child() if not wrap: # Yield to other threads if no children have exited # Sleep for a short time to avoid excessive CPU usage # (see bug #1095346) eventlet.greenthread.sleep(self.wait_interval) continue while self.running and len(wrap.children) < wrap.workers: self._start_child(wrap) def wait(self): """Loop waiting on children to die and respawning as necessary.""" systemd.notify_once() LOG.debug('Full set of CONF:') CONF.log_opt_values(LOG, std_logging.DEBUG) try: while True: self.handle_signal() self._respawn_children() # No signal means that stop was called. Don't clean up here. if not self.sigcaught: return signame = _signo_to_signame(self.sigcaught) LOG.info(_LI('Caught %s, stopping children'), signame) if not _is_sighup_and_daemon(self.sigcaught): break for pid in self.children: os.kill(pid, signal.SIGHUP) self.running = True self.sigcaught = None except eventlet.greenlet.GreenletExit: LOG.info(_LI("Wait called after thread killed. Cleaning up.")) self.stop() def stop(self): """Terminate child processes and wait on each.""" self.running = False for pid in self.children: try: os.kill(pid, signal.SIGTERM) except OSError as exc: if exc.errno != errno.ESRCH: raise # Wait for children to die if self.children: LOG.info(_LI('Waiting on %d children to exit'), len(self.children)) while self.children: self._wait_child() class Service(object): """Service object for binaries running on hosts.""" def __init__(self, threads=1000): self.tg = threadgroup.ThreadGroup(threads) # signal that the service is done shutting itself down: self._done = event.Event() def reset(self): # NOTE(Fengqian): docs for Event.reset() recommend against using it self._done = event.Event() def start(self): pass def stop(self): self.tg.stop() self.tg.wait() # Signal that service cleanup is done: if not self._done.ready(): self._done.send() def wait(self): self._done.wait() class Services(object): def __init__(self): self.services = [] self.tg = threadgroup.ThreadGroup() self.done = event.Event() def add(self, service): self.services.append(service) self.tg.add_thread(self.run_service, service, self.done) def stop(self): # wait for graceful shutdown of services: for service in self.services: service.stop() service.wait() # Each service has performed cleanup, now signal that the run_service # wrapper threads can now die: if not self.done.ready(): self.done.send() # reap threads: self.tg.stop() def wait(self): self.tg.wait() def restart(self): self.stop() self.done = event.Event() for restart_service in self.services: restart_service.reset() self.tg.add_thread(self.run_service, restart_service, self.done) @staticmethod def run_service(service, done): """Service start wrapper. :param service: service to run :param done: event to wait on until a shutdown is triggered :returns: None """ service.start() done.wait() def launch(service, workers=1): if workers is None or workers == 1: launcher = ServiceLauncher() launcher.launch_service(service) else: launcher = ProcessLauncher() launcher.launch_service(service, workers=workers) return launcher
apache-2.0
eeason3/Bootstrap
node_modules/gulp-sass/node_modules/node-sass/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py
240
99242
# Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import collections import copy import hashlib import json import multiprocessing import os.path import re import signal import subprocess import sys import gyp import gyp.common from gyp.common import OrderedSet import gyp.msvs_emulation import gyp.MSVSUtil as MSVSUtil import gyp.xcode_emulation from cStringIO import StringIO from gyp.common import GetEnvironFallback import gyp.ninja_syntax as ninja_syntax generator_default_variables = { 'EXECUTABLE_PREFIX': '', 'EXECUTABLE_SUFFIX': '', 'STATIC_LIB_PREFIX': 'lib', 'STATIC_LIB_SUFFIX': '.a', 'SHARED_LIB_PREFIX': 'lib', # Gyp expects the following variables to be expandable by the build # system to the appropriate locations. Ninja prefers paths to be # known at gyp time. To resolve this, introduce special # variables starting with $! and $| (which begin with a $ so gyp knows it # should be treated specially, but is otherwise an invalid # ninja/shell variable) that are passed to gyp here but expanded # before writing out into the target .ninja files; see # ExpandSpecial. # $! is used for variables that represent a path and that can only appear at # the start of a string, while $| is used for variables that can appear # anywhere in a string. 'INTERMEDIATE_DIR': '$!INTERMEDIATE_DIR', 'SHARED_INTERMEDIATE_DIR': '$!PRODUCT_DIR/gen', 'PRODUCT_DIR': '$!PRODUCT_DIR', 'CONFIGURATION_NAME': '$|CONFIGURATION_NAME', # Special variables that may be used by gyp 'rule' targets. # We generate definitions for these variables on the fly when processing a # rule. 'RULE_INPUT_ROOT': '${root}', 'RULE_INPUT_DIRNAME': '${dirname}', 'RULE_INPUT_PATH': '${source}', 'RULE_INPUT_EXT': '${ext}', 'RULE_INPUT_NAME': '${name}', } # Placates pylint. generator_additional_non_configuration_keys = [] generator_additional_path_sections = [] generator_extra_sources_for_rules = [] generator_filelist_paths = None generator_supports_multiple_toolsets = gyp.common.CrossCompileRequested() def StripPrefix(arg, prefix): if arg.startswith(prefix): return arg[len(prefix):] return arg def QuoteShellArgument(arg, flavor): """Quote a string such that it will be interpreted as a single argument by the shell.""" # Rather than attempting to enumerate the bad shell characters, just # whitelist common OK ones and quote anything else. if re.match(r'^[a-zA-Z0-9_=.\\/-]+$', arg): return arg # No quoting necessary. if flavor == 'win': return gyp.msvs_emulation.QuoteForRspFile(arg) return "'" + arg.replace("'", "'" + '"\'"' + "'") + "'" def Define(d, flavor): """Takes a preprocessor define and returns a -D parameter that's ninja- and shell-escaped.""" if flavor == 'win': # cl.exe replaces literal # characters with = in preprocesor definitions for # some reason. Octal-encode to work around that. d = d.replace('#', '\\%03o' % ord('#')) return QuoteShellArgument(ninja_syntax.escape('-D' + d), flavor) def AddArch(output, arch): """Adds an arch string to an output path.""" output, extension = os.path.splitext(output) return '%s.%s%s' % (output, arch, extension) class Target(object): """Target represents the paths used within a single gyp target. Conceptually, building a single target A is a series of steps: 1) actions/rules/copies generates source/resources/etc. 2) compiles generates .o files 3) link generates a binary (library/executable) 4) bundle merges the above in a mac bundle (Any of these steps can be optional.) From a build ordering perspective, a dependent target B could just depend on the last output of this series of steps. But some dependent commands sometimes need to reach inside the box. For example, when linking B it needs to get the path to the static library generated by A. This object stores those paths. To keep things simple, member variables only store concrete paths to single files, while methods compute derived values like "the last output of the target". """ def __init__(self, type): # Gyp type ("static_library", etc.) of this target. self.type = type # File representing whether any input dependencies necessary for # dependent actions have completed. self.preaction_stamp = None # File representing whether any input dependencies necessary for # dependent compiles have completed. self.precompile_stamp = None # File representing the completion of actions/rules/copies, if any. self.actions_stamp = None # Path to the output of the link step, if any. self.binary = None # Path to the file representing the completion of building the bundle, # if any. self.bundle = None # On Windows, incremental linking requires linking against all the .objs # that compose a .lib (rather than the .lib itself). That list is stored # here. self.component_objs = None # Windows only. The import .lib is the output of a build step, but # because dependents only link against the lib (not both the lib and the # dll) we keep track of the import library here. self.import_lib = None def Linkable(self): """Return true if this is a target that can be linked against.""" return self.type in ('static_library', 'shared_library') def UsesToc(self, flavor): """Return true if the target should produce a restat rule based on a TOC file.""" # For bundles, the .TOC should be produced for the binary, not for # FinalOutput(). But the naive approach would put the TOC file into the # bundle, so don't do this for bundles for now. if flavor == 'win' or self.bundle: return False return self.type in ('shared_library', 'loadable_module') def PreActionInput(self, flavor): """Return the path, if any, that should be used as a dependency of any dependent action step.""" if self.UsesToc(flavor): return self.FinalOutput() + '.TOC' return self.FinalOutput() or self.preaction_stamp def PreCompileInput(self): """Return the path, if any, that should be used as a dependency of any dependent compile step.""" return self.actions_stamp or self.precompile_stamp def FinalOutput(self): """Return the last output of the target, which depends on all prior steps.""" return self.bundle or self.binary or self.actions_stamp # A small discourse on paths as used within the Ninja build: # All files we produce (both at gyp and at build time) appear in the # build directory (e.g. out/Debug). # # Paths within a given .gyp file are always relative to the directory # containing the .gyp file. Call these "gyp paths". This includes # sources as well as the starting directory a given gyp rule/action # expects to be run from. We call the path from the source root to # the gyp file the "base directory" within the per-.gyp-file # NinjaWriter code. # # All paths as written into the .ninja files are relative to the build # directory. Call these paths "ninja paths". # # We translate between these two notions of paths with two helper # functions: # # - GypPathToNinja translates a gyp path (i.e. relative to the .gyp file) # into the equivalent ninja path. # # - GypPathToUniqueOutput translates a gyp path into a ninja path to write # an output file; the result can be namespaced such that it is unique # to the input file name as well as the output target name. class NinjaWriter(object): def __init__(self, hash_for_rules, target_outputs, base_dir, build_dir, output_file, toplevel_build, output_file_name, flavor, toplevel_dir=None): """ base_dir: path from source root to directory containing this gyp file, by gyp semantics, all input paths are relative to this build_dir: path from source root to build output toplevel_dir: path to the toplevel directory """ self.hash_for_rules = hash_for_rules self.target_outputs = target_outputs self.base_dir = base_dir self.build_dir = build_dir self.ninja = ninja_syntax.Writer(output_file) self.toplevel_build = toplevel_build self.output_file_name = output_file_name self.flavor = flavor self.abs_build_dir = None if toplevel_dir is not None: self.abs_build_dir = os.path.abspath(os.path.join(toplevel_dir, build_dir)) self.obj_ext = '.obj' if flavor == 'win' else '.o' if flavor == 'win': # See docstring of msvs_emulation.GenerateEnvironmentFiles(). self.win_env = {} for arch in ('x86', 'x64'): self.win_env[arch] = 'environment.' + arch # Relative path from build output dir to base dir. build_to_top = gyp.common.InvertRelativePath(build_dir, toplevel_dir) self.build_to_base = os.path.join(build_to_top, base_dir) # Relative path from base dir to build dir. base_to_top = gyp.common.InvertRelativePath(base_dir, toplevel_dir) self.base_to_build = os.path.join(base_to_top, build_dir) def ExpandSpecial(self, path, product_dir=None): """Expand specials like $!PRODUCT_DIR in |path|. If |product_dir| is None, assumes the cwd is already the product dir. Otherwise, |product_dir| is the relative path to the product dir. """ PRODUCT_DIR = '$!PRODUCT_DIR' if PRODUCT_DIR in path: if product_dir: path = path.replace(PRODUCT_DIR, product_dir) else: path = path.replace(PRODUCT_DIR + '/', '') path = path.replace(PRODUCT_DIR + '\\', '') path = path.replace(PRODUCT_DIR, '.') INTERMEDIATE_DIR = '$!INTERMEDIATE_DIR' if INTERMEDIATE_DIR in path: int_dir = self.GypPathToUniqueOutput('gen') # GypPathToUniqueOutput generates a path relative to the product dir, # so insert product_dir in front if it is provided. path = path.replace(INTERMEDIATE_DIR, os.path.join(product_dir or '', int_dir)) CONFIGURATION_NAME = '$|CONFIGURATION_NAME' path = path.replace(CONFIGURATION_NAME, self.config_name) return path def ExpandRuleVariables(self, path, root, dirname, source, ext, name): if self.flavor == 'win': path = self.msvs_settings.ConvertVSMacros( path, config=self.config_name) path = path.replace(generator_default_variables['RULE_INPUT_ROOT'], root) path = path.replace(generator_default_variables['RULE_INPUT_DIRNAME'], dirname) path = path.replace(generator_default_variables['RULE_INPUT_PATH'], source) path = path.replace(generator_default_variables['RULE_INPUT_EXT'], ext) path = path.replace(generator_default_variables['RULE_INPUT_NAME'], name) return path def GypPathToNinja(self, path, env=None): """Translate a gyp path to a ninja path, optionally expanding environment variable references in |path| with |env|. See the above discourse on path conversions.""" if env: if self.flavor == 'mac': path = gyp.xcode_emulation.ExpandEnvVars(path, env) elif self.flavor == 'win': path = gyp.msvs_emulation.ExpandMacros(path, env) if path.startswith('$!'): expanded = self.ExpandSpecial(path) if self.flavor == 'win': expanded = os.path.normpath(expanded) return expanded if '$|' in path: path = self.ExpandSpecial(path) assert '$' not in path, path return os.path.normpath(os.path.join(self.build_to_base, path)) def GypPathToUniqueOutput(self, path, qualified=True): """Translate a gyp path to a ninja path for writing output. If qualified is True, qualify the resulting filename with the name of the target. This is necessary when e.g. compiling the same path twice for two separate output targets. See the above discourse on path conversions.""" path = self.ExpandSpecial(path) assert not path.startswith('$'), path # Translate the path following this scheme: # Input: foo/bar.gyp, target targ, references baz/out.o # Output: obj/foo/baz/targ.out.o (if qualified) # obj/foo/baz/out.o (otherwise) # (and obj.host instead of obj for cross-compiles) # # Why this scheme and not some other one? # 1) for a given input, you can compute all derived outputs by matching # its path, even if the input is brought via a gyp file with '..'. # 2) simple files like libraries and stamps have a simple filename. obj = 'obj' if self.toolset != 'target': obj += '.' + self.toolset path_dir, path_basename = os.path.split(path) assert not os.path.isabs(path_dir), ( "'%s' can not be absolute path (see crbug.com/462153)." % path_dir) if qualified: path_basename = self.name + '.' + path_basename return os.path.normpath(os.path.join(obj, self.base_dir, path_dir, path_basename)) def WriteCollapsedDependencies(self, name, targets, order_only=None): """Given a list of targets, return a path for a single file representing the result of building all the targets or None. Uses a stamp file if necessary.""" assert targets == filter(None, targets), targets if len(targets) == 0: assert not order_only return None if len(targets) > 1 or order_only: stamp = self.GypPathToUniqueOutput(name + '.stamp') targets = self.ninja.build(stamp, 'stamp', targets, order_only=order_only) self.ninja.newline() return targets[0] def _SubninjaNameForArch(self, arch): output_file_base = os.path.splitext(self.output_file_name)[0] return '%s.%s.ninja' % (output_file_base, arch) def WriteSpec(self, spec, config_name, generator_flags): """The main entry point for NinjaWriter: write the build rules for a spec. Returns a Target object, which represents the output paths for this spec. Returns None if there are no outputs (e.g. a settings-only 'none' type target).""" self.config_name = config_name self.name = spec['target_name'] self.toolset = spec['toolset'] config = spec['configurations'][config_name] self.target = Target(spec['type']) self.is_standalone_static_library = bool( spec.get('standalone_static_library', 0)) # Track if this target contains any C++ files, to decide if gcc or g++ # should be used for linking. self.uses_cpp = False self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec) self.xcode_settings = self.msvs_settings = None if self.flavor == 'mac': self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec) if self.flavor == 'win': self.msvs_settings = gyp.msvs_emulation.MsvsSettings(spec, generator_flags) arch = self.msvs_settings.GetArch(config_name) self.ninja.variable('arch', self.win_env[arch]) self.ninja.variable('cc', '$cl_' + arch) self.ninja.variable('cxx', '$cl_' + arch) self.ninja.variable('cc_host', '$cl_' + arch) self.ninja.variable('cxx_host', '$cl_' + arch) self.ninja.variable('asm', '$ml_' + arch) if self.flavor == 'mac': self.archs = self.xcode_settings.GetActiveArchs(config_name) if len(self.archs) > 1: self.arch_subninjas = dict( (arch, ninja_syntax.Writer( OpenOutput(os.path.join(self.toplevel_build, self._SubninjaNameForArch(arch)), 'w'))) for arch in self.archs) # Compute predepends for all rules. # actions_depends is the dependencies this target depends on before running # any of its action/rule/copy steps. # compile_depends is the dependencies this target depends on before running # any of its compile steps. actions_depends = [] compile_depends = [] # TODO(evan): it is rather confusing which things are lists and which # are strings. Fix these. if 'dependencies' in spec: for dep in spec['dependencies']: if dep in self.target_outputs: target = self.target_outputs[dep] actions_depends.append(target.PreActionInput(self.flavor)) compile_depends.append(target.PreCompileInput()) actions_depends = filter(None, actions_depends) compile_depends = filter(None, compile_depends) actions_depends = self.WriteCollapsedDependencies('actions_depends', actions_depends) compile_depends = self.WriteCollapsedDependencies('compile_depends', compile_depends) self.target.preaction_stamp = actions_depends self.target.precompile_stamp = compile_depends # Write out actions, rules, and copies. These must happen before we # compile any sources, so compute a list of predependencies for sources # while we do it. extra_sources = [] mac_bundle_depends = [] self.target.actions_stamp = self.WriteActionsRulesCopies( spec, extra_sources, actions_depends, mac_bundle_depends) # If we have actions/rules/copies, we depend directly on those, but # otherwise we depend on dependent target's actions/rules/copies etc. # We never need to explicitly depend on previous target's link steps, # because no compile ever depends on them. compile_depends_stamp = (self.target.actions_stamp or compile_depends) # Write out the compilation steps, if any. link_deps = [] sources = extra_sources + spec.get('sources', []) if sources: if self.flavor == 'mac' and len(self.archs) > 1: # Write subninja file containing compile and link commands scoped to # a single arch if a fat binary is being built. for arch in self.archs: self.ninja.subninja(self._SubninjaNameForArch(arch)) pch = None if self.flavor == 'win': gyp.msvs_emulation.VerifyMissingSources( sources, self.abs_build_dir, generator_flags, self.GypPathToNinja) pch = gyp.msvs_emulation.PrecompiledHeader( self.msvs_settings, config_name, self.GypPathToNinja, self.GypPathToUniqueOutput, self.obj_ext) else: pch = gyp.xcode_emulation.MacPrefixHeader( self.xcode_settings, self.GypPathToNinja, lambda path, lang: self.GypPathToUniqueOutput(path + '-' + lang)) link_deps = self.WriteSources( self.ninja, config_name, config, sources, compile_depends_stamp, pch, spec) # Some actions/rules output 'sources' that are already object files. obj_outputs = [f for f in sources if f.endswith(self.obj_ext)] if obj_outputs: if self.flavor != 'mac' or len(self.archs) == 1: link_deps += [self.GypPathToNinja(o) for o in obj_outputs] else: print "Warning: Actions/rules writing object files don't work with " \ "multiarch targets, dropping. (target %s)" % spec['target_name'] elif self.flavor == 'mac' and len(self.archs) > 1: link_deps = collections.defaultdict(list) if self.flavor == 'win' and self.target.type == 'static_library': self.target.component_objs = link_deps # Write out a link step, if needed. output = None is_empty_bundle = not link_deps and not mac_bundle_depends if link_deps or self.target.actions_stamp or actions_depends: output = self.WriteTarget(spec, config_name, config, link_deps, self.target.actions_stamp or actions_depends) if self.is_mac_bundle: mac_bundle_depends.append(output) # Bundle all of the above together, if needed. if self.is_mac_bundle: output = self.WriteMacBundle(spec, mac_bundle_depends, is_empty_bundle) if not output: return None assert self.target.FinalOutput(), output return self.target def _WinIdlRule(self, source, prebuild, outputs): """Handle the implicit VS .idl rule for one source file. Fills |outputs| with files that are generated.""" outdir, output, vars, flags = self.msvs_settings.GetIdlBuildData( source, self.config_name) outdir = self.GypPathToNinja(outdir) def fix_path(path, rel=None): path = os.path.join(outdir, path) dirname, basename = os.path.split(source) root, ext = os.path.splitext(basename) path = self.ExpandRuleVariables( path, root, dirname, source, ext, basename) if rel: path = os.path.relpath(path, rel) return path vars = [(name, fix_path(value, outdir)) for name, value in vars] output = [fix_path(p) for p in output] vars.append(('outdir', outdir)) vars.append(('idlflags', flags)) input = self.GypPathToNinja(source) self.ninja.build(output, 'idl', input, variables=vars, order_only=prebuild) outputs.extend(output) def WriteWinIdlFiles(self, spec, prebuild): """Writes rules to match MSVS's implicit idl handling.""" assert self.flavor == 'win' if self.msvs_settings.HasExplicitIdlRulesOrActions(spec): return [] outputs = [] for source in filter(lambda x: x.endswith('.idl'), spec['sources']): self._WinIdlRule(source, prebuild, outputs) return outputs def WriteActionsRulesCopies(self, spec, extra_sources, prebuild, mac_bundle_depends): """Write out the Actions, Rules, and Copies steps. Return a path representing the outputs of these steps.""" outputs = [] if self.is_mac_bundle: mac_bundle_resources = spec.get('mac_bundle_resources', [])[:] else: mac_bundle_resources = [] extra_mac_bundle_resources = [] if 'actions' in spec: outputs += self.WriteActions(spec['actions'], extra_sources, prebuild, extra_mac_bundle_resources) if 'rules' in spec: outputs += self.WriteRules(spec['rules'], extra_sources, prebuild, mac_bundle_resources, extra_mac_bundle_resources) if 'copies' in spec: outputs += self.WriteCopies(spec['copies'], prebuild, mac_bundle_depends) if 'sources' in spec and self.flavor == 'win': outputs += self.WriteWinIdlFiles(spec, prebuild) stamp = self.WriteCollapsedDependencies('actions_rules_copies', outputs) if self.is_mac_bundle: xcassets = self.WriteMacBundleResources( extra_mac_bundle_resources + mac_bundle_resources, mac_bundle_depends) partial_info_plist = self.WriteMacXCassets(xcassets, mac_bundle_depends) self.WriteMacInfoPlist(partial_info_plist, mac_bundle_depends) return stamp def GenerateDescription(self, verb, message, fallback): """Generate and return a description of a build step. |verb| is the short summary, e.g. ACTION or RULE. |message| is a hand-written description, or None if not available. |fallback| is the gyp-level name of the step, usable as a fallback. """ if self.toolset != 'target': verb += '(%s)' % self.toolset if message: return '%s %s' % (verb, self.ExpandSpecial(message)) else: return '%s %s: %s' % (verb, self.name, fallback) def WriteActions(self, actions, extra_sources, prebuild, extra_mac_bundle_resources): # Actions cd into the base directory. env = self.GetToolchainEnv() all_outputs = [] for action in actions: # First write out a rule for the action. name = '%s_%s' % (action['action_name'], self.hash_for_rules) description = self.GenerateDescription('ACTION', action.get('message', None), name) is_cygwin = (self.msvs_settings.IsRuleRunUnderCygwin(action) if self.flavor == 'win' else False) args = action['action'] depfile = action.get('depfile', None) if depfile: depfile = self.ExpandSpecial(depfile, self.base_to_build) pool = 'console' if int(action.get('ninja_use_console', 0)) else None rule_name, _ = self.WriteNewNinjaRule(name, args, description, is_cygwin, env, pool, depfile=depfile) inputs = [self.GypPathToNinja(i, env) for i in action['inputs']] if int(action.get('process_outputs_as_sources', False)): extra_sources += action['outputs'] if int(action.get('process_outputs_as_mac_bundle_resources', False)): extra_mac_bundle_resources += action['outputs'] outputs = [self.GypPathToNinja(o, env) for o in action['outputs']] # Then write out an edge using the rule. self.ninja.build(outputs, rule_name, inputs, order_only=prebuild) all_outputs += outputs self.ninja.newline() return all_outputs def WriteRules(self, rules, extra_sources, prebuild, mac_bundle_resources, extra_mac_bundle_resources): env = self.GetToolchainEnv() all_outputs = [] for rule in rules: # Skip a rule with no action and no inputs. if 'action' not in rule and not rule.get('rule_sources', []): continue # First write out a rule for the rule action. name = '%s_%s' % (rule['rule_name'], self.hash_for_rules) args = rule['action'] description = self.GenerateDescription( 'RULE', rule.get('message', None), ('%s ' + generator_default_variables['RULE_INPUT_PATH']) % name) is_cygwin = (self.msvs_settings.IsRuleRunUnderCygwin(rule) if self.flavor == 'win' else False) pool = 'console' if int(rule.get('ninja_use_console', 0)) else None rule_name, args = self.WriteNewNinjaRule( name, args, description, is_cygwin, env, pool) # TODO: if the command references the outputs directly, we should # simplify it to just use $out. # Rules can potentially make use of some special variables which # must vary per source file. # Compute the list of variables we'll need to provide. special_locals = ('source', 'root', 'dirname', 'ext', 'name') needed_variables = set(['source']) for argument in args: for var in special_locals: if '${%s}' % var in argument: needed_variables.add(var) def cygwin_munge(path): # pylint: disable=cell-var-from-loop if is_cygwin: return path.replace('\\', '/') return path inputs = [self.GypPathToNinja(i, env) for i in rule.get('inputs', [])] # If there are n source files matching the rule, and m additional rule # inputs, then adding 'inputs' to each build edge written below will # write m * n inputs. Collapsing reduces this to m + n. sources = rule.get('rule_sources', []) num_inputs = len(inputs) if prebuild: num_inputs += 1 if num_inputs > 2 and len(sources) > 2: inputs = [self.WriteCollapsedDependencies( rule['rule_name'], inputs, order_only=prebuild)] prebuild = [] # For each source file, write an edge that generates all the outputs. for source in sources: source = os.path.normpath(source) dirname, basename = os.path.split(source) root, ext = os.path.splitext(basename) # Gather the list of inputs and outputs, expanding $vars if possible. outputs = [self.ExpandRuleVariables(o, root, dirname, source, ext, basename) for o in rule['outputs']] if int(rule.get('process_outputs_as_sources', False)): extra_sources += outputs was_mac_bundle_resource = source in mac_bundle_resources if was_mac_bundle_resource or \ int(rule.get('process_outputs_as_mac_bundle_resources', False)): extra_mac_bundle_resources += outputs # Note: This is n_resources * n_outputs_in_rule. Put to-be-removed # items in a set and remove them all in a single pass if this becomes # a performance issue. if was_mac_bundle_resource: mac_bundle_resources.remove(source) extra_bindings = [] for var in needed_variables: if var == 'root': extra_bindings.append(('root', cygwin_munge(root))) elif var == 'dirname': # '$dirname' is a parameter to the rule action, which means # it shouldn't be converted to a Ninja path. But we don't # want $!PRODUCT_DIR in there either. dirname_expanded = self.ExpandSpecial(dirname, self.base_to_build) extra_bindings.append(('dirname', cygwin_munge(dirname_expanded))) elif var == 'source': # '$source' is a parameter to the rule action, which means # it shouldn't be converted to a Ninja path. But we don't # want $!PRODUCT_DIR in there either. source_expanded = self.ExpandSpecial(source, self.base_to_build) extra_bindings.append(('source', cygwin_munge(source_expanded))) elif var == 'ext': extra_bindings.append(('ext', ext)) elif var == 'name': extra_bindings.append(('name', cygwin_munge(basename))) else: assert var == None, repr(var) outputs = [self.GypPathToNinja(o, env) for o in outputs] if self.flavor == 'win': # WriteNewNinjaRule uses unique_name for creating an rsp file on win. extra_bindings.append(('unique_name', hashlib.md5(outputs[0]).hexdigest())) self.ninja.build(outputs, rule_name, self.GypPathToNinja(source), implicit=inputs, order_only=prebuild, variables=extra_bindings) all_outputs.extend(outputs) return all_outputs def WriteCopies(self, copies, prebuild, mac_bundle_depends): outputs = [] env = self.GetToolchainEnv() for copy in copies: for path in copy['files']: # Normalize the path so trailing slashes don't confuse us. path = os.path.normpath(path) basename = os.path.split(path)[1] src = self.GypPathToNinja(path, env) dst = self.GypPathToNinja(os.path.join(copy['destination'], basename), env) outputs += self.ninja.build(dst, 'copy', src, order_only=prebuild) if self.is_mac_bundle: # gyp has mac_bundle_resources to copy things into a bundle's # Resources folder, but there's no built-in way to copy files to other # places in the bundle. Hence, some targets use copies for this. Check # if this file is copied into the current bundle, and if so add it to # the bundle depends so that dependent targets get rebuilt if the copy # input changes. if dst.startswith(self.xcode_settings.GetBundleContentsFolderPath()): mac_bundle_depends.append(dst) return outputs def WriteMacBundleResources(self, resources, bundle_depends): """Writes ninja edges for 'mac_bundle_resources'.""" xcassets = [] for output, res in gyp.xcode_emulation.GetMacBundleResources( generator_default_variables['PRODUCT_DIR'], self.xcode_settings, map(self.GypPathToNinja, resources)): output = self.ExpandSpecial(output) if os.path.splitext(output)[-1] != '.xcassets': isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name) self.ninja.build(output, 'mac_tool', res, variables=[('mactool_cmd', 'copy-bundle-resource'), \ ('binary', isBinary)]) bundle_depends.append(output) else: xcassets.append(res) return xcassets def WriteMacXCassets(self, xcassets, bundle_depends): """Writes ninja edges for 'mac_bundle_resources' .xcassets files. This add an invocation of 'actool' via the 'mac_tool.py' helper script. It assumes that the assets catalogs define at least one imageset and thus an Assets.car file will be generated in the application resources directory. If this is not the case, then the build will probably be done at each invocation of ninja.""" if not xcassets: return extra_arguments = {} settings_to_arg = { 'XCASSETS_APP_ICON': 'app-icon', 'XCASSETS_LAUNCH_IMAGE': 'launch-image', } settings = self.xcode_settings.xcode_settings[self.config_name] for settings_key, arg_name in settings_to_arg.iteritems(): value = settings.get(settings_key) if value: extra_arguments[arg_name] = value partial_info_plist = None if extra_arguments: partial_info_plist = self.GypPathToUniqueOutput( 'assetcatalog_generated_info.plist') extra_arguments['output-partial-info-plist'] = partial_info_plist outputs = [] outputs.append( os.path.join( self.xcode_settings.GetBundleResourceFolder(), 'Assets.car')) if partial_info_plist: outputs.append(partial_info_plist) keys = QuoteShellArgument(json.dumps(extra_arguments), self.flavor) extra_env = self.xcode_settings.GetPerTargetSettings() env = self.GetSortedXcodeEnv(additional_settings=extra_env) env = self.ComputeExportEnvString(env) bundle_depends.extend(self.ninja.build( outputs, 'compile_xcassets', xcassets, variables=[('env', env), ('keys', keys)])) return partial_info_plist def WriteMacInfoPlist(self, partial_info_plist, bundle_depends): """Write build rules for bundle Info.plist files.""" info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist( generator_default_variables['PRODUCT_DIR'], self.xcode_settings, self.GypPathToNinja) if not info_plist: return out = self.ExpandSpecial(out) if defines: # Create an intermediate file to store preprocessed results. intermediate_plist = self.GypPathToUniqueOutput( os.path.basename(info_plist)) defines = ' '.join([Define(d, self.flavor) for d in defines]) info_plist = self.ninja.build( intermediate_plist, 'preprocess_infoplist', info_plist, variables=[('defines',defines)]) env = self.GetSortedXcodeEnv(additional_settings=extra_env) env = self.ComputeExportEnvString(env) if partial_info_plist: intermediate_plist = self.GypPathToUniqueOutput('merged_info.plist') info_plist = self.ninja.build( intermediate_plist, 'merge_infoplist', [partial_info_plist, info_plist]) keys = self.xcode_settings.GetExtraPlistItems(self.config_name) keys = QuoteShellArgument(json.dumps(keys), self.flavor) isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name) self.ninja.build(out, 'copy_infoplist', info_plist, variables=[('env', env), ('keys', keys), ('binary', isBinary)]) bundle_depends.append(out) def WriteSources(self, ninja_file, config_name, config, sources, predepends, precompiled_header, spec): """Write build rules to compile all of |sources|.""" if self.toolset == 'host': self.ninja.variable('ar', '$ar_host') self.ninja.variable('cc', '$cc_host') self.ninja.variable('cxx', '$cxx_host') self.ninja.variable('ld', '$ld_host') self.ninja.variable('ldxx', '$ldxx_host') self.ninja.variable('nm', '$nm_host') self.ninja.variable('readelf', '$readelf_host') if self.flavor != 'mac' or len(self.archs) == 1: return self.WriteSourcesForArch( self.ninja, config_name, config, sources, predepends, precompiled_header, spec) else: return dict((arch, self.WriteSourcesForArch( self.arch_subninjas[arch], config_name, config, sources, predepends, precompiled_header, spec, arch=arch)) for arch in self.archs) def WriteSourcesForArch(self, ninja_file, config_name, config, sources, predepends, precompiled_header, spec, arch=None): """Write build rules to compile all of |sources|.""" extra_defines = [] if self.flavor == 'mac': cflags = self.xcode_settings.GetCflags(config_name, arch=arch) cflags_c = self.xcode_settings.GetCflagsC(config_name) cflags_cc = self.xcode_settings.GetCflagsCC(config_name) cflags_objc = ['$cflags_c'] + \ self.xcode_settings.GetCflagsObjC(config_name) cflags_objcc = ['$cflags_cc'] + \ self.xcode_settings.GetCflagsObjCC(config_name) elif self.flavor == 'win': asmflags = self.msvs_settings.GetAsmflags(config_name) cflags = self.msvs_settings.GetCflags(config_name) cflags_c = self.msvs_settings.GetCflagsC(config_name) cflags_cc = self.msvs_settings.GetCflagsCC(config_name) extra_defines = self.msvs_settings.GetComputedDefines(config_name) # See comment at cc_command for why there's two .pdb files. pdbpath_c = pdbpath_cc = self.msvs_settings.GetCompilerPdbName( config_name, self.ExpandSpecial) if not pdbpath_c: obj = 'obj' if self.toolset != 'target': obj += '.' + self.toolset pdbpath = os.path.normpath(os.path.join(obj, self.base_dir, self.name)) pdbpath_c = pdbpath + '.c.pdb' pdbpath_cc = pdbpath + '.cc.pdb' self.WriteVariableList(ninja_file, 'pdbname_c', [pdbpath_c]) self.WriteVariableList(ninja_file, 'pdbname_cc', [pdbpath_cc]) self.WriteVariableList(ninja_file, 'pchprefix', [self.name]) else: cflags = config.get('cflags', []) cflags_c = config.get('cflags_c', []) cflags_cc = config.get('cflags_cc', []) # Respect environment variables related to build, but target-specific # flags can still override them. if self.toolset == 'target': cflags_c = (os.environ.get('CPPFLAGS', '').split() + os.environ.get('CFLAGS', '').split() + cflags_c) cflags_cc = (os.environ.get('CPPFLAGS', '').split() + os.environ.get('CXXFLAGS', '').split() + cflags_cc) defines = config.get('defines', []) + extra_defines self.WriteVariableList(ninja_file, 'defines', [Define(d, self.flavor) for d in defines]) if self.flavor == 'win': self.WriteVariableList(ninja_file, 'asmflags', map(self.ExpandSpecial, asmflags)) self.WriteVariableList(ninja_file, 'rcflags', [QuoteShellArgument(self.ExpandSpecial(f), self.flavor) for f in self.msvs_settings.GetRcflags(config_name, self.GypPathToNinja)]) include_dirs = config.get('include_dirs', []) env = self.GetToolchainEnv() if self.flavor == 'win': include_dirs = self.msvs_settings.AdjustIncludeDirs(include_dirs, config_name) self.WriteVariableList(ninja_file, 'includes', [QuoteShellArgument('-I' + self.GypPathToNinja(i, env), self.flavor) for i in include_dirs]) if self.flavor == 'win': midl_include_dirs = config.get('midl_include_dirs', []) midl_include_dirs = self.msvs_settings.AdjustMidlIncludeDirs( midl_include_dirs, config_name) self.WriteVariableList(ninja_file, 'midl_includes', [QuoteShellArgument('-I' + self.GypPathToNinja(i, env), self.flavor) for i in midl_include_dirs]) pch_commands = precompiled_header.GetPchBuildCommands(arch) if self.flavor == 'mac': # Most targets use no precompiled headers, so only write these if needed. for ext, var in [('c', 'cflags_pch_c'), ('cc', 'cflags_pch_cc'), ('m', 'cflags_pch_objc'), ('mm', 'cflags_pch_objcc')]: include = precompiled_header.GetInclude(ext, arch) if include: ninja_file.variable(var, include) arflags = config.get('arflags', []) self.WriteVariableList(ninja_file, 'cflags', map(self.ExpandSpecial, cflags)) self.WriteVariableList(ninja_file, 'cflags_c', map(self.ExpandSpecial, cflags_c)) self.WriteVariableList(ninja_file, 'cflags_cc', map(self.ExpandSpecial, cflags_cc)) if self.flavor == 'mac': self.WriteVariableList(ninja_file, 'cflags_objc', map(self.ExpandSpecial, cflags_objc)) self.WriteVariableList(ninja_file, 'cflags_objcc', map(self.ExpandSpecial, cflags_objcc)) self.WriteVariableList(ninja_file, 'arflags', map(self.ExpandSpecial, arflags)) ninja_file.newline() outputs = [] has_rc_source = False for source in sources: filename, ext = os.path.splitext(source) ext = ext[1:] obj_ext = self.obj_ext if ext in ('cc', 'cpp', 'cxx'): command = 'cxx' self.uses_cpp = True elif ext == 'c' or (ext == 'S' and self.flavor != 'win'): command = 'cc' elif ext == 's' and self.flavor != 'win': # Doesn't generate .o.d files. command = 'cc_s' elif (self.flavor == 'win' and ext == 'asm' and not self.msvs_settings.HasExplicitAsmRules(spec)): command = 'asm' # Add the _asm suffix as msvs is capable of handling .cc and # .asm files of the same name without collision. obj_ext = '_asm.obj' elif self.flavor == 'mac' and ext == 'm': command = 'objc' elif self.flavor == 'mac' and ext == 'mm': command = 'objcxx' self.uses_cpp = True elif self.flavor == 'win' and ext == 'rc': command = 'rc' obj_ext = '.res' has_rc_source = True else: # Ignore unhandled extensions. continue input = self.GypPathToNinja(source) output = self.GypPathToUniqueOutput(filename + obj_ext) if arch is not None: output = AddArch(output, arch) implicit = precompiled_header.GetObjDependencies([input], [output], arch) variables = [] if self.flavor == 'win': variables, output, implicit = precompiled_header.GetFlagsModifications( input, output, implicit, command, cflags_c, cflags_cc, self.ExpandSpecial) ninja_file.build(output, command, input, implicit=[gch for _, _, gch in implicit], order_only=predepends, variables=variables) outputs.append(output) if has_rc_source: resource_include_dirs = config.get('resource_include_dirs', include_dirs) self.WriteVariableList(ninja_file, 'resource_includes', [QuoteShellArgument('-I' + self.GypPathToNinja(i, env), self.flavor) for i in resource_include_dirs]) self.WritePchTargets(ninja_file, pch_commands) ninja_file.newline() return outputs def WritePchTargets(self, ninja_file, pch_commands): """Writes ninja rules to compile prefix headers.""" if not pch_commands: return for gch, lang_flag, lang, input in pch_commands: var_name = { 'c': 'cflags_pch_c', 'cc': 'cflags_pch_cc', 'm': 'cflags_pch_objc', 'mm': 'cflags_pch_objcc', }[lang] map = { 'c': 'cc', 'cc': 'cxx', 'm': 'objc', 'mm': 'objcxx', } cmd = map.get(lang) ninja_file.build(gch, cmd, input, variables=[(var_name, lang_flag)]) def WriteLink(self, spec, config_name, config, link_deps): """Write out a link step. Fills out target.binary. """ if self.flavor != 'mac' or len(self.archs) == 1: return self.WriteLinkForArch( self.ninja, spec, config_name, config, link_deps) else: output = self.ComputeOutput(spec) inputs = [self.WriteLinkForArch(self.arch_subninjas[arch], spec, config_name, config, link_deps[arch], arch=arch) for arch in self.archs] extra_bindings = [] build_output = output if not self.is_mac_bundle: self.AppendPostbuildVariable(extra_bindings, spec, output, output) # TODO(yyanagisawa): more work needed to fix: # https://code.google.com/p/gyp/issues/detail?id=411 if (spec['type'] in ('shared_library', 'loadable_module') and not self.is_mac_bundle): extra_bindings.append(('lib', output)) self.ninja.build([output, output + '.TOC'], 'solipo', inputs, variables=extra_bindings) else: self.ninja.build(build_output, 'lipo', inputs, variables=extra_bindings) return output def WriteLinkForArch(self, ninja_file, spec, config_name, config, link_deps, arch=None): """Write out a link step. Fills out target.binary. """ command = { 'executable': 'link', 'loadable_module': 'solink_module', 'shared_library': 'solink', }[spec['type']] command_suffix = '' implicit_deps = set() solibs = set() if 'dependencies' in spec: # Two kinds of dependencies: # - Linkable dependencies (like a .a or a .so): add them to the link line. # - Non-linkable dependencies (like a rule that generates a file # and writes a stamp file): add them to implicit_deps extra_link_deps = set() for dep in spec['dependencies']: target = self.target_outputs.get(dep) if not target: continue linkable = target.Linkable() if linkable: new_deps = [] if (self.flavor == 'win' and target.component_objs and self.msvs_settings.IsUseLibraryDependencyInputs(config_name)): new_deps = target.component_objs elif self.flavor == 'win' and target.import_lib: new_deps = [target.import_lib] elif target.UsesToc(self.flavor): solibs.add(target.binary) implicit_deps.add(target.binary + '.TOC') else: new_deps = [target.binary] for new_dep in new_deps: if new_dep not in extra_link_deps: extra_link_deps.add(new_dep) link_deps.append(new_dep) final_output = target.FinalOutput() if not linkable or final_output != target.binary: implicit_deps.add(final_output) extra_bindings = [] if self.uses_cpp and self.flavor != 'win': extra_bindings.append(('ld', '$ldxx')) output = self.ComputeOutput(spec, arch) if arch is None and not self.is_mac_bundle: self.AppendPostbuildVariable(extra_bindings, spec, output, output) is_executable = spec['type'] == 'executable' # The ldflags config key is not used on mac or win. On those platforms # linker flags are set via xcode_settings and msvs_settings, respectively. env_ldflags = os.environ.get('LDFLAGS', '').split() if self.flavor == 'mac': ldflags = self.xcode_settings.GetLdflags(config_name, self.ExpandSpecial(generator_default_variables['PRODUCT_DIR']), self.GypPathToNinja, arch) ldflags = env_ldflags + ldflags elif self.flavor == 'win': manifest_base_name = self.GypPathToUniqueOutput( self.ComputeOutputFileName(spec)) ldflags, intermediate_manifest, manifest_files = \ self.msvs_settings.GetLdflags(config_name, self.GypPathToNinja, self.ExpandSpecial, manifest_base_name, output, is_executable, self.toplevel_build) ldflags = env_ldflags + ldflags self.WriteVariableList(ninja_file, 'manifests', manifest_files) implicit_deps = implicit_deps.union(manifest_files) if intermediate_manifest: self.WriteVariableList( ninja_file, 'intermediatemanifest', [intermediate_manifest]) command_suffix = _GetWinLinkRuleNameSuffix( self.msvs_settings.IsEmbedManifest(config_name)) def_file = self.msvs_settings.GetDefFile(self.GypPathToNinja) if def_file: implicit_deps.add(def_file) else: # Respect environment variables related to build, but target-specific # flags can still override them. ldflags = env_ldflags + config.get('ldflags', []) if is_executable and len(solibs): rpath = 'lib/' if self.toolset != 'target': rpath += self.toolset ldflags.append(r'-Wl,-rpath=\$$ORIGIN/%s' % rpath) ldflags.append('-Wl,-rpath-link=%s' % rpath) self.WriteVariableList(ninja_file, 'ldflags', gyp.common.uniquer(map(self.ExpandSpecial, ldflags))) library_dirs = config.get('library_dirs', []) if self.flavor == 'win': library_dirs = [self.msvs_settings.ConvertVSMacros(l, config_name) for l in library_dirs] library_dirs = ['/LIBPATH:' + QuoteShellArgument(self.GypPathToNinja(l), self.flavor) for l in library_dirs] else: library_dirs = [QuoteShellArgument('-L' + self.GypPathToNinja(l), self.flavor) for l in library_dirs] libraries = gyp.common.uniquer(map(self.ExpandSpecial, spec.get('libraries', []))) if self.flavor == 'mac': libraries = self.xcode_settings.AdjustLibraries(libraries, config_name) elif self.flavor == 'win': libraries = self.msvs_settings.AdjustLibraries(libraries) self.WriteVariableList(ninja_file, 'libs', library_dirs + libraries) linked_binary = output if command in ('solink', 'solink_module'): extra_bindings.append(('soname', os.path.split(output)[1])) extra_bindings.append(('lib', gyp.common.EncodePOSIXShellArgument(output))) if self.flavor != 'win': link_file_list = output if self.is_mac_bundle: # 'Dependency Framework.framework/Versions/A/Dependency Framework' -> # 'Dependency Framework.framework.rsp' link_file_list = self.xcode_settings.GetWrapperName() if arch: link_file_list += '.' + arch link_file_list += '.rsp' # If an rspfile contains spaces, ninja surrounds the filename with # quotes around it and then passes it to open(), creating a file with # quotes in its name (and when looking for the rsp file, the name # makes it through bash which strips the quotes) :-/ link_file_list = link_file_list.replace(' ', '_') extra_bindings.append( ('link_file_list', gyp.common.EncodePOSIXShellArgument(link_file_list))) if self.flavor == 'win': extra_bindings.append(('binary', output)) if ('/NOENTRY' not in ldflags and not self.msvs_settings.GetNoImportLibrary(config_name)): self.target.import_lib = output + '.lib' extra_bindings.append(('implibflag', '/IMPLIB:%s' % self.target.import_lib)) pdbname = self.msvs_settings.GetPDBName( config_name, self.ExpandSpecial, output + '.pdb') output = [output, self.target.import_lib] if pdbname: output.append(pdbname) elif not self.is_mac_bundle: output = [output, output + '.TOC'] else: command = command + '_notoc' elif self.flavor == 'win': extra_bindings.append(('binary', output)) pdbname = self.msvs_settings.GetPDBName( config_name, self.ExpandSpecial, output + '.pdb') if pdbname: output = [output, pdbname] if len(solibs): extra_bindings.append(('solibs', gyp.common.EncodePOSIXShellList(solibs))) ninja_file.build(output, command + command_suffix, link_deps, implicit=list(implicit_deps), variables=extra_bindings) return linked_binary def WriteTarget(self, spec, config_name, config, link_deps, compile_deps): extra_link_deps = any(self.target_outputs.get(dep).Linkable() for dep in spec.get('dependencies', []) if dep in self.target_outputs) if spec['type'] == 'none' or (not link_deps and not extra_link_deps): # TODO(evan): don't call this function for 'none' target types, as # it doesn't do anything, and we fake out a 'binary' with a stamp file. self.target.binary = compile_deps self.target.type = 'none' elif spec['type'] == 'static_library': self.target.binary = self.ComputeOutput(spec) if (self.flavor not in ('mac', 'openbsd', 'win') and not self.is_standalone_static_library): self.ninja.build(self.target.binary, 'alink_thin', link_deps, order_only=compile_deps) else: variables = [] if self.xcode_settings: libtool_flags = self.xcode_settings.GetLibtoolflags(config_name) if libtool_flags: variables.append(('libtool_flags', libtool_flags)) if self.msvs_settings: libflags = self.msvs_settings.GetLibFlags(config_name, self.GypPathToNinja) variables.append(('libflags', libflags)) if self.flavor != 'mac' or len(self.archs) == 1: self.AppendPostbuildVariable(variables, spec, self.target.binary, self.target.binary) self.ninja.build(self.target.binary, 'alink', link_deps, order_only=compile_deps, variables=variables) else: inputs = [] for arch in self.archs: output = self.ComputeOutput(spec, arch) self.arch_subninjas[arch].build(output, 'alink', link_deps[arch], order_only=compile_deps, variables=variables) inputs.append(output) # TODO: It's not clear if libtool_flags should be passed to the alink # call that combines single-arch .a files into a fat .a file. self.AppendPostbuildVariable(variables, spec, self.target.binary, self.target.binary) self.ninja.build(self.target.binary, 'alink', inputs, # FIXME: test proving order_only=compile_deps isn't # needed. variables=variables) else: self.target.binary = self.WriteLink(spec, config_name, config, link_deps) return self.target.binary def WriteMacBundle(self, spec, mac_bundle_depends, is_empty): assert self.is_mac_bundle package_framework = spec['type'] in ('shared_library', 'loadable_module') output = self.ComputeMacBundleOutput() if is_empty: output += '.stamp' variables = [] self.AppendPostbuildVariable(variables, spec, output, self.target.binary, is_command_start=not package_framework) if package_framework and not is_empty: variables.append(('version', self.xcode_settings.GetFrameworkVersion())) self.ninja.build(output, 'package_framework', mac_bundle_depends, variables=variables) else: self.ninja.build(output, 'stamp', mac_bundle_depends, variables=variables) self.target.bundle = output return output def GetToolchainEnv(self, additional_settings=None): """Returns the variables toolchain would set for build steps.""" env = self.GetSortedXcodeEnv(additional_settings=additional_settings) if self.flavor == 'win': env = self.GetMsvsToolchainEnv( additional_settings=additional_settings) return env def GetMsvsToolchainEnv(self, additional_settings=None): """Returns the variables Visual Studio would set for build steps.""" return self.msvs_settings.GetVSMacroEnv('$!PRODUCT_DIR', config=self.config_name) def GetSortedXcodeEnv(self, additional_settings=None): """Returns the variables Xcode would set for build steps.""" assert self.abs_build_dir abs_build_dir = self.abs_build_dir return gyp.xcode_emulation.GetSortedXcodeEnv( self.xcode_settings, abs_build_dir, os.path.join(abs_build_dir, self.build_to_base), self.config_name, additional_settings) def GetSortedXcodePostbuildEnv(self): """Returns the variables Xcode would set for postbuild steps.""" postbuild_settings = {} # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack. # TODO(thakis): It would be nice to have some general mechanism instead. strip_save_file = self.xcode_settings.GetPerTargetSetting( 'CHROMIUM_STRIP_SAVE_FILE') if strip_save_file: postbuild_settings['CHROMIUM_STRIP_SAVE_FILE'] = strip_save_file return self.GetSortedXcodeEnv(additional_settings=postbuild_settings) def AppendPostbuildVariable(self, variables, spec, output, binary, is_command_start=False): """Adds a 'postbuild' variable if there is a postbuild for |output|.""" postbuild = self.GetPostbuildCommand(spec, output, binary, is_command_start) if postbuild: variables.append(('postbuilds', postbuild)) def GetPostbuildCommand(self, spec, output, output_binary, is_command_start): """Returns a shell command that runs all the postbuilds, and removes |output| if any of them fails. If |is_command_start| is False, then the returned string will start with ' && '.""" if not self.xcode_settings or spec['type'] == 'none' or not output: return '' output = QuoteShellArgument(output, self.flavor) postbuilds = gyp.xcode_emulation.GetSpecPostbuildCommands(spec, quiet=True) if output_binary is not None: postbuilds = self.xcode_settings.AddImplicitPostbuilds( self.config_name, os.path.normpath(os.path.join(self.base_to_build, output)), QuoteShellArgument( os.path.normpath(os.path.join(self.base_to_build, output_binary)), self.flavor), postbuilds, quiet=True) if not postbuilds: return '' # Postbuilds expect to be run in the gyp file's directory, so insert an # implicit postbuild to cd to there. postbuilds.insert(0, gyp.common.EncodePOSIXShellList( ['cd', self.build_to_base])) env = self.ComputeExportEnvString(self.GetSortedXcodePostbuildEnv()) # G will be non-null if any postbuild fails. Run all postbuilds in a # subshell. commands = env + ' (' + \ ' && '.join([ninja_syntax.escape(command) for command in postbuilds]) command_string = (commands + '); G=$$?; ' # Remove the final output if any postbuild failed. '((exit $$G) || rm -rf %s) ' % output + '&& exit $$G)') if is_command_start: return '(' + command_string + ' && ' else: return '$ && (' + command_string def ComputeExportEnvString(self, env): """Given an environment, returns a string looking like 'export FOO=foo; export BAR="${FOO} bar;' that exports |env| to the shell.""" export_str = [] for k, v in env: export_str.append('export %s=%s;' % (k, ninja_syntax.escape(gyp.common.EncodePOSIXShellArgument(v)))) return ' '.join(export_str) def ComputeMacBundleOutput(self): """Return the 'output' (full output path) to a bundle output directory.""" assert self.is_mac_bundle path = generator_default_variables['PRODUCT_DIR'] return self.ExpandSpecial( os.path.join(path, self.xcode_settings.GetWrapperName())) def ComputeOutputFileName(self, spec, type=None): """Compute the filename of the final output for the current target.""" if not type: type = spec['type'] default_variables = copy.copy(generator_default_variables) CalculateVariables(default_variables, {'flavor': self.flavor}) # Compute filename prefix: the product prefix, or a default for # the product type. DEFAULT_PREFIX = { 'loadable_module': default_variables['SHARED_LIB_PREFIX'], 'shared_library': default_variables['SHARED_LIB_PREFIX'], 'static_library': default_variables['STATIC_LIB_PREFIX'], 'executable': default_variables['EXECUTABLE_PREFIX'], } prefix = spec.get('product_prefix', DEFAULT_PREFIX.get(type, '')) # Compute filename extension: the product extension, or a default # for the product type. DEFAULT_EXTENSION = { 'loadable_module': default_variables['SHARED_LIB_SUFFIX'], 'shared_library': default_variables['SHARED_LIB_SUFFIX'], 'static_library': default_variables['STATIC_LIB_SUFFIX'], 'executable': default_variables['EXECUTABLE_SUFFIX'], } extension = spec.get('product_extension') if extension: extension = '.' + extension else: extension = DEFAULT_EXTENSION.get(type, '') if 'product_name' in spec: # If we were given an explicit name, use that. target = spec['product_name'] else: # Otherwise, derive a name from the target name. target = spec['target_name'] if prefix == 'lib': # Snip out an extra 'lib' from libs if appropriate. target = StripPrefix(target, 'lib') if type in ('static_library', 'loadable_module', 'shared_library', 'executable'): return '%s%s%s' % (prefix, target, extension) elif type == 'none': return '%s.stamp' % target else: raise Exception('Unhandled output type %s' % type) def ComputeOutput(self, spec, arch=None): """Compute the path for the final output of the spec.""" type = spec['type'] if self.flavor == 'win': override = self.msvs_settings.GetOutputName(self.config_name, self.ExpandSpecial) if override: return override if arch is None and self.flavor == 'mac' and type in ( 'static_library', 'executable', 'shared_library', 'loadable_module'): filename = self.xcode_settings.GetExecutablePath() else: filename = self.ComputeOutputFileName(spec, type) if arch is None and 'product_dir' in spec: path = os.path.join(spec['product_dir'], filename) return self.ExpandSpecial(path) # Some products go into the output root, libraries go into shared library # dir, and everything else goes into the normal place. type_in_output_root = ['executable', 'loadable_module'] if self.flavor == 'mac' and self.toolset == 'target': type_in_output_root += ['shared_library', 'static_library'] elif self.flavor == 'win' and self.toolset == 'target': type_in_output_root += ['shared_library'] if arch is not None: # Make sure partial executables don't end up in a bundle or the regular # output directory. archdir = 'arch' if self.toolset != 'target': archdir = os.path.join('arch', '%s' % self.toolset) return os.path.join(archdir, AddArch(filename, arch)) elif type in type_in_output_root or self.is_standalone_static_library: return filename elif type == 'shared_library': libdir = 'lib' if self.toolset != 'target': libdir = os.path.join('lib', '%s' % self.toolset) return os.path.join(libdir, filename) else: return self.GypPathToUniqueOutput(filename, qualified=False) def WriteVariableList(self, ninja_file, var, values): assert not isinstance(values, str) if values is None: values = [] ninja_file.variable(var, ' '.join(values)) def WriteNewNinjaRule(self, name, args, description, is_cygwin, env, pool, depfile=None): """Write out a new ninja "rule" statement for a given command. Returns the name of the new rule, and a copy of |args| with variables expanded.""" if self.flavor == 'win': args = [self.msvs_settings.ConvertVSMacros( arg, self.base_to_build, config=self.config_name) for arg in args] description = self.msvs_settings.ConvertVSMacros( description, config=self.config_name) elif self.flavor == 'mac': # |env| is an empty list on non-mac. args = [gyp.xcode_emulation.ExpandEnvVars(arg, env) for arg in args] description = gyp.xcode_emulation.ExpandEnvVars(description, env) # TODO: we shouldn't need to qualify names; we do it because # currently the ninja rule namespace is global, but it really # should be scoped to the subninja. rule_name = self.name if self.toolset == 'target': rule_name += '.' + self.toolset rule_name += '.' + name rule_name = re.sub('[^a-zA-Z0-9_]', '_', rule_name) # Remove variable references, but not if they refer to the magic rule # variables. This is not quite right, as it also protects these for # actions, not just for rules where they are valid. Good enough. protect = [ '${root}', '${dirname}', '${source}', '${ext}', '${name}' ] protect = '(?!' + '|'.join(map(re.escape, protect)) + ')' description = re.sub(protect + r'\$', '_', description) # gyp dictates that commands are run from the base directory. # cd into the directory before running, and adjust paths in # the arguments to point to the proper locations. rspfile = None rspfile_content = None args = [self.ExpandSpecial(arg, self.base_to_build) for arg in args] if self.flavor == 'win': rspfile = rule_name + '.$unique_name.rsp' # The cygwin case handles this inside the bash sub-shell. run_in = '' if is_cygwin else ' ' + self.build_to_base if is_cygwin: rspfile_content = self.msvs_settings.BuildCygwinBashCommandLine( args, self.build_to_base) else: rspfile_content = gyp.msvs_emulation.EncodeRspFileList(args) command = ('%s gyp-win-tool action-wrapper $arch ' % sys.executable + rspfile + run_in) else: env = self.ComputeExportEnvString(env) command = gyp.common.EncodePOSIXShellList(args) command = 'cd %s; ' % self.build_to_base + env + command # GYP rules/actions express being no-ops by not touching their outputs. # Avoid executing downstream dependencies in this case by specifying # restat=1 to ninja. self.ninja.rule(rule_name, command, description, depfile=depfile, restat=True, pool=pool, rspfile=rspfile, rspfile_content=rspfile_content) self.ninja.newline() return rule_name, args def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" global generator_additional_non_configuration_keys global generator_additional_path_sections flavor = gyp.common.GetFlavor(params) if flavor == 'mac': default_variables.setdefault('OS', 'mac') default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib') default_variables.setdefault('SHARED_LIB_DIR', generator_default_variables['PRODUCT_DIR']) default_variables.setdefault('LIB_DIR', generator_default_variables['PRODUCT_DIR']) # Copy additional generator configuration data from Xcode, which is shared # by the Mac Ninja generator. import gyp.generator.xcode as xcode_generator generator_additional_non_configuration_keys = getattr(xcode_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(xcode_generator, 'generator_additional_path_sections', []) global generator_extra_sources_for_rules generator_extra_sources_for_rules = getattr(xcode_generator, 'generator_extra_sources_for_rules', []) elif flavor == 'win': exts = gyp.MSVSUtil.TARGET_TYPE_EXT default_variables.setdefault('OS', 'win') default_variables['EXECUTABLE_SUFFIX'] = '.' + exts['executable'] default_variables['STATIC_LIB_PREFIX'] = '' default_variables['STATIC_LIB_SUFFIX'] = '.' + exts['static_library'] default_variables['SHARED_LIB_PREFIX'] = '' default_variables['SHARED_LIB_SUFFIX'] = '.' + exts['shared_library'] # Copy additional generator configuration data from VS, which is shared # by the Windows Ninja generator. import gyp.generator.msvs as msvs_generator generator_additional_non_configuration_keys = getattr(msvs_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(msvs_generator, 'generator_additional_path_sections', []) gyp.msvs_emulation.CalculateCommonVariables(default_variables, params) else: operating_system = flavor if flavor == 'android': operating_system = 'linux' # Keep this legacy behavior for now. default_variables.setdefault('OS', operating_system) default_variables.setdefault('SHARED_LIB_SUFFIX', '.so') default_variables.setdefault('SHARED_LIB_DIR', os.path.join('$!PRODUCT_DIR', 'lib')) default_variables.setdefault('LIB_DIR', os.path.join('$!PRODUCT_DIR', 'obj')) def ComputeOutputDir(params): """Returns the path from the toplevel_dir to the build output directory.""" # generator_dir: relative path from pwd to where make puts build files. # Makes migrating from make to ninja easier, ninja doesn't put anything here. generator_dir = os.path.relpath(params['options'].generator_output or '.') # output_dir: relative path from generator_dir to the build directory. output_dir = params.get('generator_flags', {}).get('output_dir', 'out') # Relative path from source root to our output files. e.g. "out" return os.path.normpath(os.path.join(generator_dir, output_dir)) def CalculateGeneratorInputInfo(params): """Called by __init__ to initialize generator values based on params.""" # E.g. "out/gypfiles" toplevel = params['options'].toplevel_dir qualified_out_dir = os.path.normpath(os.path.join( toplevel, ComputeOutputDir(params), 'gypfiles')) global generator_filelist_paths generator_filelist_paths = { 'toplevel': toplevel, 'qualified_out_dir': qualified_out_dir, } def OpenOutput(path, mode='w'): """Open |path| for writing, creating directories if necessary.""" gyp.common.EnsureDirExists(path) return open(path, mode) def CommandWithWrapper(cmd, wrappers, prog): wrapper = wrappers.get(cmd, '') if wrapper: return wrapper + ' ' + prog return prog def GetDefaultConcurrentLinks(): """Returns a best-guess for a number of concurrent links.""" pool_size = int(os.getenv('GYP_LINK_CONCURRENCY', 0)) if pool_size: return pool_size if sys.platform in ('win32', 'cygwin'): import ctypes class MEMORYSTATUSEX(ctypes.Structure): _fields_ = [ ("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), ("sullAvailExtendedVirtual", ctypes.c_ulonglong), ] stat = MEMORYSTATUSEX() stat.dwLength = ctypes.sizeof(stat) ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)) mem_limit = max(1, stat.ullTotalPhys / (4 * (2 ** 30))) # total / 4GB hard_cap = max(1, int(os.getenv('GYP_LINK_CONCURRENCY_MAX', 2**32))) return min(mem_limit, hard_cap) elif sys.platform.startswith('linux'): if os.path.exists("/proc/meminfo"): with open("/proc/meminfo") as meminfo: memtotal_re = re.compile(r'^MemTotal:\s*(\d*)\s*kB') for line in meminfo: match = memtotal_re.match(line) if not match: continue # Allow 8Gb per link on Linux because Gold is quite memory hungry return max(1, int(match.group(1)) / (8 * (2 ** 20))) return 1 elif sys.platform == 'darwin': try: avail_bytes = int(subprocess.check_output(['sysctl', '-n', 'hw.memsize'])) # A static library debug build of Chromium's unit_tests takes ~2.7GB, so # 4GB per ld process allows for some more bloat. return max(1, avail_bytes / (4 * (2 ** 30))) # total / 4GB except: return 1 else: # TODO(scottmg): Implement this for other platforms. return 1 def _GetWinLinkRuleNameSuffix(embed_manifest): """Returns the suffix used to select an appropriate linking rule depending on whether the manifest embedding is enabled.""" return '_embed' if embed_manifest else '' def _AddWinLinkRules(master_ninja, embed_manifest): """Adds link rules for Windows platform to |master_ninja|.""" def FullLinkCommand(ldcmd, out, binary_type): resource_name = { 'exe': '1', 'dll': '2', }[binary_type] return '%(python)s gyp-win-tool link-with-manifests $arch %(embed)s ' \ '%(out)s "%(ldcmd)s" %(resname)s $mt $rc "$intermediatemanifest" ' \ '$manifests' % { 'python': sys.executable, 'out': out, 'ldcmd': ldcmd, 'resname': resource_name, 'embed': embed_manifest } rule_name_suffix = _GetWinLinkRuleNameSuffix(embed_manifest) use_separate_mspdbsrv = ( int(os.environ.get('GYP_USE_SEPARATE_MSPDBSRV', '0')) != 0) dlldesc = 'LINK%s(DLL) $binary' % rule_name_suffix.upper() dllcmd = ('%s gyp-win-tool link-wrapper $arch %s ' '$ld /nologo $implibflag /DLL /OUT:$binary ' '@$binary.rsp' % (sys.executable, use_separate_mspdbsrv)) dllcmd = FullLinkCommand(dllcmd, '$binary', 'dll') master_ninja.rule('solink' + rule_name_suffix, description=dlldesc, command=dllcmd, rspfile='$binary.rsp', rspfile_content='$libs $in_newline $ldflags', restat=True, pool='link_pool') master_ninja.rule('solink_module' + rule_name_suffix, description=dlldesc, command=dllcmd, rspfile='$binary.rsp', rspfile_content='$libs $in_newline $ldflags', restat=True, pool='link_pool') # Note that ldflags goes at the end so that it has the option of # overriding default settings earlier in the command line. exe_cmd = ('%s gyp-win-tool link-wrapper $arch %s ' '$ld /nologo /OUT:$binary @$binary.rsp' % (sys.executable, use_separate_mspdbsrv)) exe_cmd = FullLinkCommand(exe_cmd, '$binary', 'exe') master_ninja.rule('link' + rule_name_suffix, description='LINK%s $binary' % rule_name_suffix.upper(), command=exe_cmd, rspfile='$binary.rsp', rspfile_content='$in_newline $libs $ldflags', pool='link_pool') def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name): options = params['options'] flavor = gyp.common.GetFlavor(params) generator_flags = params.get('generator_flags', {}) # build_dir: relative path from source root to our output files. # e.g. "out/Debug" build_dir = os.path.normpath( os.path.join(ComputeOutputDir(params), config_name)) toplevel_build = os.path.join(options.toplevel_dir, build_dir) master_ninja_file = OpenOutput(os.path.join(toplevel_build, 'build.ninja')) master_ninja = ninja_syntax.Writer(master_ninja_file, width=120) # Put build-time support tools in out/{config_name}. gyp.common.CopyTool(flavor, toplevel_build) # Grab make settings for CC/CXX. # The rules are # - The priority from low to high is gcc/g++, the 'make_global_settings' in # gyp, the environment variable. # - If there is no 'make_global_settings' for CC.host/CXX.host or # 'CC_host'/'CXX_host' enviroment variable, cc_host/cxx_host should be set # to cc/cxx. if flavor == 'win': ar = 'lib.exe' # cc and cxx must be set to the correct architecture by overriding with one # of cl_x86 or cl_x64 below. cc = 'UNSET' cxx = 'UNSET' ld = 'link.exe' ld_host = '$ld' else: ar = 'ar' cc = 'cc' cxx = 'c++' ld = '$cc' ldxx = '$cxx' ld_host = '$cc_host' ldxx_host = '$cxx_host' ar_host = 'ar' cc_host = None cxx_host = None cc_host_global_setting = None cxx_host_global_setting = None clang_cl = None nm = 'nm' nm_host = 'nm' readelf = 'readelf' readelf_host = 'readelf' build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0]) make_global_settings = data[build_file].get('make_global_settings', []) build_to_root = gyp.common.InvertRelativePath(build_dir, options.toplevel_dir) wrappers = {} for key, value in make_global_settings: if key == 'AR': ar = os.path.join(build_to_root, value) if key == 'AR.host': ar_host = os.path.join(build_to_root, value) if key == 'CC': cc = os.path.join(build_to_root, value) if cc.endswith('clang-cl'): clang_cl = cc if key == 'CXX': cxx = os.path.join(build_to_root, value) if key == 'CC.host': cc_host = os.path.join(build_to_root, value) cc_host_global_setting = value if key == 'CXX.host': cxx_host = os.path.join(build_to_root, value) cxx_host_global_setting = value if key == 'LD': ld = os.path.join(build_to_root, value) if key == 'LD.host': ld_host = os.path.join(build_to_root, value) if key == 'NM': nm = os.path.join(build_to_root, value) if key == 'NM.host': nm_host = os.path.join(build_to_root, value) if key == 'READELF': readelf = os.path.join(build_to_root, value) if key == 'READELF.host': readelf_host = os.path.join(build_to_root, value) if key.endswith('_wrapper'): wrappers[key[:-len('_wrapper')]] = os.path.join(build_to_root, value) # Support wrappers from environment variables too. for key, value in os.environ.iteritems(): if key.lower().endswith('_wrapper'): key_prefix = key[:-len('_wrapper')] key_prefix = re.sub(r'\.HOST$', '.host', key_prefix) wrappers[key_prefix] = os.path.join(build_to_root, value) if flavor == 'win': configs = [target_dicts[qualified_target]['configurations'][config_name] for qualified_target in target_list] shared_system_includes = None if not generator_flags.get('ninja_use_custom_environment_files', 0): shared_system_includes = \ gyp.msvs_emulation.ExtractSharedMSVSSystemIncludes( configs, generator_flags) cl_paths = gyp.msvs_emulation.GenerateEnvironmentFiles( toplevel_build, generator_flags, shared_system_includes, OpenOutput) for arch, path in cl_paths.iteritems(): if clang_cl: # If we have selected clang-cl, use that instead. path = clang_cl command = CommandWithWrapper('CC', wrappers, QuoteShellArgument(path, 'win')) if clang_cl: # Use clang-cl to cross-compile for x86 or x86_64. command += (' -m32' if arch == 'x86' else ' -m64') master_ninja.variable('cl_' + arch, command) cc = GetEnvironFallback(['CC_target', 'CC'], cc) master_ninja.variable('cc', CommandWithWrapper('CC', wrappers, cc)) cxx = GetEnvironFallback(['CXX_target', 'CXX'], cxx) master_ninja.variable('cxx', CommandWithWrapper('CXX', wrappers, cxx)) if flavor == 'win': master_ninja.variable('ld', ld) master_ninja.variable('idl', 'midl.exe') master_ninja.variable('ar', ar) master_ninja.variable('rc', 'rc.exe') master_ninja.variable('ml_x86', 'ml.exe') master_ninja.variable('ml_x64', 'ml64.exe') master_ninja.variable('mt', 'mt.exe') else: master_ninja.variable('ld', CommandWithWrapper('LINK', wrappers, ld)) master_ninja.variable('ldxx', CommandWithWrapper('LINK', wrappers, ldxx)) master_ninja.variable('ar', GetEnvironFallback(['AR_target', 'AR'], ar)) if flavor != 'mac': # Mac does not use readelf/nm for .TOC generation, so avoiding polluting # the master ninja with extra unused variables. master_ninja.variable( 'nm', GetEnvironFallback(['NM_target', 'NM'], nm)) master_ninja.variable( 'readelf', GetEnvironFallback(['READELF_target', 'READELF'], readelf)) if generator_supports_multiple_toolsets: if not cc_host: cc_host = cc if not cxx_host: cxx_host = cxx master_ninja.variable('ar_host', GetEnvironFallback(['AR_host'], ar_host)) master_ninja.variable('nm_host', GetEnvironFallback(['NM_host'], nm_host)) master_ninja.variable('readelf_host', GetEnvironFallback(['READELF_host'], readelf_host)) cc_host = GetEnvironFallback(['CC_host'], cc_host) cxx_host = GetEnvironFallback(['CXX_host'], cxx_host) # The environment variable could be used in 'make_global_settings', like # ['CC.host', '$(CC)'] or ['CXX.host', '$(CXX)'], transform them here. if '$(CC)' in cc_host and cc_host_global_setting: cc_host = cc_host_global_setting.replace('$(CC)', cc) if '$(CXX)' in cxx_host and cxx_host_global_setting: cxx_host = cxx_host_global_setting.replace('$(CXX)', cxx) master_ninja.variable('cc_host', CommandWithWrapper('CC.host', wrappers, cc_host)) master_ninja.variable('cxx_host', CommandWithWrapper('CXX.host', wrappers, cxx_host)) if flavor == 'win': master_ninja.variable('ld_host', ld_host) else: master_ninja.variable('ld_host', CommandWithWrapper( 'LINK', wrappers, ld_host)) master_ninja.variable('ldxx_host', CommandWithWrapper( 'LINK', wrappers, ldxx_host)) master_ninja.newline() master_ninja.pool('link_pool', depth=GetDefaultConcurrentLinks()) master_ninja.newline() deps = 'msvc' if flavor == 'win' else 'gcc' if flavor != 'win': master_ninja.rule( 'cc', description='CC $out', command=('$cc -MMD -MF $out.d $defines $includes $cflags $cflags_c ' '$cflags_pch_c -c $in -o $out'), depfile='$out.d', deps=deps) master_ninja.rule( 'cc_s', description='CC $out', command=('$cc $defines $includes $cflags $cflags_c ' '$cflags_pch_c -c $in -o $out')) master_ninja.rule( 'cxx', description='CXX $out', command=('$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_cc ' '$cflags_pch_cc -c $in -o $out'), depfile='$out.d', deps=deps) else: # TODO(scottmg) Separate pdb names is a test to see if it works around # http://crbug.com/142362. It seems there's a race between the creation of # the .pdb by the precompiled header step for .cc and the compilation of # .c files. This should be handled by mspdbsrv, but rarely errors out with # c1xx : fatal error C1033: cannot open program database # By making the rules target separate pdb files this might be avoided. cc_command = ('ninja -t msvc -e $arch ' + '-- ' '$cc /nologo /showIncludes /FC ' '@$out.rsp /c $in /Fo$out /Fd$pdbname_c ') cxx_command = ('ninja -t msvc -e $arch ' + '-- ' '$cxx /nologo /showIncludes /FC ' '@$out.rsp /c $in /Fo$out /Fd$pdbname_cc ') master_ninja.rule( 'cc', description='CC $out', command=cc_command, rspfile='$out.rsp', rspfile_content='$defines $includes $cflags $cflags_c', deps=deps) master_ninja.rule( 'cxx', description='CXX $out', command=cxx_command, rspfile='$out.rsp', rspfile_content='$defines $includes $cflags $cflags_cc', deps=deps) master_ninja.rule( 'idl', description='IDL $in', command=('%s gyp-win-tool midl-wrapper $arch $outdir ' '$tlb $h $dlldata $iid $proxy $in ' '$midl_includes $idlflags' % sys.executable)) master_ninja.rule( 'rc', description='RC $in', # Note: $in must be last otherwise rc.exe complains. command=('%s gyp-win-tool rc-wrapper ' '$arch $rc $defines $resource_includes $rcflags /fo$out $in' % sys.executable)) master_ninja.rule( 'asm', description='ASM $out', command=('%s gyp-win-tool asm-wrapper ' '$arch $asm $defines $includes $asmflags /c /Fo $out $in' % sys.executable)) if flavor != 'mac' and flavor != 'win': master_ninja.rule( 'alink', description='AR $out', command='rm -f $out && $ar rcs $arflags $out $in') master_ninja.rule( 'alink_thin', description='AR $out', command='rm -f $out && $ar rcsT $arflags $out $in') # This allows targets that only need to depend on $lib's API to declare an # order-only dependency on $lib.TOC and avoid relinking such downstream # dependencies when $lib changes only in non-public ways. # The resulting string leaves an uninterpolated %{suffix} which # is used in the final substitution below. mtime_preserving_solink_base = ( 'if [ ! -e $lib -o ! -e $lib.TOC ]; then ' '%(solink)s && %(extract_toc)s > $lib.TOC; else ' '%(solink)s && %(extract_toc)s > $lib.tmp && ' 'if ! cmp -s $lib.tmp $lib.TOC; then mv $lib.tmp $lib.TOC ; ' 'fi; fi' % { 'solink': '$ld -shared $ldflags -o $lib -Wl,-soname=$soname %(suffix)s', 'extract_toc': ('{ $readelf -d $lib | grep SONAME ; ' '$nm -gD -f p $lib | cut -f1-2 -d\' \'; }')}) master_ninja.rule( 'solink', description='SOLINK $lib', restat=True, command=mtime_preserving_solink_base % {'suffix': '@$link_file_list'}, rspfile='$link_file_list', rspfile_content= '-Wl,--whole-archive $in $solibs -Wl,--no-whole-archive $libs', pool='link_pool') master_ninja.rule( 'solink_module', description='SOLINK(module) $lib', restat=True, command=mtime_preserving_solink_base % {'suffix': '@$link_file_list'}, rspfile='$link_file_list', rspfile_content='-Wl,--start-group $in -Wl,--end-group $solibs $libs', pool='link_pool') master_ninja.rule( 'link', description='LINK $out', command=('$ld $ldflags -o $out ' '-Wl,--start-group $in -Wl,--end-group $solibs $libs'), pool='link_pool') elif flavor == 'win': master_ninja.rule( 'alink', description='LIB $out', command=('%s gyp-win-tool link-wrapper $arch False ' '$ar /nologo /ignore:4221 /OUT:$out @$out.rsp' % sys.executable), rspfile='$out.rsp', rspfile_content='$in_newline $libflags') _AddWinLinkRules(master_ninja, embed_manifest=True) _AddWinLinkRules(master_ninja, embed_manifest=False) else: master_ninja.rule( 'objc', description='OBJC $out', command=('$cc -MMD -MF $out.d $defines $includes $cflags $cflags_objc ' '$cflags_pch_objc -c $in -o $out'), depfile='$out.d', deps=deps) master_ninja.rule( 'objcxx', description='OBJCXX $out', command=('$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_objcc ' '$cflags_pch_objcc -c $in -o $out'), depfile='$out.d', deps=deps) master_ninja.rule( 'alink', description='LIBTOOL-STATIC $out, POSTBUILDS', command='rm -f $out && ' './gyp-mac-tool filter-libtool libtool $libtool_flags ' '-static -o $out $in' '$postbuilds') master_ninja.rule( 'lipo', description='LIPO $out, POSTBUILDS', command='rm -f $out && lipo -create $in -output $out$postbuilds') master_ninja.rule( 'solipo', description='SOLIPO $out, POSTBUILDS', command=( 'rm -f $lib $lib.TOC && lipo -create $in -output $lib$postbuilds &&' '%(extract_toc)s > $lib.TOC' % { 'extract_toc': '{ otool -l $lib | grep LC_ID_DYLIB -A 5; ' 'nm -gP $lib | cut -f1-2 -d\' \' | grep -v U$$; true; }'})) # Record the public interface of $lib in $lib.TOC. See the corresponding # comment in the posix section above for details. solink_base = '$ld %(type)s $ldflags -o $lib %(suffix)s' mtime_preserving_solink_base = ( 'if [ ! -e $lib -o ! -e $lib.TOC ] || ' # Always force dependent targets to relink if this library # reexports something. Handling this correctly would require # recursive TOC dumping but this is rare in practice, so punt. 'otool -l $lib | grep -q LC_REEXPORT_DYLIB ; then ' '%(solink)s && %(extract_toc)s > $lib.TOC; ' 'else ' '%(solink)s && %(extract_toc)s > $lib.tmp && ' 'if ! cmp -s $lib.tmp $lib.TOC; then ' 'mv $lib.tmp $lib.TOC ; ' 'fi; ' 'fi' % { 'solink': solink_base, 'extract_toc': '{ otool -l $lib | grep LC_ID_DYLIB -A 5; ' 'nm -gP $lib | cut -f1-2 -d\' \' | grep -v U$$; true; }'}) solink_suffix = '@$link_file_list$postbuilds' master_ninja.rule( 'solink', description='SOLINK $lib, POSTBUILDS', restat=True, command=mtime_preserving_solink_base % {'suffix': solink_suffix, 'type': '-shared'}, rspfile='$link_file_list', rspfile_content='$in $solibs $libs', pool='link_pool') master_ninja.rule( 'solink_notoc', description='SOLINK $lib, POSTBUILDS', restat=True, command=solink_base % {'suffix':solink_suffix, 'type': '-shared'}, rspfile='$link_file_list', rspfile_content='$in $solibs $libs', pool='link_pool') master_ninja.rule( 'solink_module', description='SOLINK(module) $lib, POSTBUILDS', restat=True, command=mtime_preserving_solink_base % {'suffix': solink_suffix, 'type': '-bundle'}, rspfile='$link_file_list', rspfile_content='$in $solibs $libs', pool='link_pool') master_ninja.rule( 'solink_module_notoc', description='SOLINK(module) $lib, POSTBUILDS', restat=True, command=solink_base % {'suffix': solink_suffix, 'type': '-bundle'}, rspfile='$link_file_list', rspfile_content='$in $solibs $libs', pool='link_pool') master_ninja.rule( 'link', description='LINK $out, POSTBUILDS', command=('$ld $ldflags -o $out ' '$in $solibs $libs$postbuilds'), pool='link_pool') master_ninja.rule( 'preprocess_infoplist', description='PREPROCESS INFOPLIST $out', command=('$cc -E -P -Wno-trigraphs -x c $defines $in -o $out && ' 'plutil -convert xml1 $out $out')) master_ninja.rule( 'copy_infoplist', description='COPY INFOPLIST $in', command='$env ./gyp-mac-tool copy-info-plist $in $out $binary $keys') master_ninja.rule( 'merge_infoplist', description='MERGE INFOPLISTS $in', command='$env ./gyp-mac-tool merge-info-plist $out $in') master_ninja.rule( 'compile_xcassets', description='COMPILE XCASSETS $in', command='$env ./gyp-mac-tool compile-xcassets $keys $in') master_ninja.rule( 'mac_tool', description='MACTOOL $mactool_cmd $in', command='$env ./gyp-mac-tool $mactool_cmd $in $out $binary') master_ninja.rule( 'package_framework', description='PACKAGE FRAMEWORK $out, POSTBUILDS', command='./gyp-mac-tool package-framework $out $version$postbuilds ' '&& touch $out') if flavor == 'win': master_ninja.rule( 'stamp', description='STAMP $out', command='%s gyp-win-tool stamp $out' % sys.executable) master_ninja.rule( 'copy', description='COPY $in $out', command='%s gyp-win-tool recursive-mirror $in $out' % sys.executable) else: master_ninja.rule( 'stamp', description='STAMP $out', command='${postbuilds}touch $out') master_ninja.rule( 'copy', description='COPY $in $out', command='rm -rf $out && cp -af $in $out') master_ninja.newline() all_targets = set() for build_file in params['build_files']: for target in gyp.common.AllTargets(target_list, target_dicts, os.path.normpath(build_file)): all_targets.add(target) all_outputs = set() # target_outputs is a map from qualified target name to a Target object. target_outputs = {} # target_short_names is a map from target short name to a list of Target # objects. target_short_names = {} # short name of targets that were skipped because they didn't contain anything # interesting. # NOTE: there may be overlap between this an non_empty_target_names. empty_target_names = set() # Set of non-empty short target names. # NOTE: there may be overlap between this an empty_target_names. non_empty_target_names = set() for qualified_target in target_list: # qualified_target is like: third_party/icu/icu.gyp:icui18n#target build_file, name, toolset = \ gyp.common.ParseQualifiedTarget(qualified_target) this_make_global_settings = data[build_file].get('make_global_settings', []) assert make_global_settings == this_make_global_settings, ( "make_global_settings needs to be the same for all targets. %s vs. %s" % (this_make_global_settings, make_global_settings)) spec = target_dicts[qualified_target] if flavor == 'mac': gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec) build_file = gyp.common.RelativePath(build_file, options.toplevel_dir) qualified_target_for_hash = gyp.common.QualifiedTarget(build_file, name, toolset) hash_for_rules = hashlib.md5(qualified_target_for_hash).hexdigest() base_path = os.path.dirname(build_file) obj = 'obj' if toolset != 'target': obj += '.' + toolset output_file = os.path.join(obj, base_path, name + '.ninja') ninja_output = StringIO() writer = NinjaWriter(hash_for_rules, target_outputs, base_path, build_dir, ninja_output, toplevel_build, output_file, flavor, toplevel_dir=options.toplevel_dir) target = writer.WriteSpec(spec, config_name, generator_flags) if ninja_output.tell() > 0: # Only create files for ninja files that actually have contents. with OpenOutput(os.path.join(toplevel_build, output_file)) as ninja_file: ninja_file.write(ninja_output.getvalue()) ninja_output.close() master_ninja.subninja(output_file) if target: if name != target.FinalOutput() and spec['toolset'] == 'target': target_short_names.setdefault(name, []).append(target) target_outputs[qualified_target] = target if qualified_target in all_targets: all_outputs.add(target.FinalOutput()) non_empty_target_names.add(name) else: empty_target_names.add(name) if target_short_names: # Write a short name to build this target. This benefits both the # "build chrome" case as well as the gyp tests, which expect to be # able to run actions and build libraries by their short name. master_ninja.newline() master_ninja.comment('Short names for targets.') for short_name in target_short_names: master_ninja.build(short_name, 'phony', [x.FinalOutput() for x in target_short_names[short_name]]) # Write phony targets for any empty targets that weren't written yet. As # short names are not necessarily unique only do this for short names that # haven't already been output for another target. empty_target_names = empty_target_names - non_empty_target_names if empty_target_names: master_ninja.newline() master_ninja.comment('Empty targets (output for completeness).') for name in sorted(empty_target_names): master_ninja.build(name, 'phony') if all_outputs: master_ninja.newline() master_ninja.build('all', 'phony', list(all_outputs)) master_ninja.default(generator_flags.get('default_target', 'all')) master_ninja_file.close() def PerformBuild(data, configurations, params): options = params['options'] for config in configurations: builddir = os.path.join(options.toplevel_dir, 'out', config) arguments = ['ninja', '-C', builddir] print 'Building [%s]: %s' % (config, arguments) subprocess.check_call(arguments) def CallGenerateOutputForConfig(arglist): # Ignore the interrupt signal so that the parent process catches it and # kills all multiprocessing children. signal.signal(signal.SIGINT, signal.SIG_IGN) (target_list, target_dicts, data, params, config_name) = arglist GenerateOutputForConfig(target_list, target_dicts, data, params, config_name) def GenerateOutput(target_list, target_dicts, data, params): # Update target_dicts for iOS device builds. target_dicts = gyp.xcode_emulation.CloneConfigurationForDeviceAndEmulator( target_dicts) user_config = params.get('generator_flags', {}).get('config', None) if gyp.common.GetFlavor(params) == 'win': target_list, target_dicts = MSVSUtil.ShardTargets(target_list, target_dicts) target_list, target_dicts = MSVSUtil.InsertLargePdbShims( target_list, target_dicts, generator_default_variables) if user_config: GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: config_names = target_dicts[target_list[0]]['configurations'].keys() if params['parallel']: try: pool = multiprocessing.Pool(len(config_names)) arglists = [] for config_name in config_names: arglists.append( (target_list, target_dicts, data, params, config_name)) pool.map(CallGenerateOutputForConfig, arglists) except KeyboardInterrupt, e: pool.terminate() raise e else: for config_name in config_names: GenerateOutputForConfig(target_list, target_dicts, data, params, config_name)
mit
2014c2g2/2014c2
wsgi/static/Brython2.1.0-20140419-113919/Lib/inspect.py
91
78882
"""Get useful information from live Python objects. This module encapsulates the interface provided by the internal special attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion. It also provides some help for examining source code and class layout. Here are some of the useful functions provided by this module: ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(), isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(), isroutine() - check object types getmembers() - get members of an object that satisfy a given condition getfile(), getsourcefile(), getsource() - find an object's source code getdoc(), getcomments() - get documentation on an object getmodule() - determine the module that an object came from getclasstree() - arrange classes so as to represent their hierarchy getargspec(), getargvalues(), getcallargs() - get info about function arguments getfullargspec() - same, with support for Python-3000 features formatargspec(), formatargvalues() - format an argument spec getouterframes(), getinnerframes() - get info about frames currentframe() - get the current stack frame stack(), trace() - get info about frames on the stack or in a traceback signature() - get a Signature object for the callable """ # This module is in the public domain. No warranties. __author__ = ('Ka-Ping Yee <[email protected]>', 'Yury Selivanov <[email protected]>') import imp import importlib.machinery import itertools import linecache import os import re import sys import tokenize import types import warnings import functools import builtins from operator import attrgetter from collections import namedtuple, OrderedDict # Create constants for the compiler flags in Include/code.h # We try to get them from dis to avoid duplication, but fall # back to hardcoding so the dependency is optional try: from dis import COMPILER_FLAG_NAMES as _flag_names except ImportError: CO_OPTIMIZED, CO_NEWLOCALS = 0x1, 0x2 CO_VARARGS, CO_VARKEYWORDS = 0x4, 0x8 CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40 else: mod_dict = globals() for k, v in _flag_names.items(): mod_dict["CO_" + v] = k # See Include/object.h TPFLAGS_IS_ABSTRACT = 1 << 20 # ----------------------------------------------------------- type-checking def ismodule(object): """Return true if the object is a module. Module objects provide these attributes: __cached__ pathname to byte compiled file __doc__ documentation string __file__ filename (missing for built-in modules)""" return isinstance(object, types.ModuleType) def isclass(object): """Return true if the object is a class. Class objects provide these attributes: __doc__ documentation string __module__ name of module in which this class was defined""" return isinstance(object, type) def ismethod(object): """Return true if the object is an instance method. Instance method objects provide these attributes: __doc__ documentation string __name__ name with which this method was defined __func__ function object containing implementation of method __self__ instance to which this method is bound""" return isinstance(object, types.MethodType) def ismethoddescriptor(object): """Return true if the object is a method descriptor. But not if ismethod() or isclass() or isfunction() are true. This is new in Python 2.2, and, for example, is true of int.__add__. An object passing this test has a __get__ attribute but not a __set__ attribute, but beyond that the set of attributes varies. __name__ is usually sensible, and __doc__ often is. Methods implemented via descriptors that also pass one of the other tests return false from the ismethoddescriptor() test, simply because the other tests promise more -- you can, e.g., count on having the __func__ attribute (etc) when an object passes ismethod().""" if isclass(object) or ismethod(object) or isfunction(object): # mutual exclusion return False tp = type(object) return hasattr(tp, "__get__") and not hasattr(tp, "__set__") def isdatadescriptor(object): """Return true if the object is a data descriptor. Data descriptors have both a __get__ and a __set__ attribute. Examples are properties (defined in Python) and getsets and members (defined in C). Typically, data descriptors will also have __name__ and __doc__ attributes (properties, getsets, and members have both of these attributes), but this is not guaranteed.""" if isclass(object) or ismethod(object) or isfunction(object): # mutual exclusion return False tp = type(object) return hasattr(tp, "__set__") and hasattr(tp, "__get__") if hasattr(types, 'MemberDescriptorType'): # CPython and equivalent def ismemberdescriptor(object): """Return true if the object is a member descriptor. Member descriptors are specialized descriptors defined in extension modules.""" return isinstance(object, types.MemberDescriptorType) else: # Other implementations def ismemberdescriptor(object): """Return true if the object is a member descriptor. Member descriptors are specialized descriptors defined in extension modules.""" return False if hasattr(types, 'GetSetDescriptorType'): # CPython and equivalent def isgetsetdescriptor(object): """Return true if the object is a getset descriptor. getset descriptors are specialized descriptors defined in extension modules.""" return isinstance(object, types.GetSetDescriptorType) else: # Other implementations def isgetsetdescriptor(object): """Return true if the object is a getset descriptor. getset descriptors are specialized descriptors defined in extension modules.""" return False def isfunction(object): """Return true if the object is a user-defined function. Function objects provide these attributes: __doc__ documentation string __name__ name with which this function was defined __code__ code object containing compiled function bytecode __defaults__ tuple of any default values for arguments __globals__ global namespace in which this function was defined __annotations__ dict of parameter annotations __kwdefaults__ dict of keyword only parameters with defaults""" return isinstance(object, types.FunctionType) def isgeneratorfunction(object): """Return true if the object is a user-defined generator function. Generator function objects provides same attributes as functions. See help(isfunction) for attributes listing.""" return bool((isfunction(object) or ismethod(object)) and object.__code__.co_flags & CO_GENERATOR) def isgenerator(object): """Return true if the object is a generator. Generator objects provide these attributes: __iter__ defined to support iteration over container close raises a new GeneratorExit exception inside the generator to terminate the iteration gi_code code object gi_frame frame object or possibly None once the generator has been exhausted gi_running set to 1 when generator is executing, 0 otherwise next return the next item from the container send resumes the generator and "sends" a value that becomes the result of the current yield-expression throw used to raise an exception inside the generator""" return isinstance(object, types.GeneratorType) def istraceback(object): """Return true if the object is a traceback. Traceback objects provide these attributes: tb_frame frame object at this level tb_lasti index of last attempted instruction in bytecode tb_lineno current line number in Python source code tb_next next inner traceback object (called by this level)""" return isinstance(object, types.TracebackType) def isframe(object): """Return true if the object is a frame object. Frame objects provide these attributes: f_back next outer frame object (this frame's caller) f_builtins built-in namespace seen by this frame f_code code object being executed in this frame f_globals global namespace seen by this frame f_lasti index of last attempted instruction in bytecode f_lineno current line number in Python source code f_locals local namespace seen by this frame f_trace tracing function for this frame, or None""" return isinstance(object, types.FrameType) def iscode(object): """Return true if the object is a code object. Code objects provide these attributes: co_argcount number of arguments (not including * or ** args) co_code string of raw compiled bytecode co_consts tuple of constants used in the bytecode co_filename name of file in which this code object was created co_firstlineno number of first line in Python source code co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg co_lnotab encoded mapping of line numbers to bytecode indices co_name name with which this code object was defined co_names tuple of names of local variables co_nlocals number of local variables co_stacksize virtual machine stack space required co_varnames tuple of names of arguments and local variables""" return isinstance(object, types.CodeType) def isbuiltin(object): """Return true if the object is a built-in function or method. Built-in functions and methods provide these attributes: __doc__ documentation string __name__ original name of this function or method __self__ instance to which a method is bound, or None""" return isinstance(object, types.BuiltinFunctionType) def isroutine(object): """Return true if the object is any kind of function or method.""" return (isbuiltin(object) or isfunction(object) or ismethod(object) or ismethoddescriptor(object)) def isabstract(object): """Return true if the object is an abstract base class (ABC).""" return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT) def getmembers(object, predicate=None): """Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.""" if isclass(object): mro = (object,) + getmro(object) else: mro = () results = [] for key in dir(object): # First try to get the value via __dict__. Some descriptors don't # like calling their __get__ (see bug #1785). for base in mro: if key in base.__dict__: value = base.__dict__[key] break else: try: value = getattr(object, key) except AttributeError: continue if not predicate or predicate(value): results.append((key, value)) results.sort() return results Attribute = namedtuple('Attribute', 'name kind defining_class object') def classify_class_attrs(cls): """Return list of attribute-descriptor tuples. For each name in dir(cls), the return list contains a 4-tuple with these elements: 0. The name (a string). 1. The kind of attribute this is, one of these strings: 'class method' created via classmethod() 'static method' created via staticmethod() 'property' created via property() 'method' any other flavor of method 'data' not a method 2. The class which defined this attribute (a class). 3. The object as obtained directly from the defining class's __dict__, not via getattr. This is especially important for data attributes: C.data is just a data object, but C.__dict__['data'] may be a data descriptor with additional info, like a __doc__ string. """ mro = getmro(cls) names = dir(cls) result = [] for name in names: # Get the object associated with the name, and where it was defined. # Getting an obj from the __dict__ sometimes reveals more than # using getattr. Static and class methods are dramatic examples. # Furthermore, some objects may raise an Exception when fetched with # getattr(). This is the case with some descriptors (bug #1785). # Thus, we only use getattr() as a last resort. homecls = None for base in (cls,) + mro: if name in base.__dict__: obj = base.__dict__[name] homecls = base break else: obj = getattr(cls, name) homecls = getattr(obj, "__objclass__", homecls) # Classify the object. if isinstance(obj, staticmethod): kind = "static method" elif isinstance(obj, classmethod): kind = "class method" elif isinstance(obj, property): kind = "property" elif ismethoddescriptor(obj): kind = "method" elif isdatadescriptor(obj): kind = "data" else: obj_via_getattr = getattr(cls, name) if (isfunction(obj_via_getattr) or ismethoddescriptor(obj_via_getattr)): kind = "method" else: kind = "data" obj = obj_via_getattr result.append(Attribute(name, kind, homecls, obj)) return result # ----------------------------------------------------------- class helpers def getmro(cls): "Return tuple of base classes (including cls) in method resolution order." return cls.__mro__ # -------------------------------------------------- source code extraction def indentsize(line): """Return the indent size, in spaces, at the start of a line of text.""" expline = line.expandtabs() return len(expline) - len(expline.lstrip()) def getdoc(object): """Get the documentation string for an object. All tabs are expanded to spaces. To clean up docstrings that are indented to line up with blocks of code, any whitespace than can be uniformly removed from the second line onwards is removed.""" try: doc = object.__doc__ except AttributeError: return None if not isinstance(doc, str): return None return cleandoc(doc) def cleandoc(doc): """Clean up indentation from docstrings. Any whitespace that can be uniformly removed from the second line onwards is removed.""" try: lines = doc.expandtabs().split('\n') except UnicodeError: return None else: # Find minimum indentation of any non-blank lines after first line. margin = sys.maxsize for line in lines[1:]: content = len(line.lstrip()) if content: indent = len(line) - content margin = min(margin, indent) # Remove indentation. if lines: lines[0] = lines[0].lstrip() if margin < sys.maxsize: for i in range(1, len(lines)): lines[i] = lines[i][margin:] # Remove any trailing or leading blank lines. while lines and not lines[-1]: lines.pop() while lines and not lines[0]: lines.pop(0) return '\n'.join(lines) def getfile(object): """Work out which source or compiled file an object was defined in.""" if ismodule(object): if hasattr(object, '__file__'): return object.__file__ raise TypeError('{!r} is a built-in module'.format(object)) if isclass(object): object = sys.modules.get(object.__module__) if hasattr(object, '__file__'): return object.__file__ raise TypeError('{!r} is a built-in class'.format(object)) if ismethod(object): object = object.__func__ if isfunction(object): object = object.__code__ if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): return object.co_filename raise TypeError('{!r} is not a module, class, method, ' 'function, traceback, frame, or code object'.format(object)) ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type') def getmoduleinfo(path): """Get the module name, suffix, mode, and module type for a given file.""" warnings.warn('inspect.getmoduleinfo() is deprecated', DeprecationWarning, 2) filename = os.path.basename(path) suffixes = [(-len(suffix), suffix, mode, mtype) for suffix, mode, mtype in imp.get_suffixes()] suffixes.sort() # try longest suffixes first, in case they overlap for neglen, suffix, mode, mtype in suffixes: if filename[neglen:] == suffix: return ModuleInfo(filename[:neglen], suffix, mode, mtype) def getmodulename(path): """Return the module name for a given file, or None.""" fname = os.path.basename(path) # Check for paths that look like an actual module file suffixes = [(-len(suffix), suffix) for suffix in importlib.machinery.all_suffixes()] suffixes.sort() # try longest suffixes first, in case they overlap for neglen, suffix in suffixes: if fname.endswith(suffix): return fname[:neglen] return None def getsourcefile(object): """Return the filename that can be used to locate an object's source. Return None if no way can be identified to get the source. """ filename = getfile(object) all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:] all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:] if any(filename.endswith(s) for s in all_bytecode_suffixes): filename = (os.path.splitext(filename)[0] + importlib.machinery.SOURCE_SUFFIXES[0]) elif any(filename.endswith(s) for s in importlib.machinery.EXTENSION_SUFFIXES): return None if os.path.exists(filename): return filename # only return a non-existent filename if the module has a PEP 302 loader if hasattr(getmodule(object, filename), '__loader__'): return filename # or it is in the linecache if filename in linecache.cache: return filename def getabsfile(object, _filename=None): """Return an absolute path to the source or compiled file for an object. The idea is for each object to have a unique origin, so this routine normalizes the result as much as possible.""" if _filename is None: _filename = getsourcefile(object) or getfile(object) return os.path.normcase(os.path.abspath(_filename)) modulesbyfile = {} _filesbymodname = {} def getmodule(object, _filename=None): """Return the module an object was defined in, or None if not found.""" if ismodule(object): return object if hasattr(object, '__module__'): return sys.modules.get(object.__module__) # Try the filename to modulename cache if _filename is not None and _filename in modulesbyfile: return sys.modules.get(modulesbyfile[_filename]) # Try the cache again with the absolute file name try: file = getabsfile(object, _filename) except TypeError: return None if file in modulesbyfile: return sys.modules.get(modulesbyfile[file]) # Update the filename to module name cache and check yet again # Copy sys.modules in order to cope with changes while iterating for modname, module in list(sys.modules.items()): if ismodule(module) and hasattr(module, '__file__'): f = module.__file__ if f == _filesbymodname.get(modname, None): # Have already mapped this module, so skip it continue _filesbymodname[modname] = f f = getabsfile(module) # Always map to the name the module knows itself by modulesbyfile[f] = modulesbyfile[ os.path.realpath(f)] = module.__name__ if file in modulesbyfile: return sys.modules.get(modulesbyfile[file]) # Check the main module main = sys.modules['__main__'] if not hasattr(object, '__name__'): return None if hasattr(main, object.__name__): mainobject = getattr(main, object.__name__) if mainobject is object: return main # Check builtins builtin = sys.modules['builtins'] if hasattr(builtin, object.__name__): builtinobject = getattr(builtin, object.__name__) if builtinobject is object: return builtin def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" file = getfile(object) sourcefile = getsourcefile(object) if not sourcefile and file[:1] + file[-1:] != '<>': raise IOError('source code not available') file = sourcefile if sourcefile else file module = getmodule(object, file) if module: lines = linecache.getlines(file, module.__dict__) else: lines = linecache.getlines(file) if not lines: raise IOError('could not get source code') if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ pat = re.compile(r'^(\s*)class\s*' + name + r'\b') # make some effort to find the best matching class definition: # use the one with the least indentation, which is the one # that's most probably not inside a function definition. candidates = [] for i in range(len(lines)): match = pat.match(lines[i]) if match: # if it's at toplevel, it's already the best one if lines[i][0] == 'c': return lines, i # else add whitespace to candidate list candidates.append((match.group(1), i)) if candidates: # this will sort by whitespace, and by line number, # less whitespace first candidates.sort() return lines, candidates[0][1] else: raise IOError('could not find class definition') if ismethod(object): object = object.__func__ if isfunction(object): object = object.__code__ if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError('could not find function definition') lnum = object.co_firstlineno - 1 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') while lnum > 0: if pat.match(lines[lnum]): break lnum = lnum - 1 return lines, lnum raise IOError('could not find code object') def getcomments(object): """Get lines of comments immediately preceding an object's source code. Returns None when source can't be found. """ try: lines, lnum = findsource(object) except (IOError, TypeError): return None if ismodule(object): # Look for a comment block at the top of the file. start = 0 if lines and lines[0][:2] == '#!': start = 1 while start < len(lines) and lines[start].strip() in ('', '#'): start = start + 1 if start < len(lines) and lines[start][:1] == '#': comments = [] end = start while end < len(lines) and lines[end][:1] == '#': comments.append(lines[end].expandtabs()) end = end + 1 return ''.join(comments) # Look for a preceding block of comments at the same indentation. elif lnum > 0: indent = indentsize(lines[lnum]) end = lnum - 1 if end >= 0 and lines[end].lstrip()[:1] == '#' and \ indentsize(lines[end]) == indent: comments = [lines[end].expandtabs().lstrip()] if end > 0: end = end - 1 comment = lines[end].expandtabs().lstrip() while comment[:1] == '#' and indentsize(lines[end]) == indent: comments[:0] = [comment] end = end - 1 if end < 0: break comment = lines[end].expandtabs().lstrip() while comments and comments[0].strip() == '#': comments[:1] = [] while comments and comments[-1].strip() == '#': comments[-1:] = [] return ''.join(comments) class EndOfBlock(Exception): pass class BlockFinder: """Provide a tokeneater() method to detect the end of a code block.""" def __init__(self): self.indent = 0 self.islambda = False self.started = False self.passline = False self.last = 1 def tokeneater(self, type, token, srowcol, erowcol, line): if not self.started: # look for the first "def", "class" or "lambda" if token in ("def", "class", "lambda"): if token == "lambda": self.islambda = True self.started = True self.passline = True # skip to the end of the line elif type == tokenize.NEWLINE: self.passline = False # stop skipping when a NEWLINE is seen self.last = srowcol[0] if self.islambda: # lambdas always end at the first NEWLINE raise EndOfBlock elif self.passline: pass elif type == tokenize.INDENT: self.indent = self.indent + 1 self.passline = True elif type == tokenize.DEDENT: self.indent = self.indent - 1 # the end of matching indent/dedent pairs end a block # (note that this only works for "def"/"class" blocks, # not e.g. for "if: else:" or "try: finally:" blocks) if self.indent <= 0: raise EndOfBlock elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL): # any other token on the same indentation level end the previous # block as well, except the pseudo-tokens COMMENT and NL. raise EndOfBlock def getblock(lines): """Extract the block of code at the top of the given list of lines.""" blockfinder = BlockFinder() try: tokens = tokenize.generate_tokens(iter(lines).__next__) for _token in tokens: blockfinder.tokeneater(*_token) except (EndOfBlock, IndentationError): pass return lines[:blockfinder.last] def getsourcelines(object): """Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An IOError is raised if the source code cannot be retrieved.""" lines, lnum = findsource(object) if ismodule(object): return lines, 0 else: return getblock(lines[lnum:]), lnum + 1 def getsource(object): """Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An IOError is raised if the source code cannot be retrieved.""" lines, lnum = getsourcelines(object) return ''.join(lines) # --------------------------------------------------- class tree extraction def walktree(classes, children, parent): """Recursive helper function for getclasstree().""" results = [] classes.sort(key=attrgetter('__module__', '__name__')) for c in classes: results.append((c, c.__bases__)) if c in children: results.append(walktree(children[c], children, c)) return results def getclasstree(classes, unique=False): """Arrange the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list. Each entry is a 2-tuple containing a class and a tuple of its base classes. If the 'unique' argument is true, exactly one entry appears in the returned structure for each class in the given list. Otherwise, classes using multiple inheritance and their descendants will appear multiple times.""" children = {} roots = [] for c in classes: if c.__bases__: for parent in c.__bases__: if not parent in children: children[parent] = [] if c not in children[parent]: children[parent].append(c) if unique and parent in classes: break elif c not in roots: roots.append(c) for parent in children: if parent not in classes: roots.append(parent) return walktree(roots, children, None) # ------------------------------------------------ argument list extraction Arguments = namedtuple('Arguments', 'args, varargs, varkw') def getargs(co): """Get information about the arguments accepted by a code object. Three things are returned: (args, varargs, varkw), where 'args' is the list of argument names. Keyword-only arguments are appended. 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" args, varargs, kwonlyargs, varkw = _getfullargs(co) return Arguments(args + kwonlyargs, varargs, varkw) def _getfullargs(co): """Get information about the arguments accepted by a code object. Four things are returned: (args, varargs, kwonlyargs, varkw), where 'args' and 'kwonlyargs' are lists of argument names, and 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" if not iscode(co): raise TypeError('{!r} is not a code object'.format(co)) nargs = co.co_argcount names = co.co_varnames nkwargs = co.co_kwonlyargcount args = list(names[:nargs]) kwonlyargs = list(names[nargs:nargs+nkwargs]) step = 0 nargs += nkwargs varargs = None if co.co_flags & CO_VARARGS: varargs = co.co_varnames[nargs] nargs = nargs + 1 varkw = None if co.co_flags & CO_VARKEYWORDS: varkw = co.co_varnames[nargs] return args, varargs, kwonlyargs, varkw ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults') def getargspec(func): """Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names. 'args' will include keyword-only argument names. 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. Use the getfullargspec() API for Python-3000 code, as annotations and keyword arguments are supported. getargspec() will raise ValueError if the func has either annotations or keyword arguments. """ args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \ getfullargspec(func) if kwonlyargs or ann: raise ValueError("Function has keyword-only arguments or annotations" ", use getfullargspec() API which can support them") return ArgSpec(args, varargs, varkw, defaults) FullArgSpec = namedtuple('FullArgSpec', 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations') def getfullargspec(func): """Get the names and default values of a function's arguments. A tuple of seven things is returned: (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations). 'args' is a list of the argument names. 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. 'kwonlyargs' is a list of keyword-only argument names. 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults. 'annotations' is a dictionary mapping argument names to annotations. The first four items in the tuple correspond to getargspec(). """ if ismethod(func): func = func.__func__ if not isfunction(func): raise TypeError('{!r} is not a Python function'.format(func)) args, varargs, kwonlyargs, varkw = _getfullargs(func.__code__) return FullArgSpec(args, varargs, varkw, func.__defaults__, kwonlyargs, func.__kwdefaults__, func.__annotations__) ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals') def getargvalues(frame): """Get information about arguments passed into a particular frame. A tuple of four things is returned: (args, varargs, varkw, locals). 'args' is a list of the argument names. 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'locals' is the locals dictionary of the given frame.""" args, varargs, varkw = getargs(frame.f_code) return ArgInfo(args, varargs, varkw, frame.f_locals) def formatannotation(annotation, base_module=None): if isinstance(annotation, type): if annotation.__module__ in ('builtins', base_module): return annotation.__name__ return annotation.__module__+'.'+annotation.__name__ return repr(annotation) def formatannotationrelativeto(object): module = getattr(object, '__module__', None) def _formatannotation(annotation): return formatannotation(annotation, module) return _formatannotation def formatargspec(args, varargs=None, varkw=None, defaults=None, kwonlyargs=(), kwonlydefaults={}, annotations={}, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), formatreturns=lambda text: ' -> ' + text, formatannotation=formatannotation): """Format an argument spec from the values returned by getargspec or getfullargspec. The first seven arguments are (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations). The other five arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The last argument is an optional function to format the sequence of arguments.""" def formatargandannotation(arg): result = formatarg(arg) if arg in annotations: result += ': ' + formatannotation(annotations[arg]) return result specs = [] if defaults: firstdefault = len(args) - len(defaults) for i, arg in enumerate(args): spec = formatargandannotation(arg) if defaults and i >= firstdefault: spec = spec + formatvalue(defaults[i - firstdefault]) specs.append(spec) if varargs is not None: specs.append(formatvarargs(formatargandannotation(varargs))) else: if kwonlyargs: specs.append('*') if kwonlyargs: for kwonlyarg in kwonlyargs: spec = formatargandannotation(kwonlyarg) if kwonlydefaults and kwonlyarg in kwonlydefaults: spec += formatvalue(kwonlydefaults[kwonlyarg]) specs.append(spec) if varkw is not None: specs.append(formatvarkw(formatargandannotation(varkw))) result = '(' + ', '.join(specs) + ')' if 'return' in annotations: result += formatreturns(formatannotation(annotations['return'])) return result def formatargvalues(args, varargs, varkw, locals, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value)): """Format an argument spec from the 4 values returned by getargvalues. The first four arguments are (args, varargs, varkw, locals). The next four arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The ninth argument is an optional function to format the sequence of arguments.""" def convert(name, locals=locals, formatarg=formatarg, formatvalue=formatvalue): return formatarg(name) + formatvalue(locals[name]) specs = [] for i in range(len(args)): specs.append(convert(args[i])) if varargs: specs.append(formatvarargs(varargs) + formatvalue(locals[varargs])) if varkw: specs.append(formatvarkw(varkw) + formatvalue(locals[varkw])) return '(' + ', '.join(specs) + ')' def _missing_arguments(f_name, argnames, pos, values): names = [repr(name) for name in argnames if name not in values] missing = len(names) if missing == 1: s = names[0] elif missing == 2: s = "{} and {}".format(*names) else: tail = ", {} and {}".format(names[-2:]) del names[-2:] s = ", ".join(names) + tail raise TypeError("%s() missing %i required %s argument%s: %s" % (f_name, missing, "positional" if pos else "keyword-only", "" if missing == 1 else "s", s)) def _too_many(f_name, args, kwonly, varargs, defcount, given, values): atleast = len(args) - defcount kwonly_given = len([arg for arg in kwonly if arg in values]) if varargs: plural = atleast != 1 sig = "at least %d" % (atleast,) elif defcount: plural = True sig = "from %d to %d" % (atleast, len(args)) else: plural = len(args) != 1 sig = str(len(args)) kwonly_sig = "" if kwonly_given: msg = " positional argument%s (and %d keyword-only argument%s)" kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given, "s" if kwonly_given != 1 else "")) raise TypeError("%s() takes %s positional argument%s but %d%s %s given" % (f_name, sig, "s" if plural else "", given, kwonly_sig, "was" if given == 1 and not kwonly_given else "were")) def getcallargs(func, *positional, **named): """Get the mapping of arguments to values. A dict is returned, with keys the function argument names (including the names of the * and ** arguments, if any), and values the respective bound values from 'positional' and 'named'.""" spec = getfullargspec(func) args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec f_name = func.__name__ arg2value = {} if ismethod(func) and func.__self__ is not None: # implicit 'self' (or 'cls' for classmethods) argument positional = (func.__self__,) + positional num_pos = len(positional) num_args = len(args) num_defaults = len(defaults) if defaults else 0 n = min(num_pos, num_args) for i in range(n): arg2value[args[i]] = positional[i] if varargs: arg2value[varargs] = tuple(positional[n:]) possible_kwargs = set(args + kwonlyargs) if varkw: arg2value[varkw] = {} for kw, value in named.items(): if kw not in possible_kwargs: if not varkw: raise TypeError("%s() got an unexpected keyword argument %r" % (f_name, kw)) arg2value[varkw][kw] = value continue if kw in arg2value: raise TypeError("%s() got multiple values for argument %r" % (f_name, kw)) arg2value[kw] = value if num_pos > num_args and not varargs: _too_many(f_name, args, kwonlyargs, varargs, num_defaults, num_pos, arg2value) if num_pos < num_args: req = args[:num_args - num_defaults] for arg in req: if arg not in arg2value: _missing_arguments(f_name, req, True, arg2value) for i, arg in enumerate(args[num_args - num_defaults:]): if arg not in arg2value: arg2value[arg] = defaults[i] missing = 0 for kwarg in kwonlyargs: if kwarg not in arg2value: if kwarg in kwonlydefaults: arg2value[kwarg] = kwonlydefaults[kwarg] else: missing += 1 if missing: _missing_arguments(f_name, kwonlyargs, False, arg2value) return arg2value ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound') def getclosurevars(func): """ Get the mapping of free variables to their current values. Returns a named tuple of dicts mapping the current nonlocal, global and builtin references as seen by the body of the function. A final set of unbound names that could not be resolved is also provided. """ if ismethod(func): func = func.__func__ if not isfunction(func): raise TypeError("'{!r}' is not a Python function".format(func)) code = func.__code__ # Nonlocal references are named in co_freevars and resolved # by looking them up in __closure__ by positional index if func.__closure__ is None: nonlocal_vars = {} else: nonlocal_vars = { var : cell.cell_contents for var, cell in zip(code.co_freevars, func.__closure__) } # Global and builtin references are named in co_names and resolved # by looking them up in __globals__ or __builtins__ global_ns = func.__globals__ builtin_ns = global_ns.get("__builtins__", builtins.__dict__) if ismodule(builtin_ns): builtin_ns = builtin_ns.__dict__ global_vars = {} builtin_vars = {} unbound_names = set() for name in code.co_names: if name in ("None", "True", "False"): # Because these used to be builtins instead of keywords, they # may still show up as name references. We ignore them. continue try: global_vars[name] = global_ns[name] except KeyError: try: builtin_vars[name] = builtin_ns[name] except KeyError: unbound_names.add(name) return ClosureVars(nonlocal_vars, global_vars, builtin_vars, unbound_names) # -------------------------------------------------- stack frame extraction Traceback = namedtuple('Traceback', 'filename lineno function code_context index') def getframeinfo(frame, context=1): """Get information about a frame or traceback object. A tuple of five things is returned: the filename, the line number of the current line, the function name, a list of lines of context from the source code, and the index of the current line within that list. The optional second argument specifies the number of lines of context to return, which are centered around the current line.""" if istraceback(frame): lineno = frame.tb_lineno frame = frame.tb_frame else: lineno = frame.f_lineno if not isframe(frame): raise TypeError('{!r} is not a frame or traceback object'.format(frame)) filename = getsourcefile(frame) or getfile(frame) if context > 0: start = lineno - 1 - context//2 try: lines, lnum = findsource(frame) except IOError: lines = index = None else: start = max(start, 1) start = max(0, min(start, len(lines) - context)) lines = lines[start:start+context] index = lineno - 1 - start else: lines = index = None return Traceback(filename, lineno, frame.f_code.co_name, lines, index) def getlineno(frame): """Get the line number from a frame object, allowing for optimization.""" # FrameType.f_lineno is now a descriptor that grovels co_lnotab return frame.f_lineno def getouterframes(frame, context=1): """Get a list of records for a frame and all higher (calling) frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.""" framelist = [] while frame: framelist.append((frame,) + getframeinfo(frame, context)) frame = frame.f_back return framelist def getinnerframes(tb, context=1): """Get a list of records for a traceback's frame and all lower frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.""" framelist = [] while tb: framelist.append((tb.tb_frame,) + getframeinfo(tb, context)) tb = tb.tb_next return framelist def currentframe(): """Return the frame of the caller or None if this is not possible.""" return sys._getframe(1) if hasattr(sys, "_getframe") else None def stack(context=1): """Return a list of records for the stack above the caller's frame.""" return getouterframes(sys._getframe(1), context) def trace(context=1): """Return a list of records for the stack below the current exception.""" return getinnerframes(sys.exc_info()[2], context) # ------------------------------------------------ static version of getattr _sentinel = object() def _static_getmro(klass): return type.__dict__['__mro__'].__get__(klass) def _check_instance(obj, attr): instance_dict = {} try: instance_dict = object.__getattribute__(obj, "__dict__") except AttributeError: pass return dict.get(instance_dict, attr, _sentinel) def _check_class(klass, attr): for entry in _static_getmro(klass): if _shadowed_dict(type(entry)) is _sentinel: try: return entry.__dict__[attr] except KeyError: pass return _sentinel def _is_type(obj): try: _static_getmro(obj) except TypeError: return False return True def _shadowed_dict(klass): dict_attr = type.__dict__["__dict__"] for entry in _static_getmro(klass): try: class_dict = dict_attr.__get__(entry)["__dict__"] except KeyError: pass else: if not (type(class_dict) is types.GetSetDescriptorType and class_dict.__name__ == "__dict__" and class_dict.__objclass__ is entry): return class_dict return _sentinel def getattr_static(obj, attr, default=_sentinel): """Retrieve attributes without triggering dynamic lookup via the descriptor protocol, __getattr__ or __getattribute__. Note: this function may not be able to retrieve all attributes that getattr can fetch (like dynamically created attributes) and may find attributes that getattr can't (like descriptors that raise AttributeError). It can also return descriptor objects instead of instance members in some cases. See the documentation for details. """ instance_result = _sentinel if not _is_type(obj): klass = type(obj) dict_attr = _shadowed_dict(klass) if (dict_attr is _sentinel or type(dict_attr) is types.MemberDescriptorType): instance_result = _check_instance(obj, attr) else: klass = obj klass_result = _check_class(klass, attr) if instance_result is not _sentinel and klass_result is not _sentinel: if (_check_class(type(klass_result), '__get__') is not _sentinel and _check_class(type(klass_result), '__set__') is not _sentinel): return klass_result if instance_result is not _sentinel: return instance_result if klass_result is not _sentinel: return klass_result if obj is klass: # for types we check the metaclass too for entry in _static_getmro(type(klass)): if _shadowed_dict(type(entry)) is _sentinel: try: return entry.__dict__[attr] except KeyError: pass if default is not _sentinel: return default raise AttributeError(attr) # ------------------------------------------------ generator introspection GEN_CREATED = 'GEN_CREATED' GEN_RUNNING = 'GEN_RUNNING' GEN_SUSPENDED = 'GEN_SUSPENDED' GEN_CLOSED = 'GEN_CLOSED' def getgeneratorstate(generator): """Get current state of a generator-iterator. Possible states are: GEN_CREATED: Waiting to start execution. GEN_RUNNING: Currently being executed by the interpreter. GEN_SUSPENDED: Currently suspended at a yield expression. GEN_CLOSED: Execution has completed. """ if generator.gi_running: return GEN_RUNNING if generator.gi_frame is None: return GEN_CLOSED if generator.gi_frame.f_lasti == -1: return GEN_CREATED return GEN_SUSPENDED def getgeneratorlocals(generator): """ Get the mapping of generator local variables to their current values. A dict is returned, with the keys the local variable names and values the bound values.""" if not isgenerator(generator): raise TypeError("'{!r}' is not a Python generator".format(generator)) frame = getattr(generator, "gi_frame", None) if frame is not None: return generator.gi_frame.f_locals else: return {} ############################################################################### ### Function Signature Object (PEP 362) ############################################################################### _WrapperDescriptor = type(type.__call__) _MethodWrapper = type(all.__call__) _NonUserDefinedCallables = (_WrapperDescriptor, _MethodWrapper, types.BuiltinFunctionType) def _get_user_defined_method(cls, method_name): try: meth = getattr(cls, method_name) except AttributeError: return else: if not isinstance(meth, _NonUserDefinedCallables): # Once '__signature__' will be added to 'C'-level # callables, this check won't be necessary return meth def signature(obj): '''Get a signature object for the passed callable.''' if not callable(obj): raise TypeError('{!r} is not a callable object'.format(obj)) if isinstance(obj, types.MethodType): # In this case we skip the first parameter of the underlying # function (usually `self` or `cls`). sig = signature(obj.__func__) return sig.replace(parameters=tuple(sig.parameters.values())[1:]) try: sig = obj.__signature__ except AttributeError: pass else: if sig is not None: return sig try: # Was this function wrapped by a decorator? wrapped = obj.__wrapped__ except AttributeError: pass else: return signature(wrapped) if isinstance(obj, types.FunctionType): return Signature.from_function(obj) if isinstance(obj, functools.partial): sig = signature(obj.func) new_params = OrderedDict(sig.parameters.items()) partial_args = obj.args or () partial_keywords = obj.keywords or {} try: ba = sig.bind_partial(*partial_args, **partial_keywords) except TypeError as ex: msg = 'partial object {!r} has incorrect arguments'.format(obj) raise ValueError(msg) from ex for arg_name, arg_value in ba.arguments.items(): param = new_params[arg_name] if arg_name in partial_keywords: # We set a new default value, because the following code # is correct: # # >>> def foo(a): print(a) # >>> print(partial(partial(foo, a=10), a=20)()) # 20 # >>> print(partial(partial(foo, a=10), a=20)(a=30)) # 30 # # So, with 'partial' objects, passing a keyword argument is # like setting a new default value for the corresponding # parameter # # We also mark this parameter with '_partial_kwarg' # flag. Later, in '_bind', the 'default' value of this # parameter will be added to 'kwargs', to simulate # the 'functools.partial' real call. new_params[arg_name] = param.replace(default=arg_value, _partial_kwarg=True) elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and not param._partial_kwarg): new_params.pop(arg_name) return sig.replace(parameters=new_params.values()) sig = None if isinstance(obj, type): # obj is a class or a metaclass # First, let's see if it has an overloaded __call__ defined # in its metaclass call = _get_user_defined_method(type(obj), '__call__') if call is not None: sig = signature(call) else: # Now we check if the 'obj' class has a '__new__' method new = _get_user_defined_method(obj, '__new__') if new is not None: sig = signature(new) else: # Finally, we should have at least __init__ implemented init = _get_user_defined_method(obj, '__init__') if init is not None: sig = signature(init) elif not isinstance(obj, _NonUserDefinedCallables): # An object with __call__ # We also check that the 'obj' is not an instance of # _WrapperDescriptor or _MethodWrapper to avoid # infinite recursion (and even potential segfault) call = _get_user_defined_method(type(obj), '__call__') if call is not None: sig = signature(call) if sig is not None: # For classes and objects we skip the first parameter of their # __call__, __new__, or __init__ methods return sig.replace(parameters=tuple(sig.parameters.values())[1:]) if isinstance(obj, types.BuiltinFunctionType): # Raise a nicer error message for builtins msg = 'no signature found for builtin function {!r}'.format(obj) raise ValueError(msg) raise ValueError('callable {!r} is not supported by signature'.format(obj)) class _void: '''A private marker - used in Parameter & Signature''' class _empty: pass class _ParameterKind(int): def __new__(self, *args, name): obj = int.__new__(self, *args) obj._name = name return obj def __str__(self): return self._name def __repr__(self): return '<_ParameterKind: {!r}>'.format(self._name) _POSITIONAL_ONLY = _ParameterKind(0, name='POSITIONAL_ONLY') _POSITIONAL_OR_KEYWORD = _ParameterKind(1, name='POSITIONAL_OR_KEYWORD') _VAR_POSITIONAL = _ParameterKind(2, name='VAR_POSITIONAL') _KEYWORD_ONLY = _ParameterKind(3, name='KEYWORD_ONLY') _VAR_KEYWORD = _ParameterKind(4, name='VAR_KEYWORD') class Parameter: '''Represents a parameter in a function signature. Has the following public attributes: * name : str The name of the parameter as a string. * default : object The default value for the parameter if specified. If the parameter has no default value, this attribute is not set. * annotation The annotation for the parameter if specified. If the parameter has no annotation, this attribute is not set. * kind : str Describes how argument values are bound to the parameter. Possible values: `Parameter.POSITIONAL_ONLY`, `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`, `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`. ''' __slots__ = ('_name', '_kind', '_default', '_annotation', '_partial_kwarg') POSITIONAL_ONLY = _POSITIONAL_ONLY POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD VAR_POSITIONAL = _VAR_POSITIONAL KEYWORD_ONLY = _KEYWORD_ONLY VAR_KEYWORD = _VAR_KEYWORD empty = _empty def __init__(self, name, kind, *, default=_empty, annotation=_empty, _partial_kwarg=False): if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD, _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD): raise ValueError("invalid value for 'Parameter.kind' attribute") self._kind = kind if default is not _empty: if kind in (_VAR_POSITIONAL, _VAR_KEYWORD): msg = '{} parameters cannot have default values'.format(kind) raise ValueError(msg) self._default = default self._annotation = annotation if name is None: if kind != _POSITIONAL_ONLY: raise ValueError("None is not a valid name for a " "non-positional-only parameter") self._name = name else: name = str(name) if kind != _POSITIONAL_ONLY and not name.isidentifier(): msg = '{!r} is not a valid parameter name'.format(name) raise ValueError(msg) self._name = name self._partial_kwarg = _partial_kwarg @property def name(self): return self._name @property def default(self): return self._default @property def annotation(self): return self._annotation @property def kind(self): return self._kind def replace(self, *, name=_void, kind=_void, annotation=_void, default=_void, _partial_kwarg=_void): '''Creates a customized copy of the Parameter.''' if name is _void: name = self._name if kind is _void: kind = self._kind if annotation is _void: annotation = self._annotation if default is _void: default = self._default if _partial_kwarg is _void: _partial_kwarg = self._partial_kwarg return type(self)(name, kind, default=default, annotation=annotation, _partial_kwarg=_partial_kwarg) def __str__(self): kind = self.kind formatted = self._name if kind == _POSITIONAL_ONLY: if formatted is None: formatted = '' formatted = '<{}>'.format(formatted) # Add annotation and default value if self._annotation is not _empty: formatted = '{}:{}'.format(formatted, formatannotation(self._annotation)) if self._default is not _empty: formatted = '{}={}'.format(formatted, repr(self._default)) if kind == _VAR_POSITIONAL: formatted = '*' + formatted elif kind == _VAR_KEYWORD: formatted = '**' + formatted return formatted def __repr__(self): return '<{} at {:#x} {!r}>'.format(self.__class__.__name__, id(self), self.name) def __eq__(self, other): return (issubclass(other.__class__, Parameter) and self._name == other._name and self._kind == other._kind and self._default == other._default and self._annotation == other._annotation) def __ne__(self, other): return not self.__eq__(other) class BoundArguments: '''Result of `Signature.bind` call. Holds the mapping of arguments to the function's parameters. Has the following public attributes: * arguments : OrderedDict An ordered mutable mapping of parameters' names to arguments' values. Does not contain arguments' default values. * signature : Signature The Signature object that created this instance. * args : tuple Tuple of positional arguments values. * kwargs : dict Dict of keyword arguments values. ''' def __init__(self, signature, arguments): self.arguments = arguments self._signature = signature @property def signature(self): return self._signature @property def args(self): args = [] for param_name, param in self._signature.parameters.items(): if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or param._partial_kwarg): # Keyword arguments mapped by 'functools.partial' # (Parameter._partial_kwarg is True) are mapped # in 'BoundArguments.kwargs', along with VAR_KEYWORD & # KEYWORD_ONLY break try: arg = self.arguments[param_name] except KeyError: # We're done here. Other arguments # will be mapped in 'BoundArguments.kwargs' break else: if param.kind == _VAR_POSITIONAL: # *args args.extend(arg) else: # plain argument args.append(arg) return tuple(args) @property def kwargs(self): kwargs = {} kwargs_started = False for param_name, param in self._signature.parameters.items(): if not kwargs_started: if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or param._partial_kwarg): kwargs_started = True else: if param_name not in self.arguments: kwargs_started = True continue if not kwargs_started: continue try: arg = self.arguments[param_name] except KeyError: pass else: if param.kind == _VAR_KEYWORD: # **kwargs kwargs.update(arg) else: # plain keyword argument kwargs[param_name] = arg return kwargs def __eq__(self, other): return (issubclass(other.__class__, BoundArguments) and self.signature == other.signature and self.arguments == other.arguments) def __ne__(self, other): return not self.__eq__(other) class Signature: '''A Signature object represents the overall signature of a function. It stores a Parameter object for each parameter accepted by the function, as well as information specific to the function itself. A Signature object has the following public attributes and methods: * parameters : OrderedDict An ordered mapping of parameters' names to the corresponding Parameter objects (keyword-only arguments are in the same order as listed in `code.co_varnames`). * return_annotation : object The annotation for the return type of the function if specified. If the function has no annotation for its return type, this attribute is not set. * bind(*args, **kwargs) -> BoundArguments Creates a mapping from positional and keyword arguments to parameters. * bind_partial(*args, **kwargs) -> BoundArguments Creates a partial mapping from positional and keyword arguments to parameters (simulating 'functools.partial' behavior.) ''' __slots__ = ('_return_annotation', '_parameters') _parameter_cls = Parameter _bound_arguments_cls = BoundArguments empty = _empty def __init__(self, parameters=None, *, return_annotation=_empty, __validate_parameters__=True): '''Constructs Signature from the given list of Parameter objects and 'return_annotation'. All arguments are optional. ''' if parameters is None: params = OrderedDict() else: if __validate_parameters__: params = OrderedDict() top_kind = _POSITIONAL_ONLY for idx, param in enumerate(parameters): kind = param.kind if kind < top_kind: msg = 'wrong parameter order: {} before {}' msg = msg.format(top_kind, param.kind) raise ValueError(msg) else: top_kind = kind name = param.name if name is None: name = str(idx) param = param.replace(name=name) if name in params: msg = 'duplicate parameter name: {!r}'.format(name) raise ValueError(msg) params[name] = param else: params = OrderedDict(((param.name, param) for param in parameters)) self._parameters = types.MappingProxyType(params) self._return_annotation = return_annotation @classmethod def from_function(cls, func): '''Constructs Signature for the given python function''' if not isinstance(func, types.FunctionType): raise TypeError('{!r} is not a Python function'.format(func)) Parameter = cls._parameter_cls # Parameter information. func_code = func.__code__ pos_count = func_code.co_argcount arg_names = func_code.co_varnames positional = tuple(arg_names[:pos_count]) keyword_only_count = func_code.co_kwonlyargcount keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)] annotations = func.__annotations__ defaults = func.__defaults__ kwdefaults = func.__kwdefaults__ if defaults: pos_default_count = len(defaults) else: pos_default_count = 0 parameters = [] # Non-keyword-only parameters w/o defaults. non_default_count = pos_count - pos_default_count for name in positional[:non_default_count]: annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_POSITIONAL_OR_KEYWORD)) # ... w/ defaults. for offset, name in enumerate(positional[non_default_count:]): annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_POSITIONAL_OR_KEYWORD, default=defaults[offset])) # *args if func_code.co_flags & 0x04: name = arg_names[pos_count + keyword_only_count] annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_VAR_POSITIONAL)) # Keyword-only parameters. for name in keyword_only: default = _empty if kwdefaults is not None: default = kwdefaults.get(name, _empty) annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_KEYWORD_ONLY, default=default)) # **kwargs if func_code.co_flags & 0x08: index = pos_count + keyword_only_count if func_code.co_flags & 0x04: index += 1 name = arg_names[index] annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_VAR_KEYWORD)) return cls(parameters, return_annotation=annotations.get('return', _empty), __validate_parameters__=False) @property def parameters(self): return self._parameters @property def return_annotation(self): return self._return_annotation def replace(self, *, parameters=_void, return_annotation=_void): '''Creates a customized copy of the Signature. Pass 'parameters' and/or 'return_annotation' arguments to override them in the new copy. ''' if parameters is _void: parameters = self.parameters.values() if return_annotation is _void: return_annotation = self._return_annotation return type(self)(parameters, return_annotation=return_annotation) def __eq__(self, other): if (not issubclass(type(other), Signature) or self.return_annotation != other.return_annotation or len(self.parameters) != len(other.parameters)): return False other_positions = {param: idx for idx, param in enumerate(other.parameters.keys())} for idx, (param_name, param) in enumerate(self.parameters.items()): if param.kind == _KEYWORD_ONLY: try: other_param = other.parameters[param_name] except KeyError: return False else: if param != other_param: return False else: try: other_idx = other_positions[param_name] except KeyError: return False else: if (idx != other_idx or param != other.parameters[param_name]): return False return True def __ne__(self, other): return not self.__eq__(other) def _bind(self, args, kwargs, *, partial=False): '''Private method. Don't use directly.''' arguments = OrderedDict() parameters = iter(self.parameters.values()) parameters_ex = () arg_vals = iter(args) if partial: # Support for binding arguments to 'functools.partial' objects. # See 'functools.partial' case in 'signature()' implementation # for details. for param_name, param in self.parameters.items(): if (param._partial_kwarg and param_name not in kwargs): # Simulating 'functools.partial' behavior kwargs[param_name] = param.default while True: # Let's iterate through the positional arguments and corresponding # parameters try: arg_val = next(arg_vals) except StopIteration: # No more positional arguments try: param = next(parameters) except StopIteration: # No more parameters. That's it. Just need to check that # we have no `kwargs` after this while loop break else: if param.kind == _VAR_POSITIONAL: # That's OK, just empty *args. Let's start parsing # kwargs break elif param.name in kwargs: if param.kind == _POSITIONAL_ONLY: msg = '{arg!r} parameter is positional only, ' \ 'but was passed as a keyword' msg = msg.format(arg=param.name) raise TypeError(msg) from None parameters_ex = (param,) break elif (param.kind == _VAR_KEYWORD or param.default is not _empty): # That's fine too - we have a default value for this # parameter. So, lets start parsing `kwargs`, starting # with the current parameter parameters_ex = (param,) break else: if partial: parameters_ex = (param,) break else: msg = '{arg!r} parameter lacking default value' msg = msg.format(arg=param.name) raise TypeError(msg) from None else: # We have a positional argument to process try: param = next(parameters) except StopIteration: raise TypeError('too many positional arguments') from None else: if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY): # Looks like we have no parameter for this positional # argument raise TypeError('too many positional arguments') if param.kind == _VAR_POSITIONAL: # We have an '*args'-like argument, let's fill it with # all positional arguments we have left and move on to # the next phase values = [arg_val] values.extend(arg_vals) arguments[param.name] = tuple(values) break if param.name in kwargs: raise TypeError('multiple values for argument ' '{arg!r}'.format(arg=param.name)) arguments[param.name] = arg_val # Now, we iterate through the remaining parameters to process # keyword arguments kwargs_param = None for param in itertools.chain(parameters_ex, parameters): if param.kind == _POSITIONAL_ONLY: # This should never happen in case of a properly built # Signature object (but let's have this check here # to ensure correct behaviour just in case) raise TypeError('{arg!r} parameter is positional only, ' 'but was passed as a keyword'. \ format(arg=param.name)) if param.kind == _VAR_KEYWORD: # Memorize that we have a '**kwargs'-like parameter kwargs_param = param continue param_name = param.name try: arg_val = kwargs.pop(param_name) except KeyError: # We have no value for this parameter. It's fine though, # if it has a default value, or it is an '*args'-like # parameter, left alone by the processing of positional # arguments. if (not partial and param.kind != _VAR_POSITIONAL and param.default is _empty): raise TypeError('{arg!r} parameter lacking default value'. \ format(arg=param_name)) from None else: arguments[param_name] = arg_val if kwargs: if kwargs_param is not None: # Process our '**kwargs'-like parameter arguments[kwargs_param.name] = kwargs else: raise TypeError('too many keyword arguments') return self._bound_arguments_cls(self, arguments) def bind(__bind_self, *args, **kwargs): '''Get a BoundArguments object, that maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound. ''' return __bind_self._bind(args, kwargs) def bind_partial(__bind_self, *args, **kwargs): '''Get a BoundArguments object, that partially maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound. ''' return __bind_self._bind(args, kwargs, partial=True) def __str__(self): result = [] render_kw_only_separator = True for idx, param in enumerate(self.parameters.values()): formatted = str(param) kind = param.kind if kind == _VAR_POSITIONAL: # OK, we have an '*args'-like parameter, so we won't need # a '*' to separate keyword-only arguments render_kw_only_separator = False elif kind == _KEYWORD_ONLY and render_kw_only_separator: # We have a keyword-only parameter to render and we haven't # rendered an '*args'-like parameter before, so add a '*' # separator to the parameters list ("foo(arg1, *, arg2)" case) result.append('*') # This condition should be only triggered once, so # reset the flag render_kw_only_separator = False result.append(formatted) rendered = '({})'.format(', '.join(result)) if self.return_annotation is not _empty: anno = formatannotation(self.return_annotation) rendered += ' -> {}'.format(anno) return rendered
gpl-2.0
TheTypoMaster/chromium-crosswalk
build/android/pylib/base/test_dispatcher_unittest.py
36
8197
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unittests for test_dispatcher.py.""" # pylint: disable=R0201 # pylint: disable=W0212 import os import sys import unittest from pylib import constants from pylib.base import base_test_result from pylib.base import test_collection from pylib.base import test_dispatcher from pylib.device import adb_wrapper from pylib.device import device_utils from pylib.utils import watchdog_timer sys.path.append( os.path.join(constants.DIR_SOURCE_ROOT, 'third_party', 'pymock')) import mock class TestException(Exception): pass def _MockDevice(serial): d = mock.MagicMock(spec=device_utils.DeviceUtils) d.__str__.return_value = serial d.adb = mock.MagicMock(spec=adb_wrapper.AdbWrapper) d.adb.GetDeviceSerial = mock.MagicMock(return_value=serial) d.IsOnline = mock.MagicMock(return_value=True) return d class MockRunner(object): """A mock TestRunner.""" def __init__(self, device=None, shard_index=0): self.device = device or _MockDevice('0') self.device_serial = self.device.adb.GetDeviceSerial() self.shard_index = shard_index self.setups = 0 self.teardowns = 0 def RunTest(self, test): results = base_test_result.TestRunResults() results.AddResult( base_test_result.BaseTestResult(test, base_test_result.ResultType.PASS)) return (results, None) def SetUp(self): self.setups += 1 def TearDown(self): self.teardowns += 1 class MockRunnerFail(MockRunner): def RunTest(self, test): results = base_test_result.TestRunResults() results.AddResult( base_test_result.BaseTestResult(test, base_test_result.ResultType.FAIL)) return (results, test) class MockRunnerFailTwice(MockRunner): def __init__(self, device=None, shard_index=0): super(MockRunnerFailTwice, self).__init__(device, shard_index) self._fails = 0 def RunTest(self, test): self._fails += 1 results = base_test_result.TestRunResults() if self._fails <= 2: results.AddResult(base_test_result.BaseTestResult( test, base_test_result.ResultType.FAIL)) return (results, test) else: results.AddResult(base_test_result.BaseTestResult( test, base_test_result.ResultType.PASS)) return (results, None) class MockRunnerException(MockRunner): def RunTest(self, test): raise TestException class TestFunctions(unittest.TestCase): """Tests test_dispatcher._RunTestsFromQueue.""" @staticmethod def _RunTests(mock_runner, tests): results = [] tests = test_collection.TestCollection( [test_dispatcher._Test(t) for t in tests]) test_dispatcher._RunTestsFromQueue(mock_runner, tests, results, watchdog_timer.WatchdogTimer(None), 2) run_results = base_test_result.TestRunResults() for r in results: run_results.AddTestRunResults(r) return run_results def testRunTestsFromQueue(self): results = TestFunctions._RunTests(MockRunner(), ['a', 'b']) self.assertEqual(len(results.GetPass()), 2) self.assertEqual(len(results.GetNotPass()), 0) def testRunTestsFromQueueRetry(self): results = TestFunctions._RunTests(MockRunnerFail(), ['a', 'b']) self.assertEqual(len(results.GetPass()), 0) self.assertEqual(len(results.GetFail()), 2) def testRunTestsFromQueueFailTwice(self): results = TestFunctions._RunTests(MockRunnerFailTwice(), ['a', 'b']) self.assertEqual(len(results.GetPass()), 2) self.assertEqual(len(results.GetNotPass()), 0) def testSetUp(self): runners = [] counter = test_dispatcher._ThreadSafeCounter() test_dispatcher._SetUp(MockRunner, _MockDevice('0'), runners, counter) self.assertEqual(len(runners), 1) self.assertEqual(runners[0].setups, 1) def testThreadSafeCounter(self): counter = test_dispatcher._ThreadSafeCounter() for i in xrange(5): self.assertEqual(counter.GetAndIncrement(), i) def testApplyMaxPerRun(self): self.assertEqual( ['A:B', 'C:D', 'E', 'F:G', 'H:I'], test_dispatcher.ApplyMaxPerRun(['A:B', 'C:D:E', 'F:G:H:I'], 2)) class TestThreadGroupFunctions(unittest.TestCase): """Tests test_dispatcher._RunAllTests and test_dispatcher._CreateRunners.""" def setUp(self): self.tests = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] shared_test_collection = test_collection.TestCollection( [test_dispatcher._Test(t) for t in self.tests]) self.test_collection_factory = lambda: shared_test_collection def testCreate(self): runners = test_dispatcher._CreateRunners( MockRunner, [_MockDevice('0'), _MockDevice('1')]) for runner in runners: self.assertEqual(runner.setups, 1) self.assertEqual(set([r.device_serial for r in runners]), set(['0', '1'])) self.assertEqual(set([r.shard_index for r in runners]), set([0, 1])) def testRun(self): runners = [MockRunner(_MockDevice('0')), MockRunner(_MockDevice('1'))] results, exit_code = test_dispatcher._RunAllTests( runners, self.test_collection_factory, 0) self.assertEqual(len(results.GetPass()), len(self.tests)) self.assertEqual(exit_code, 0) def testTearDown(self): runners = [MockRunner(_MockDevice('0')), MockRunner(_MockDevice('1'))] test_dispatcher._TearDownRunners(runners) for runner in runners: self.assertEqual(runner.teardowns, 1) def testRetry(self): runners = test_dispatcher._CreateRunners( MockRunnerFail, [_MockDevice('0'), _MockDevice('1')]) results, exit_code = test_dispatcher._RunAllTests( runners, self.test_collection_factory, 0) self.assertEqual(len(results.GetFail()), len(self.tests)) self.assertEqual(exit_code, constants.ERROR_EXIT_CODE) def testReraise(self): runners = test_dispatcher._CreateRunners( MockRunnerException, [_MockDevice('0'), _MockDevice('1')]) with self.assertRaises(TestException): test_dispatcher._RunAllTests(runners, self.test_collection_factory, 0) class TestShard(unittest.TestCase): """Tests test_dispatcher.RunTests with sharding.""" @staticmethod def _RunShard(runner_factory): return test_dispatcher.RunTests( ['a', 'b', 'c'], runner_factory, [_MockDevice('0'), _MockDevice('1')], shard=True) def testShard(self): results, exit_code = TestShard._RunShard(MockRunner) self.assertEqual(len(results.GetPass()), 3) self.assertEqual(exit_code, 0) def testFailing(self): results, exit_code = TestShard._RunShard(MockRunnerFail) self.assertEqual(len(results.GetPass()), 0) self.assertEqual(len(results.GetFail()), 3) self.assertEqual(exit_code, constants.ERROR_EXIT_CODE) def testNoTests(self): results, exit_code = test_dispatcher.RunTests( [], MockRunner, [_MockDevice('0'), _MockDevice('1')], shard=True) self.assertEqual(len(results.GetAll()), 0) self.assertEqual(exit_code, constants.ERROR_EXIT_CODE) class TestReplicate(unittest.TestCase): """Tests test_dispatcher.RunTests with replication.""" @staticmethod def _RunReplicate(runner_factory): return test_dispatcher.RunTests( ['a', 'b', 'c'], runner_factory, [_MockDevice('0'), _MockDevice('1')], shard=False) def testReplicate(self): results, exit_code = TestReplicate._RunReplicate(MockRunner) # We expect 6 results since each test should have been run on every device self.assertEqual(len(results.GetPass()), 6) self.assertEqual(exit_code, 0) def testFailing(self): results, exit_code = TestReplicate._RunReplicate(MockRunnerFail) self.assertEqual(len(results.GetPass()), 0) self.assertEqual(len(results.GetFail()), 6) self.assertEqual(exit_code, constants.ERROR_EXIT_CODE) def testNoTests(self): results, exit_code = test_dispatcher.RunTests( [], MockRunner, [_MockDevice('0'), _MockDevice('1')], shard=False) self.assertEqual(len(results.GetAll()), 0) self.assertEqual(exit_code, constants.ERROR_EXIT_CODE) if __name__ == '__main__': unittest.main()
bsd-3-clause
kyunghyuncho/GroundHog
tutorials/DT_RNN_Tut_Ex_Pieces.py
28
1136
############## outhid = outhid_dropout(outhid, use_noise=False) ############## outhid_activ = UnaryOp(activation=eval(state['dout_activ'])) ############## emb_words_out = MultiLayer( rng, n_in=state['n_in'], n_hids=eval(state['dout_nhid']), activation=linear, init_fn='sample_weights_classic', weight_noise=state['weight_noise'], scale=state['dout_scale'], sparsity=state['dout_sparse'], rank_n_approx=state['dout_rank_n_approx'], learn_bias = False, bias_scale=eval(state['dout_bias']), name='emb_words_out') ############## outhid = outhid_dropout(outhid) ############## outhid_dropout = DropOp(dropout=state['dropout'], rng=rng) ############# emb_state = MultiLayer( rng, n_in=eval(state['nhids'])[-1], n_hids=eval(state['dout_nhid']), activation=linear, init_fn=eval(state['dout_init']), weight_noise=state['weight_noise'], scale=state['dout_scale'], sparsity=state['dout_sparse'], learn_bias = True, bias_scale=eval(state['dout_bias']), name='emb_state') ############## outhid = outhid_activ(emb_state(rec_layer) + emb_words_out(x))
bsd-3-clause
DarkmatterVale/Haiku-Configuration-Repo
hello/models.py
1
2729
from django.db import models from django.contrib.auth.models import User class Component(models.Model): name = models.CharField(default='', max_length=200) notes = models.CharField(default='', max_length=500) is_working = models.CharField(default='', max_length=10) rating = models.CharField(default='', max_length=100) manufacturer = models.CharField(default='', max_length=100) category = models.CharField(default='', max_length=100) author = models.CharField(default='', max_length=100) author_email = models.CharField(default='', max_length=100) date_created = models.DateTimeField('date created', auto_now=True) date_modified = models.DateTimeField('date modified', auto_now=True) haiku_revision = models.CharField(default='', max_length=100) haiku_arch = models.CharField(default='', max_length=10) class Device(models.Model): name = models.CharField(default='', max_length=200) notes = models.CharField(default='', max_length=500) is_working = models.CharField(default='', max_length=10) rating = models.CharField(default='', max_length=100) manufacturer = models.CharField(default='', max_length=100) author = models.CharField(default='', max_length=100) author_email = models.CharField(default='', max_length=100) date_created = models.DateTimeField('date created', auto_now=True) date_modified = models.DateTimeField('date modified', auto_now=True) cpu = models.CharField(default='', max_length=100) motherboard = models.CharField(default='', max_length=100) hard_drive = models.CharField(default='', max_length=100) sound = models.CharField(default='', max_length=100) is_sound_working = models.CharField(default='', max_length=10) display = models.CharField(default='', max_length=100) display_configuration = models.CharField(default='', max_length=20) is_display_working = models.CharField(default='', max_length=10) graphics_card = models.CharField(default='', max_length=100) graphics_card_is_working = models.CharField(default='', max_length=10) lan_network_chipset = models.CharField(default='', max_length=100) wlan_network_chipset = models.CharField(default='', max_length=100) does_usb2_work = models.CharField(default='', max_length=10) does_usb3_work = models.CharField(default='', max_length=10) does_optical_drive_work = models.CharField(default='', max_length=10) does_card_reader_work = models.CharField(default='', max_length=10) haiku_revision = models.CharField(default='', max_length=100) haiku_arch = models.CharField(default='', max_length=10) category = models.CharField(default='', max_length=100)
mit
wgcv/SWW-Crashphone
lib/python2.7/site-packages/django/contrib/sessions/tests.py
31
22770
import base64 from datetime import timedelta import os import shutil import string import tempfile import unittest import warnings from django.conf import settings from django.contrib.sessions.backends.db import SessionStore as DatabaseSession from django.contrib.sessions.backends.cache import SessionStore as CacheSession from django.contrib.sessions.backends.cached_db import SessionStore as CacheDBSession from django.contrib.sessions.backends.file import SessionStore as FileSession from django.contrib.sessions.backends.signed_cookies import SessionStore as CookieSession from django.contrib.sessions.models import Session from django.contrib.sessions.middleware import SessionMiddleware from django.core.cache import caches from django.core.cache.backends.base import InvalidCacheBackendError from django.core import management from django.core.exceptions import ImproperlyConfigured from django.http import HttpResponse from django.test import TestCase, RequestFactory, override_settings from django.test.utils import patch_logger from django.utils import six from django.utils import timezone from django.utils.six.moves import http_cookies from django.contrib.sessions.exceptions import InvalidSessionKey class SessionTestsMixin(object): # This does not inherit from TestCase to avoid any tests being run with this # class, which wouldn't work, and to allow different TestCase subclasses to # be used. backend = None # subclasses must specify def setUp(self): self.session = self.backend() def tearDown(self): # NB: be careful to delete any sessions created; stale sessions fill up # the /tmp (with some backends) and eventually overwhelm it after lots # of runs (think buildbots) self.session.delete() def test_new_session(self): self.assertFalse(self.session.modified) self.assertFalse(self.session.accessed) def test_get_empty(self): self.assertEqual(self.session.get('cat'), None) def test_store(self): self.session['cat'] = "dog" self.assertTrue(self.session.modified) self.assertEqual(self.session.pop('cat'), 'dog') def test_pop(self): self.session['some key'] = 'exists' # Need to reset these to pretend we haven't accessed it: self.accessed = False self.modified = False self.assertEqual(self.session.pop('some key'), 'exists') self.assertTrue(self.session.accessed) self.assertTrue(self.session.modified) self.assertEqual(self.session.get('some key'), None) def test_pop_default(self): self.assertEqual(self.session.pop('some key', 'does not exist'), 'does not exist') self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) def test_setdefault(self): self.assertEqual(self.session.setdefault('foo', 'bar'), 'bar') self.assertEqual(self.session.setdefault('foo', 'baz'), 'bar') self.assertTrue(self.session.accessed) self.assertTrue(self.session.modified) def test_update(self): self.session.update({'update key': 1}) self.assertTrue(self.session.accessed) self.assertTrue(self.session.modified) self.assertEqual(self.session.get('update key', None), 1) def test_has_key(self): self.session['some key'] = 1 self.session.modified = False self.session.accessed = False self.assertIn('some key', self.session) self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) def test_values(self): self.assertEqual(list(self.session.values()), []) self.assertTrue(self.session.accessed) self.session['some key'] = 1 self.assertEqual(list(self.session.values()), [1]) def test_iterkeys(self): self.session['x'] = 1 self.session.modified = False self.session.accessed = False i = six.iterkeys(self.session) self.assertTrue(hasattr(i, '__iter__')) self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) self.assertEqual(list(i), ['x']) def test_itervalues(self): self.session['x'] = 1 self.session.modified = False self.session.accessed = False i = six.itervalues(self.session) self.assertTrue(hasattr(i, '__iter__')) self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) self.assertEqual(list(i), [1]) def test_iteritems(self): self.session['x'] = 1 self.session.modified = False self.session.accessed = False i = six.iteritems(self.session) self.assertTrue(hasattr(i, '__iter__')) self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) self.assertEqual(list(i), [('x', 1)]) def test_clear(self): self.session['x'] = 1 self.session.modified = False self.session.accessed = False self.assertEqual(list(self.session.items()), [('x', 1)]) self.session.clear() self.assertEqual(list(self.session.items()), []) self.assertTrue(self.session.accessed) self.assertTrue(self.session.modified) def test_save(self): if (hasattr(self.session, '_cache') and 'DummyCache' in settings.CACHES[settings.SESSION_CACHE_ALIAS]['BACKEND']): raise unittest.SkipTest("Session saving tests require a real cache backend") self.session.save() self.assertTrue(self.session.exists(self.session.session_key)) def test_delete(self): self.session.save() self.session.delete(self.session.session_key) self.assertFalse(self.session.exists(self.session.session_key)) def test_flush(self): self.session['foo'] = 'bar' self.session.save() prev_key = self.session.session_key self.session.flush() self.assertFalse(self.session.exists(prev_key)) self.assertNotEqual(self.session.session_key, prev_key) self.assertTrue(self.session.modified) self.assertTrue(self.session.accessed) def test_cycle(self): self.session['a'], self.session['b'] = 'c', 'd' self.session.save() prev_key = self.session.session_key prev_data = list(self.session.items()) self.session.cycle_key() self.assertNotEqual(self.session.session_key, prev_key) self.assertEqual(list(self.session.items()), prev_data) def test_invalid_key(self): # Submitting an invalid session key (either by guessing, or if the db has # removed the key) results in a new key being generated. try: session = self.backend('1') try: session.save() except AttributeError: self.fail("The session object did not save properly. Middleware may be saving cache items without namespaces.") self.assertNotEqual(session.session_key, '1') self.assertEqual(session.get('cat'), None) session.delete() finally: # Some backends leave a stale cache entry for the invalid # session key; make sure that entry is manually deleted session.delete('1') def test_session_key_is_read_only(self): def set_session_key(session): session.session_key = session._get_new_session_key() self.assertRaises(AttributeError, set_session_key, self.session) # Custom session expiry def test_default_expiry(self): # A normal session has a max age equal to settings self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) # So does a custom session with an idle expiration time of 0 (but it'll # expire at browser close) self.session.set_expiry(0) self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) def test_custom_expiry_seconds(self): modification = timezone.now() self.session.set_expiry(10) date = self.session.get_expiry_date(modification=modification) self.assertEqual(date, modification + timedelta(seconds=10)) age = self.session.get_expiry_age(modification=modification) self.assertEqual(age, 10) def test_custom_expiry_timedelta(self): modification = timezone.now() # Mock timezone.now, because set_expiry calls it on this code path. original_now = timezone.now try: timezone.now = lambda: modification self.session.set_expiry(timedelta(seconds=10)) finally: timezone.now = original_now date = self.session.get_expiry_date(modification=modification) self.assertEqual(date, modification + timedelta(seconds=10)) age = self.session.get_expiry_age(modification=modification) self.assertEqual(age, 10) def test_custom_expiry_datetime(self): modification = timezone.now() self.session.set_expiry(modification + timedelta(seconds=10)) date = self.session.get_expiry_date(modification=modification) self.assertEqual(date, modification + timedelta(seconds=10)) age = self.session.get_expiry_age(modification=modification) self.assertEqual(age, 10) def test_custom_expiry_reset(self): self.session.set_expiry(None) self.session.set_expiry(10) self.session.set_expiry(None) self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) def test_get_expire_at_browser_close(self): # Tests get_expire_at_browser_close with different settings and different # set_expiry calls with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=False): self.session.set_expiry(10) self.assertFalse(self.session.get_expire_at_browser_close()) self.session.set_expiry(0) self.assertTrue(self.session.get_expire_at_browser_close()) self.session.set_expiry(None) self.assertFalse(self.session.get_expire_at_browser_close()) with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=True): self.session.set_expiry(10) self.assertFalse(self.session.get_expire_at_browser_close()) self.session.set_expiry(0) self.assertTrue(self.session.get_expire_at_browser_close()) self.session.set_expiry(None) self.assertTrue(self.session.get_expire_at_browser_close()) def test_decode(self): # Ensure we can decode what we encode data = {'a test key': 'a test value'} encoded = self.session.encode(data) self.assertEqual(self.session.decode(encoded), data) def test_decode_failure_logged_to_security(self): bad_encode = base64.b64encode(b'flaskdj:alkdjf') with patch_logger('django.security.SuspiciousSession', 'warning') as calls: self.assertEqual({}, self.session.decode(bad_encode)) # check that the failed decode is logged self.assertEqual(len(calls), 1) self.assertTrue('corrupted' in calls[0]) def test_actual_expiry(self): # this doesn't work with JSONSerializer (serializing timedelta) with override_settings(SESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer'): self.session = self.backend() # reinitialize after overriding settings # Regression test for #19200 old_session_key = None new_session_key = None try: self.session['foo'] = 'bar' self.session.set_expiry(-timedelta(seconds=10)) self.session.save() old_session_key = self.session.session_key # With an expiry date in the past, the session expires instantly. new_session = self.backend(self.session.session_key) new_session_key = new_session.session_key self.assertNotIn('foo', new_session) finally: self.session.delete(old_session_key) self.session.delete(new_session_key) class DatabaseSessionTests(SessionTestsMixin, TestCase): backend = DatabaseSession def test_session_get_decoded(self): """ Test we can use Session.get_decoded to retrieve data stored in normal way """ self.session['x'] = 1 self.session.save() s = Session.objects.get(session_key=self.session.session_key) self.assertEqual(s.get_decoded(), {'x': 1}) def test_sessionmanager_save(self): """ Test SessionManager.save method """ # Create a session self.session['y'] = 1 self.session.save() s = Session.objects.get(session_key=self.session.session_key) # Change it Session.objects.save(s.session_key, {'y': 2}, s.expire_date) # Clear cache, so that it will be retrieved from DB del self.session._session_cache self.assertEqual(self.session['y'], 2) @override_settings(SESSION_ENGINE="django.contrib.sessions.backends.db") def test_clearsessions_command(self): """ Test clearsessions command for clearing expired sessions. """ self.assertEqual(0, Session.objects.count()) # One object in the future self.session['foo'] = 'bar' self.session.set_expiry(3600) self.session.save() # One object in the past other_session = self.backend() other_session['foo'] = 'bar' other_session.set_expiry(-3600) other_session.save() # Two sessions are in the database before clearsessions... self.assertEqual(2, Session.objects.count()) management.call_command('clearsessions') # ... and one is deleted. self.assertEqual(1, Session.objects.count()) @override_settings(USE_TZ=True) class DatabaseSessionWithTimeZoneTests(DatabaseSessionTests): pass class CacheDBSessionTests(SessionTestsMixin, TestCase): backend = CacheDBSession @unittest.skipIf('DummyCache' in settings.CACHES[settings.SESSION_CACHE_ALIAS]['BACKEND'], "Session saving tests require a real cache backend") def test_exists_searches_cache_first(self): self.session.save() with self.assertNumQueries(0): self.assertTrue(self.session.exists(self.session.session_key)) def test_load_overlong_key(self): # Some backends might issue a warning with warnings.catch_warnings(): warnings.simplefilter("ignore") self.session._session_key = (string.ascii_letters + string.digits) * 20 self.assertEqual(self.session.load(), {}) @override_settings(SESSION_CACHE_ALIAS='sessions') def test_non_default_cache(self): # 21000 - CacheDB backend should respect SESSION_CACHE_ALIAS. self.assertRaises(InvalidCacheBackendError, self.backend) @override_settings(USE_TZ=True) class CacheDBSessionWithTimeZoneTests(CacheDBSessionTests): pass # Don't need DB flushing for these tests, so can use unittest.TestCase as base class class FileSessionTests(SessionTestsMixin, unittest.TestCase): backend = FileSession def setUp(self): # Do file session tests in an isolated directory, and kill it after we're done. self.original_session_file_path = settings.SESSION_FILE_PATH self.temp_session_store = settings.SESSION_FILE_PATH = tempfile.mkdtemp() # Reset the file session backend's internal caches if hasattr(self.backend, '_storage_path'): del self.backend._storage_path super(FileSessionTests, self).setUp() def tearDown(self): super(FileSessionTests, self).tearDown() settings.SESSION_FILE_PATH = self.original_session_file_path shutil.rmtree(self.temp_session_store) @override_settings( SESSION_FILE_PATH="/if/this/directory/exists/you/have/a/weird/computer") def test_configuration_check(self): del self.backend._storage_path # Make sure the file backend checks for a good storage dir self.assertRaises(ImproperlyConfigured, self.backend) def test_invalid_key_backslash(self): # Ensure we don't allow directory-traversal. # This is tested directly on _key_to_file, as load() will swallow # a SuspiciousOperation in the same way as an IOError - by creating # a new session, making it unclear whether the slashes were detected. self.assertRaises(InvalidSessionKey, self.backend()._key_to_file, "a\\b\\c") def test_invalid_key_forwardslash(self): # Ensure we don't allow directory-traversal self.assertRaises(InvalidSessionKey, self.backend()._key_to_file, "a/b/c") @override_settings(SESSION_ENGINE="django.contrib.sessions.backends.file") def test_clearsessions_command(self): """ Test clearsessions command for clearing expired sessions. """ storage_path = self.backend._get_storage_path() file_prefix = settings.SESSION_COOKIE_NAME def count_sessions(): return len([session_file for session_file in os.listdir(storage_path) if session_file.startswith(file_prefix)]) self.assertEqual(0, count_sessions()) # One object in the future self.session['foo'] = 'bar' self.session.set_expiry(3600) self.session.save() # One object in the past other_session = self.backend() other_session['foo'] = 'bar' other_session.set_expiry(-3600) other_session.save() # Two sessions are in the filesystem before clearsessions... self.assertEqual(2, count_sessions()) management.call_command('clearsessions') # ... and one is deleted. self.assertEqual(1, count_sessions()) class CacheSessionTests(SessionTestsMixin, unittest.TestCase): backend = CacheSession def test_load_overlong_key(self): # Some backends might issue a warning with warnings.catch_warnings(): warnings.simplefilter("ignore") self.session._session_key = (string.ascii_letters + string.digits) * 20 self.assertEqual(self.session.load(), {}) def test_default_cache(self): self.session.save() self.assertNotEqual(caches['default'].get(self.session.cache_key), None) @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', }, 'sessions': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'session', }, }, SESSION_CACHE_ALIAS='sessions') def test_non_default_cache(self): # Re-initialize the session backend to make use of overridden settings. self.session = self.backend() self.session.save() self.assertEqual(caches['default'].get(self.session.cache_key), None) self.assertNotEqual(caches['sessions'].get(self.session.cache_key), None) class SessionMiddlewareTests(unittest.TestCase): @override_settings(SESSION_COOKIE_SECURE=True) def test_secure_session_cookie(self): request = RequestFactory().get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Simulate a request the modifies the session middleware.process_request(request) request.session['hello'] = 'world' # Handle the response through the middleware response = middleware.process_response(request, response) self.assertTrue( response.cookies[settings.SESSION_COOKIE_NAME]['secure']) @override_settings(SESSION_COOKIE_HTTPONLY=True) def test_httponly_session_cookie(self): request = RequestFactory().get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Simulate a request the modifies the session middleware.process_request(request) request.session['hello'] = 'world' # Handle the response through the middleware response = middleware.process_response(request, response) self.assertTrue( response.cookies[settings.SESSION_COOKIE_NAME]['httponly']) self.assertIn(http_cookies.Morsel._reserved['httponly'], str(response.cookies[settings.SESSION_COOKIE_NAME])) @override_settings(SESSION_COOKIE_HTTPONLY=False) def test_no_httponly_session_cookie(self): request = RequestFactory().get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Simulate a request the modifies the session middleware.process_request(request) request.session['hello'] = 'world' # Handle the response through the middleware response = middleware.process_response(request, response) self.assertFalse(response.cookies[settings.SESSION_COOKIE_NAME]['httponly']) self.assertNotIn(http_cookies.Morsel._reserved['httponly'], str(response.cookies[settings.SESSION_COOKIE_NAME])) def test_session_save_on_500(self): request = RequestFactory().get('/') response = HttpResponse('Horrible error') response.status_code = 500 middleware = SessionMiddleware() # Simulate a request the modifies the session middleware.process_request(request) request.session['hello'] = 'world' # Handle the response through the middleware response = middleware.process_response(request, response) # Check that the value wasn't saved above. self.assertNotIn('hello', request.session.load()) class CookieSessionTests(SessionTestsMixin, TestCase): backend = CookieSession def test_save(self): """ This test tested exists() in the other session backends, but that doesn't make sense for us. """ pass def test_cycle(self): """ This test tested cycle_key() which would create a new session key for the same session data. But we can't invalidate previously signed cookies (other than letting them expire naturally) so testing for this behavior is meaningless. """ pass @unittest.expectedFailure def test_actual_expiry(self): # The cookie backend doesn't handle non-default expiry dates, see #19201 super(CookieSessionTests, self).test_actual_expiry()
apache-2.0
TornikeNatsvlishvili/GeorgianAutoComplete
backend/app.py
1
1103
from flask import Flask, request, jsonify import heapq import logging import trie server = Flask(__name__, static_url_path='') LOGGING_FILE_NAME = 'log.txt' NUM_SUGGESTIONS_TO_RETURN = 10 single_word_trie = None def init(): global single_word_trie logging.basicConfig(filename=LOGGING_FILE_NAME, level=logging.DEBUG) print("initializing word store...") # load autocomplete single_word_trie = trie.load_kb("0.txt") print("done") init() @server.route('/') def main(): return server.send_static_file('index.html') @server.route('/suggestion') def suggestion(): if 'q' not in request.args: return 500 query = request.args['q'] context = request.args.get('c', '') candidates = single_word_trie.get_all_data_with_prefix(query) sorted_candidates = sorted(candidates, key = lambda word: word[1], reverse=True)[:NUM_SUGGESTIONS_TO_RETURN] suggestions = [word for word, count in sorted_candidates] return jsonify({'suggestions': suggestions[:NUM_SUGGESTIONS_TO_RETURN]}) if __name__ == '__main__': server.run(host="0.0.0.0", port=8080)
mit
handspring/bite-project
tools/bugs/server/appengine/handlers/bugs/create.py
17
2214
# Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Create a new bug entry.""" __author__ = '[email protected] (Jason Stredwick)' import logging import webapp2 from bugs import kind from bugs.models.bugs import bug from bugs.providers import services from common.handlers import base class Error(base.Error): pass class CreateHandler(base.BaseHandler): """Create a new bug entry.""" # Disable 'Invalid method name' lint error. # pylint: disable-msg=C6409 def post(self): """Create a new bug entry with the given data. Raises: Error: Raised if the data fails to be JSON parsed/stringified or is not present. """ logging.info('New bug handler; bugs.handlers.bugs.create.CreateHandler') # TODO (jason.stredwick): Figure out the correct failure strategy if a new # bug is created but either the url/bug mapping or pusher fails. try: data = self.GetData(kind.Kind.BUG) bug_model = bug.Create(data) id = bug_model.key().id() services.Index(id) services.Push(id) self.WriteResponse({'kind': kind.Kind.ID, 'id': id}) except bug.CreateError, e: raise Error('Failed to create a new bug.\n%s\n' % e, code=400) except services.PushError: raise Error('Failed to push new bug [id=%s].\n' % id, code=400) except services.IndexError: raise Error('Failed to create index for new bug [id=%s].\n' % id, code=400) except base.Error, e: raise Error(e) routes = [ webapp2.Route(r'/bugs', handler=CreateHandler, name='bugs_create', methods=['POST']) ] app = webapp2.WSGIApplication(routes, debug=True)
apache-2.0
uber/pyro
tests/contrib/gp/test_models.py
1
15173
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import logging from collections import namedtuple import pytest import torch import pyro.distributions as dist from pyro.contrib.gp.kernels import Cosine, Matern32, RBF, WhiteNoise from pyro.contrib.gp.likelihoods import Gaussian from pyro.contrib.gp.models import (GPLVM, GPRegression, SparseGPRegression, VariationalGP, VariationalSparseGP) from pyro.contrib.gp.util import train from pyro.infer.mcmc.hmc import HMC from pyro.infer.mcmc.api import MCMC from pyro.nn.module import PyroSample from tests.common import assert_equal logger = logging.getLogger(__name__) T = namedtuple("TestGPModel", ["model_class", "X", "y", "kernel", "likelihood"]) X = torch.tensor([[1., 5., 3.], [4., 3., 7.]]) y1D = torch.tensor([2., 1.]) y2D = torch.tensor([[1., 2.], [3., 3.], [1., 4.], [-1., 1.]]) noise = torch.tensor(1e-7) def _kernel(): return RBF(input_dim=3, variance=torch.tensor(3.), lengthscale=torch.tensor(2.)) def _likelihood(): return Gaussian(torch.tensor(1e-7)) def _TEST_CASES(): TEST_CASES = [ T( GPRegression, X, y1D, _kernel(), noise ), T( GPRegression, X, y2D, _kernel(), noise ), T( SparseGPRegression, X, y1D, _kernel(), noise ), T( SparseGPRegression, X, y2D, _kernel(), noise ), T( VariationalGP, X, y1D, _kernel(), _likelihood() ), T( VariationalGP, X, y2D, _kernel(), _likelihood() ), T( VariationalSparseGP, X, y1D, _kernel(), _likelihood() ), T( VariationalSparseGP, X, y2D, _kernel(), _likelihood() ), ] return TEST_CASES TEST_IDS = [t[0].__name__ + "_y{}D".format(str(t[2].dim())) for t in _TEST_CASES()] @pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS) def test_model(model_class, X, y, kernel, likelihood): if model_class is SparseGPRegression or model_class is VariationalSparseGP: gp = model_class(X, None, kernel, X, likelihood) else: gp = model_class(X, None, kernel, likelihood) loc, var = gp.model() if model_class is VariationalGP or model_class is VariationalSparseGP: assert_equal(loc.norm().item(), 0) assert_equal(var, torch.ones(var.shape[-1]).expand(var.shape)) else: assert_equal(loc.norm().item(), 0) assert_equal(var, kernel(X).diag()) @pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS) def test_forward(model_class, X, y, kernel, likelihood): if model_class is SparseGPRegression or model_class is VariationalSparseGP: gp = model_class(X, y, kernel, X, likelihood) else: gp = model_class(X, y, kernel, likelihood) # test shape Xnew = torch.tensor([[2.0, 3.0, 1.0]]) loc0, cov0 = gp(Xnew, full_cov=True) loc1, var1 = gp(Xnew, full_cov=False) assert loc0.dim() == y.dim() assert loc0.shape[-1] == Xnew.shape[0] # test latent shape assert loc0.shape[:-1] == y.shape[:-1] assert cov0.shape[:-2] == y.shape[:-1] assert cov0.shape[-1] == cov0.shape[-2] assert cov0.shape[-1] == Xnew.shape[0] assert_equal(loc0, loc1) n = Xnew.shape[0] cov0_diag = torch.stack([mat.diag() for mat in cov0.view(-1, n, n)]).reshape(var1.shape) assert_equal(cov0_diag, var1) # test trivial forward: Xnew = X loc, cov = gp(X, full_cov=True) if model_class is VariationalGP or model_class is VariationalSparseGP: assert_equal(loc.norm().item(), 0) assert_equal(cov, torch.eye(cov.shape[-1]).expand(cov.shape)) else: assert_equal(loc, y) assert_equal(cov.norm().item(), 0) # test same input forward: Xnew[0,:] = Xnew[1,:] = ... Xnew = torch.tensor([[2.0, 3.0, 1.0]]).expand(10, 3) loc, cov = gp(Xnew, full_cov=True) loc_diff = loc - loc[..., :1].expand(y.shape[:-1] + (10,)) assert_equal(loc_diff.norm().item(), 0) cov_diff = cov - cov[..., :1, :1].expand(y.shape[:-1] + (10, 10)) assert_equal(cov_diff.norm().item(), 0) # test noise kernel forward: kernel = WhiteNoise gp.kernel = WhiteNoise(input_dim=3, variance=torch.tensor(10.)) loc, cov = gp(X, full_cov=True) assert_equal(loc.norm().item(), 0) assert_equal(cov, torch.eye(cov.shape[-1]).expand(cov.shape) * 10) @pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS) def test_forward_with_empty_latent_shape(model_class, X, y, kernel, likelihood): # regression models don't use latent_shape, no need for test if model_class is GPRegression or model_class is SparseGPRegression: return elif model_class is VariationalGP: gp = model_class(X, y, kernel, likelihood, latent_shape=torch.Size([])) else: # model_class is VariationalSparseGP gp = model_class(X, y, kernel, X, likelihood, latent_shape=torch.Size([])) # test shape Xnew = torch.tensor([[2.0, 3.0, 1.0]]) loc0, cov0 = gp(Xnew, full_cov=True) loc1, var1 = gp(Xnew, full_cov=False) assert loc0.shape[-1] == Xnew.shape[0] assert cov0.shape[-1] == cov0.shape[-2] assert cov0.shape[-1] == Xnew.shape[0] # test latent shape assert loc0.shape[:-1] == torch.Size([]) assert cov0.shape[:-2] == torch.Size([]) assert_equal(loc0, loc1) assert_equal(cov0.diag(), var1) @pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS) @pytest.mark.init(rng_seed=0) def test_inference(model_class, X, y, kernel, likelihood): # skip variational GP models because variance/lengthscale highly # depend on variational parameters if model_class is VariationalGP or model_class is VariationalSparseGP: return elif model_class is GPRegression: gp = model_class(X, y, RBF(input_dim=3), likelihood) else: # model_class is SparseGPRegression gp = model_class(X, y, RBF(input_dim=3), X, likelihood) # fix inducing points because variance/lengthscale highly depend on it gp.Xu.requires_grad_(False) generator = dist.MultivariateNormal(torch.zeros(X.shape[0]), kernel(X)) target_y = generator(sample_shape=torch.Size([1000])).detach() gp.set_data(X, target_y) train(gp) y_cov = gp.kernel(X) target_y_cov = kernel(X) assert_equal(y_cov, target_y_cov, prec=0.15) @pytest.mark.init(rng_seed=0) def test_inference_sgpr(): N = 1000 X = dist.Uniform(torch.zeros(N), torch.ones(N)*5).sample() y = 0.5 * torch.sin(3*X) + dist.Normal(torch.zeros(N), torch.ones(N)*0.5).sample() kernel = RBF(input_dim=1) Xu = torch.arange(0., 5.5, 0.5) sgpr = SparseGPRegression(X, y, kernel, Xu) train(sgpr) Xnew = torch.arange(0., 5.05, 0.05) loc, var = sgpr(Xnew, full_cov=False) target = 0.5 * torch.sin(3*Xnew) assert_equal((loc - target).abs().mean().item(), 0, prec=0.07) @pytest.mark.init(rng_seed=0) def test_inference_vsgp(): N = 1000 X = dist.Uniform(torch.zeros(N), torch.ones(N)*5).sample() y = 0.5 * torch.sin(3*X) + dist.Normal(torch.zeros(N), torch.ones(N)*0.5).sample() kernel = RBF(input_dim=1) Xu = torch.arange(0., 5.5, 0.5) vsgp = VariationalSparseGP(X, y, kernel, Xu, Gaussian()) optimizer = torch.optim.Adam(vsgp.parameters(), lr=0.03) train(vsgp, optimizer) Xnew = torch.arange(0., 5.05, 0.05) loc, var = vsgp(Xnew, full_cov=False) target = 0.5 * torch.sin(3*Xnew) assert_equal((loc - target).abs().mean().item(), 0, prec=0.06) @pytest.mark.init(rng_seed=0) def test_inference_whiten_vsgp(): N = 1000 X = dist.Uniform(torch.zeros(N), torch.ones(N)*5).sample() y = 0.5 * torch.sin(3*X) + dist.Normal(torch.zeros(N), torch.ones(N)*0.5).sample() kernel = RBF(input_dim=1) Xu = torch.arange(0., 5.5, 0.5) vsgp = VariationalSparseGP(X, y, kernel, Xu, Gaussian(), whiten=True) train(vsgp) Xnew = torch.arange(0., 5.05, 0.05) loc, var = vsgp(Xnew, full_cov=False) target = 0.5 * torch.sin(3*Xnew) assert_equal((loc - target).abs().mean().item(), 0, prec=0.07) @pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS) def test_inference_with_empty_latent_shape(model_class, X, y, kernel, likelihood): # regression models don't use latent_shape (default=torch.Size([])) if model_class is GPRegression or model_class is SparseGPRegression: return elif model_class is VariationalGP: gp = model_class(X, y, kernel, likelihood, latent_shape=torch.Size([])) else: # model_class is SparseVariationalGP gp = model_class(X, y, kernel, X.clone(), likelihood, latent_shape=torch.Size([])) train(gp, num_steps=1) @pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS) def test_inference_with_whiten(model_class, X, y, kernel, likelihood): # regression models don't use whiten if model_class is GPRegression or model_class is SparseGPRegression: return elif model_class is VariationalGP: gp = model_class(X, y, kernel, likelihood, whiten=True) else: # model_class is SparseVariationalGP gp = model_class(X, y, kernel, X.clone(), likelihood, whiten=True) train(gp, num_steps=1) @pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS) def test_hmc(model_class, X, y, kernel, likelihood): if model_class is SparseGPRegression or model_class is VariationalSparseGP: gp = model_class(X, y, kernel, X.clone(), likelihood) else: gp = model_class(X, y, kernel, likelihood) kernel.variance = PyroSample(dist.Uniform(torch.tensor(0.5), torch.tensor(1.5))) kernel.lengthscale = PyroSample(dist.Uniform(torch.tensor(1.0), torch.tensor(3.0))) hmc_kernel = HMC(gp.model, step_size=1) mcmc = MCMC(hmc_kernel, num_samples=10) mcmc.run() for name, param in mcmc.get_samples().items(): param_mean = torch.mean(param, 0) logger.info("Posterior mean - {}".format(name)) logger.info(param_mean) def test_inference_deepGP(): gp1 = GPRegression(X, None, RBF(input_dim=3, variance=torch.tensor(3.), lengthscale=torch.tensor(2.))) Z, _ = gp1.model() gp2 = VariationalSparseGP(Z, y2D, Matern32(input_dim=3), Z.clone(), Gaussian(torch.tensor(1e-6))) class DeepGP(torch.nn.Module): def __init__(self, gp1, gp2): super().__init__() self.gp1 = gp1 self.gp2 = gp2 def model(self): Z, _ = self.gp1.model() self.gp2.set_data(Z, y2D) self.gp2.model() def guide(self): self.gp1.guide() self.gp2.guide() deepgp = DeepGP(gp1, gp2) train(deepgp, num_steps=1) @pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS) def test_gplvm(model_class, X, y, kernel, likelihood): if model_class is SparseGPRegression or model_class is VariationalSparseGP: gp = model_class(X, y, kernel, X.clone(), likelihood) else: gp = model_class(X, y, kernel, likelihood) gplvm = GPLVM(gp) # test inference train(gplvm, num_steps=1) # test forward gplvm(Xnew=X) def _pre_test_mean_function(): def f(x): return 2 * x + 3 + 5 * torch.sin(7 * x) X = torch.arange(100, dtype=torch.Tensor().dtype) y = f(X) Xnew = torch.arange(100, 150, dtype=torch.Tensor().dtype) ynew = f(Xnew) kernel = Cosine(input_dim=1) class Trend(torch.nn.Module): def __init__(self): super().__init__() self.a = torch.nn.Parameter(torch.tensor(0.)) self.b = torch.nn.Parameter(torch.tensor(1.)) def forward(self, x): return self.a * x + self.b trend = Trend() return X, y, Xnew, ynew, kernel, trend def _mape(y_true, y_pred): return ((y_pred - y_true) / y_true).abs().mean() def _post_test_mean_function(gpmodule, Xnew, y_true): assert_equal(gpmodule.mean_function.a.item(), 2, prec=0.03) assert_equal(gpmodule.mean_function.b.item(), 3, prec=0.03) y_pred, _ = gpmodule(Xnew) assert_equal(_mape(y_true, y_pred).item(), 0, prec=0.02) def test_mean_function_GPR(): X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function() gpmodule = GPRegression(X, y, kernel, mean_function=mean_fn) train(gpmodule) _post_test_mean_function(gpmodule, Xnew, ynew) def test_mean_function_SGPR(): X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function() Xu = X[::20].clone() gpmodule = SparseGPRegression(X, y, kernel, Xu, mean_function=mean_fn) train(gpmodule) _post_test_mean_function(gpmodule, Xnew, ynew) def test_mean_function_SGPR_DTC(): X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function() Xu = X[::20].clone() gpmodule = SparseGPRegression(X, y, kernel, Xu, mean_function=mean_fn, approx="DTC") train(gpmodule) _post_test_mean_function(gpmodule, Xnew, ynew) def test_mean_function_SGPR_FITC(): X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function() Xu = X[::20].clone() gpmodule = SparseGPRegression(X, y, kernel, Xu, mean_function=mean_fn, approx="FITC") train(gpmodule) _post_test_mean_function(gpmodule, Xnew, ynew) def test_mean_function_VGP(): X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function() likelihood = Gaussian() gpmodule = VariationalGP(X, y, kernel, likelihood, mean_function=mean_fn) train(gpmodule) _post_test_mean_function(gpmodule, Xnew, ynew) def test_mean_function_VGP_whiten(): X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function() likelihood = Gaussian() gpmodule = VariationalGP(X, y, kernel, likelihood, mean_function=mean_fn, whiten=True) optimizer = torch.optim.Adam(gpmodule.parameters(), lr=0.1) train(gpmodule, optimizer) _post_test_mean_function(gpmodule, Xnew, ynew) def test_mean_function_VSGP(): X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function() Xu = X[::20].clone() likelihood = Gaussian() gpmodule = VariationalSparseGP(X, y, kernel, Xu, likelihood, mean_function=mean_fn) optimizer = torch.optim.Adam(gpmodule.parameters(), lr=0.02) train(gpmodule, optimizer) _post_test_mean_function(gpmodule, Xnew, ynew) def test_mean_function_VSGP_whiten(): X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function() Xu = X[::20].clone() likelihood = Gaussian() gpmodule = VariationalSparseGP(X, y, kernel, Xu, likelihood, mean_function=mean_fn, whiten=True) optimizer = torch.optim.Adam(gpmodule.parameters(), lr=0.1) train(gpmodule, optimizer) _post_test_mean_function(gpmodule, Xnew, ynew)
apache-2.0
crowdworks/redash
redash/handlers/embed.py
4
3657
from __future__ import absolute_import import logging import time import pystache from flask import request from .authentication import current_org from flask_login import current_user, login_required from flask_restful import abort from redash import models, utils from redash.handlers import routes from redash.handlers.base import (get_object_or_404, org_scoped_rule, record_event) from redash.handlers.query_results import collect_query_parameters from redash.handlers.static import render_index from redash.utils import gen_query_hash # # Run a parameterized query synchronously and return the result # DISCLAIMER: Temporary solution to support parameters in queries. Should be # removed once we refactor the query results API endpoints and handling # on the client side. Please don't reuse in other API handlers. # def run_query_sync(data_source, parameter_values, query_text, max_age=0): query_parameters = set(collect_query_parameters(query_text)) missing_params = set(query_parameters) - set(parameter_values.keys()) if missing_params: raise Exception('Missing parameter value for: {}'.format(", ".join(missing_params))) if query_parameters: query_text = pystache.render(query_text, parameter_values) if max_age <= 0: query_result = None else: query_result = models.QueryResult.get_latest(data_source, query_text, max_age) query_hash = gen_query_hash(query_text) if query_result: logging.info("Returning cached result for query %s" % query_hash) return query_result.data try: started_at = time.time() data, error = data_source.query_runner.run_query(query_text, current_user) if error: return None # update cache if max_age > 0: run_time = time.time() - started_at query_result, updated_query_ids = models.QueryResult.store_result(data_source.org_id, data_source.id, query_hash, query_text, data, run_time, utils.utcnow()) models.db.session.commit() return data except Exception: if max_age > 0: abort(404, message="Unable to get result from the database, and no cached query result found.") else: abort(503, message="Unable to get result from the database.") return None @routes.route(org_scoped_rule('/embed/query/<query_id>/visualization/<visualization_id>'), methods=['GET']) @login_required def embed(query_id, visualization_id, org_slug=None): record_event(current_org, current_user._get_current_object(), { 'action': 'view', 'object_id': visualization_id, 'object_type': 'visualization', 'query_id': query_id, 'embed': True, 'referer': request.headers.get('Referer') }) return render_index() @routes.route(org_scoped_rule('/public/dashboards/<token>'), methods=['GET']) @login_required def public_dashboard(token, org_slug=None): if current_user.is_api_user(): dashboard = current_user.object else: api_key = get_object_or_404(models.ApiKey.get_by_api_key, token) dashboard = api_key.object record_event(current_org, current_user, { 'action': 'view', 'object_id': dashboard.id, 'object_type': 'dashboard', 'public': True, 'headless': 'embed' in request.args, 'referer': request.headers.get('Referer') }) return render_index()
bsd-2-clause
dolph/keystone-workout
keystoneworkout/cli/subcommands.py
1
8625
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import uuid import keystoneclient from keystoneclient.v2_0 import client as client_v2 from keystoneclient.v3 import client from keystoneworkout import benchmark ADMIN_USERNAME = 'admin' ADMIN_PASSWORD = 'secrete' ADMIN_PROJECT_NAME = 'admin' ADMIN_ROLE_NAME = 'admin' def uid(): return uuid.uuid4().hex[:6] class SubCommand(object): command = None @classmethod def configure_parser(cls, parser): pass class AdminCommand(object): def get_admin_client(self, args): """Authenticates as admin using the "long" auth flow.""" c = client.Client( debug=args.debug, username=ADMIN_USERNAME, password=ADMIN_PASSWORD, auth_url=args.os_endpoint) c.management_url = args.os_endpoint # FIXME # find a project that we have access to project = c.projects.list(user=c.auth_ref.user_id).pop() return client.Client( debug=args.debug, token=c.auth_token, project_id=project.id, auth_url=args.os_endpoint) class Bootstrap(SubCommand): """Wrapper to call bootstrap-admin and bootstrap-catalog in sequence.""" command = 'bootstrap' def __call__(self, args): BootstrapAdmin()(args) BootstrapCatalog()(args) class BootstrapAdmin(SubCommand): """Bootstraps an admin user using a pre-existing token & endpoint. For the purpose of bootstrapping, the token is assumed to be keystone.conf's admin_token, and the endpoint is assumed to refer to the v3 API. """ command = 'bootstrap-admin' def _get_by_name(self, manager, name): collection = manager.list(name=name) collection_by_name = dict((x.name, x) for x in collection) return collection_by_name[name] def __call__(self, args): c = client.Client( debug=args.debug, token=args.os_token, endpoint=args.os_endpoint) try: user = c.users.create( name=ADMIN_USERNAME, domain=args.default_domain_id, password=ADMIN_PASSWORD) except keystoneclient.exceptions.Conflict: user = self._get_by_name(c.users, ADMIN_USERNAME) else: print 'Created user', user.name try: project = c.projects.create( name=ADMIN_PROJECT_NAME, domain=args.default_domain_id) except keystoneclient.exceptions.Conflict: project = self._get_by_name(c.projects, ADMIN_PROJECT_NAME) else: print 'Created project', project.name try: role = c.roles.create( name=ADMIN_ROLE_NAME) except keystoneclient.exceptions.Conflict: role = self._get_by_name(c.roles, ADMIN_ROLE_NAME) else: print 'Created role', role.name try: c.roles.check( user=user, project=project, role=role) except keystoneclient.exceptions.NotFound: c.roles.grant( user=user, project=project, role=role) print 'Assigned role', role.name, print 'to user', user.name, print 'on project', project.name # try to authenticate as our new admin user c = client.Client( debug=args.debug, username=ADMIN_USERNAME, password=ADMIN_PASSWORD, project_name=ADMIN_PROJECT_NAME, auth_url=args.os_endpoint) class BootstrapCatalog(SubCommand, AdminCommand): command = 'bootstrap-catalog' def __call__(self, args): c = client.Client( debug=args.debug, token=args.os_token, endpoint=args.os_endpoint) services_by_type = dict((x.type, x) for x in c.services.list()) if 'identity' in services_by_type: identity = services_by_type['identity'] else: identity = c.services.create( name='keystone', type='identity') identity_endpoints_by_interface = dict( (x.interface, x) for x in c.endpoints.list() if x.service_id == identity.id) if 'admin' not in identity_endpoints_by_interface: c.endpoints.create( service=identity, interface='admin', url=args.os_endpoint) if 'internal' not in identity_endpoints_by_interface: c.endpoints.create( service=identity, interface='internal', url=args.os_endpoint) if 'public' not in identity_endpoints_by_interface: c.endpoints.create( service=identity, interface='public', url=args.os_endpoint) class BenchmarkV3Auth(SubCommand, AdminCommand): command = 'benchmark-auth-v3-long' @classmethod def configure_parser(cls, parser): parser.add_argument( '--concurrency', '-c', type=int, default=10, help='Total number of threads to utilize in each benchmark') parser.add_argument( '--iterations', '-n', type=int, default=10, help='Total number of task iterations each thread must perform') def __call__(self, args): @benchmark.Benchmark( concurrency=args.concurrency, iterations=args.iterations) def long_authentication_flow(username, password, iterations=args.iterations): for _ in range(iterations): c = client.Client( debug=args.debug, username=username, password=password, auth_url=args.os_endpoint) c.management_url = args.os_endpoint # FIXME # find a project that we have access to project = c.projects.list(user=c.auth_ref.user_id).pop() c = client.Client( debug=args.debug, token=c.auth_token, project_id=project.id, auth_url=args.os_endpoint) c.authenticate() long_authentication_flow(ADMIN_USERNAME, ADMIN_PASSWORD) class BenchmarkV2Auth(SubCommand, AdminCommand): command = 'benchmark-auth-v2-short' @classmethod def configure_parser(cls, parser): parser.add_argument( '--concurrency', '-c', type=int, default=10, help='Total number of threads to utilize in each benchmark') parser.add_argument( '--iterations', '-n', type=int, default=10, help='Total number of task iterations each thread must perform') def __call__(self, args): @benchmark.Benchmark( concurrency=args.concurrency, iterations=args.iterations) def short_authentication_flow(username, password, tenant_name, iterations=args.iterations): for _ in range(iterations): c = client_v2.Client( debug=args.debug, username=username, password=password, tenant_name=tenant_name, auth_url=args.os_endpoint) c.authenticate() # create a v2 admin client c = client_v2.Client( debug=args.debug, token=args.os_token, endpoint=args.os_endpoint) # create a tenant tenant_name = uuid.uuid4().hex tenant = c.tenants.create(tenant_name) # create a user with a default tenant username = uuid.uuid4().hex password = uuid.uuid4().hex c.users.create( name=username, password=password, email=None, tenant_id=tenant.id) short_authentication_flow(username, password, tenant_name)
apache-2.0
alfredodeza/boto
boto/manage/volume.py
153
16296
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/ # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. from __future__ import print_function from boto.sdb.db.model import Model from boto.sdb.db.property import StringProperty, IntegerProperty, ListProperty, ReferenceProperty, CalculatedProperty from boto.manage.server import Server from boto.manage import propget import boto.utils import boto.ec2 import time import traceback from contextlib import closing import datetime class CommandLineGetter(object): def get_region(self, params): if not params.get('region', None): prop = self.cls.find_property('region_name') params['region'] = propget.get(prop, choices=boto.ec2.regions) def get_zone(self, params): if not params.get('zone', None): prop = StringProperty(name='zone', verbose_name='EC2 Availability Zone', choices=self.ec2.get_all_zones) params['zone'] = propget.get(prop) def get_name(self, params): if not params.get('name', None): prop = self.cls.find_property('name') params['name'] = propget.get(prop) def get_size(self, params): if not params.get('size', None): prop = IntegerProperty(name='size', verbose_name='Size (GB)') params['size'] = propget.get(prop) def get_mount_point(self, params): if not params.get('mount_point', None): prop = self.cls.find_property('mount_point') params['mount_point'] = propget.get(prop) def get_device(self, params): if not params.get('device', None): prop = self.cls.find_property('device') params['device'] = propget.get(prop) def get(self, cls, params): self.cls = cls self.get_region(params) self.ec2 = params['region'].connect() self.get_zone(params) self.get_name(params) self.get_size(params) self.get_mount_point(params) self.get_device(params) class Volume(Model): name = StringProperty(required=True, unique=True, verbose_name='Name') region_name = StringProperty(required=True, verbose_name='EC2 Region') zone_name = StringProperty(required=True, verbose_name='EC2 Zone') mount_point = StringProperty(verbose_name='Mount Point') device = StringProperty(verbose_name="Device Name", default='/dev/sdp') volume_id = StringProperty(required=True) past_volume_ids = ListProperty(item_type=str) server = ReferenceProperty(Server, collection_name='volumes', verbose_name='Server Attached To') volume_state = CalculatedProperty(verbose_name="Volume State", calculated_type=str, use_method=True) attachment_state = CalculatedProperty(verbose_name="Attachment State", calculated_type=str, use_method=True) size = CalculatedProperty(verbose_name="Size (GB)", calculated_type=int, use_method=True) @classmethod def create(cls, **params): getter = CommandLineGetter() getter.get(cls, params) region = params.get('region') ec2 = region.connect() zone = params.get('zone') size = params.get('size') ebs_volume = ec2.create_volume(size, zone.name) v = cls() v.ec2 = ec2 v.volume_id = ebs_volume.id v.name = params.get('name') v.mount_point = params.get('mount_point') v.device = params.get('device') v.region_name = region.name v.zone_name = zone.name v.put() return v @classmethod def create_from_volume_id(cls, region_name, volume_id, name): vol = None ec2 = boto.ec2.connect_to_region(region_name) rs = ec2.get_all_volumes([volume_id]) if len(rs) == 1: v = rs[0] vol = cls() vol.volume_id = v.id vol.name = name vol.region_name = v.region.name vol.zone_name = v.zone vol.put() return vol def create_from_latest_snapshot(self, name, size=None): snapshot = self.get_snapshots()[-1] return self.create_from_snapshot(name, snapshot, size) def create_from_snapshot(self, name, snapshot, size=None): if size < self.size: size = self.size ec2 = self.get_ec2_connection() if self.zone_name is None or self.zone_name == '': # deal with the migration case where the zone is not set in the logical volume: current_volume = ec2.get_all_volumes([self.volume_id])[0] self.zone_name = current_volume.zone ebs_volume = ec2.create_volume(size, self.zone_name, snapshot) v = Volume() v.ec2 = self.ec2 v.volume_id = ebs_volume.id v.name = name v.mount_point = self.mount_point v.device = self.device v.region_name = self.region_name v.zone_name = self.zone_name v.put() return v def get_ec2_connection(self): if self.server: return self.server.ec2 if not hasattr(self, 'ec2') or self.ec2 is None: self.ec2 = boto.ec2.connect_to_region(self.region_name) return self.ec2 def _volume_state(self): ec2 = self.get_ec2_connection() rs = ec2.get_all_volumes([self.volume_id]) return rs[0].volume_state() def _attachment_state(self): ec2 = self.get_ec2_connection() rs = ec2.get_all_volumes([self.volume_id]) return rs[0].attachment_state() def _size(self): if not hasattr(self, '__size'): ec2 = self.get_ec2_connection() rs = ec2.get_all_volumes([self.volume_id]) self.__size = rs[0].size return self.__size def install_xfs(self): if self.server: self.server.install('xfsprogs xfsdump') def get_snapshots(self): """ Returns a list of all completed snapshots for this volume ID. """ ec2 = self.get_ec2_connection() rs = ec2.get_all_snapshots() all_vols = [self.volume_id] + self.past_volume_ids snaps = [] for snapshot in rs: if snapshot.volume_id in all_vols: if snapshot.progress == '100%': snapshot.date = boto.utils.parse_ts(snapshot.start_time) snapshot.keep = True snaps.append(snapshot) snaps.sort(cmp=lambda x, y: cmp(x.date, y.date)) return snaps def attach(self, server=None): if self.attachment_state == 'attached': print('already attached') return None if server: self.server = server self.put() ec2 = self.get_ec2_connection() ec2.attach_volume(self.volume_id, self.server.instance_id, self.device) def detach(self, force=False): state = self.attachment_state if state == 'available' or state is None or state == 'detaching': print('already detached') return None ec2 = self.get_ec2_connection() ec2.detach_volume(self.volume_id, self.server.instance_id, self.device, force) self.server = None self.put() def checkfs(self, use_cmd=None): if self.server is None: raise ValueError('server attribute must be set to run this command') # detemine state of file system on volume, only works if attached if use_cmd: cmd = use_cmd else: cmd = self.server.get_cmdshell() status = cmd.run('xfs_check %s' % self.device) if not use_cmd: cmd.close() if status[1].startswith('bad superblock magic number 0'): return False return True def wait(self): if self.server is None: raise ValueError('server attribute must be set to run this command') with closing(self.server.get_cmdshell()) as cmd: # wait for the volume device to appear cmd = self.server.get_cmdshell() while not cmd.exists(self.device): boto.log.info('%s still does not exist, waiting 10 seconds' % self.device) time.sleep(10) def format(self): if self.server is None: raise ValueError('server attribute must be set to run this command') status = None with closing(self.server.get_cmdshell()) as cmd: if not self.checkfs(cmd): boto.log.info('make_fs...') status = cmd.run('mkfs -t xfs %s' % self.device) return status def mount(self): if self.server is None: raise ValueError('server attribute must be set to run this command') boto.log.info('handle_mount_point') with closing(self.server.get_cmdshell()) as cmd: cmd = self.server.get_cmdshell() if not cmd.isdir(self.mount_point): boto.log.info('making directory') # mount directory doesn't exist so create it cmd.run("mkdir %s" % self.mount_point) else: boto.log.info('directory exists already') status = cmd.run('mount -l') lines = status[1].split('\n') for line in lines: t = line.split() if t and t[2] == self.mount_point: # something is already mounted at the mount point # unmount that and mount it as /tmp if t[0] != self.device: cmd.run('umount %s' % self.mount_point) cmd.run('mount %s /tmp' % t[0]) cmd.run('chmod 777 /tmp') break # Mount up our new EBS volume onto mount_point cmd.run("mount %s %s" % (self.device, self.mount_point)) cmd.run('xfs_growfs %s' % self.mount_point) def make_ready(self, server): self.server = server self.put() self.install_xfs() self.attach() self.wait() self.format() self.mount() def freeze(self): if self.server: return self.server.run("/usr/sbin/xfs_freeze -f %s" % self.mount_point) def unfreeze(self): if self.server: return self.server.run("/usr/sbin/xfs_freeze -u %s" % self.mount_point) def snapshot(self): # if this volume is attached to a server # we need to freeze the XFS file system try: self.freeze() if self.server is None: snapshot = self.get_ec2_connection().create_snapshot(self.volume_id) else: snapshot = self.server.ec2.create_snapshot(self.volume_id) boto.log.info('Snapshot of Volume %s created: %s' % (self.name, snapshot)) except Exception: boto.log.info('Snapshot error') boto.log.info(traceback.format_exc()) finally: status = self.unfreeze() return status def get_snapshot_range(self, snaps, start_date=None, end_date=None): l = [] for snap in snaps: if start_date and end_date: if snap.date >= start_date and snap.date <= end_date: l.append(snap) elif start_date: if snap.date >= start_date: l.append(snap) elif end_date: if snap.date <= end_date: l.append(snap) else: l.append(snap) return l def trim_snapshots(self, delete=False): """ Trim the number of snapshots for this volume. This method always keeps the oldest snapshot. It then uses the parameters passed in to determine how many others should be kept. The algorithm is to keep all snapshots from the current day. Then it will keep the first snapshot of the day for the previous seven days. Then, it will keep the first snapshot of the week for the previous four weeks. After than, it will keep the first snapshot of the month for as many months as there are. """ snaps = self.get_snapshots() # Always keep the oldest and the newest if len(snaps) <= 2: return snaps snaps = snaps[1:-1] now = datetime.datetime.now(snaps[0].date.tzinfo) midnight = datetime.datetime(year=now.year, month=now.month, day=now.day, tzinfo=now.tzinfo) # Keep the first snapshot from each day of the previous week one_week = datetime.timedelta(days=7, seconds=60*60) print(midnight-one_week, midnight) previous_week = self.get_snapshot_range(snaps, midnight-one_week, midnight) print(previous_week) if not previous_week: return snaps current_day = None for snap in previous_week: if current_day and current_day == snap.date.day: snap.keep = False else: current_day = snap.date.day # Get ourselves onto the next full week boundary if previous_week: week_boundary = previous_week[0].date if week_boundary.weekday() != 0: delta = datetime.timedelta(days=week_boundary.weekday()) week_boundary = week_boundary - delta # Keep one within this partial week partial_week = self.get_snapshot_range(snaps, week_boundary, previous_week[0].date) if len(partial_week) > 1: for snap in partial_week[1:]: snap.keep = False # Keep the first snapshot of each week for the previous 4 weeks for i in range(0, 4): weeks_worth = self.get_snapshot_range(snaps, week_boundary-one_week, week_boundary) if len(weeks_worth) > 1: for snap in weeks_worth[1:]: snap.keep = False week_boundary = week_boundary - one_week # Now look through all remaining snaps and keep one per month remainder = self.get_snapshot_range(snaps, end_date=week_boundary) current_month = None for snap in remainder: if current_month and current_month == snap.date.month: snap.keep = False else: current_month = snap.date.month if delete: for snap in snaps: if not snap.keep: boto.log.info('Deleting %s(%s) for %s' % (snap, snap.date, self.name)) snap.delete() return snaps def grow(self, size): pass def copy(self, snapshot): pass def get_snapshot_from_date(self, date): pass def delete(self, delete_ebs_volume=False): if delete_ebs_volume: self.detach() ec2 = self.get_ec2_connection() ec2.delete_volume(self.volume_id) super(Volume, self).delete() def archive(self): # snapshot volume, trim snaps, delete volume-id pass
mit
jordiclariana/ansible
lib/ansible/modules/cloud/openstack/os_stack.py
27
9090
#!/usr/bin/python #coding: utf-8 -*- # (c) 2016, Mathieu Bultel <[email protected]> # (c) 2016, Steve Baker <[email protected]> # # This module 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 software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this software. If not, see <http://www.gnu.org/licenses/>. from time import sleep from distutils.version import StrictVersion try: import shade HAS_SHADE = True except ImportError: HAS_SHADE = False ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: os_stack short_description: Add/Remove Heat Stack extends_documentation_fragment: openstack version_added: "2.2" author: "Mathieu Bultel (matbu), Steve Baker (steveb)" description: - Add or Remove a Stack to an OpenStack Heat options: state: description: - Indicate desired state of the resource choices: ['present', 'absent'] required: false default: present name: description: - Name of the stack that should be created, name could be char and digit, no space required: true template: description: - Path of the template file to use for the stack creation required: false default: None environment: description: - List of environment files that should be used for the stack creation required: false default: None parameters: description: - Dictionary of parameters for the stack creation required: false default: None rollback: description: - Rollback stack creation required: false default: false timeout: description: - Maximum number of seconds to wait for the stack creation required: false default: 3600 requirements: - "python >= 2.6" - "shade" ''' EXAMPLES = ''' --- - name: create stack ignore_errors: True register: stack_create os_stack: name: "{{ stack_name }}" state: present template: "/path/to/my_stack.yaml" environment: - /path/to/resource-registry.yaml - /path/to/environment.yaml parameters: bmc_flavor: m1.medium bmc_image: CentOS key_name: default private_net: {{ private_net_param }} node_count: 2 name: undercloud image: CentOS my_flavor: m1.large external_net: {{ external_net_param }} ''' RETURN = ''' id: description: Stack ID. type: string sample: "97a3f543-8136-4570-920e-fd7605c989d6" stack: action: description: Action, could be Create or Update. type: string sample: "CREATE" creation_time: description: Time when the action has been made. type: string sample: "2016-07-05T17:38:12Z" description: description: Description of the Stack provided in the heat template. type: string sample: "HOT template to create a new instance and networks" id: description: Stack ID. type: string sample: "97a3f543-8136-4570-920e-fd7605c989d6" name: description: Name of the Stack type: string sample: "test-stack" identifier: description: Identifier of the current Stack action. type: string sample: "test-stack/97a3f543-8136-4570-920e-fd7605c989d6" links: description: Links to the current Stack. type: list of dict sample: "[{'href': 'http://foo:8004/v1/7f6a/stacks/test-stack/97a3f543-8136-4570-920e-fd7605c989d6']" outputs: description: Output returned by the Stack. type: list of dict sample: "{'description': 'IP address of server1 in private network', 'output_key': 'server1_private_ip', 'output_value': '10.1.10.103'}" parameters: description: Parameters of the current Stack type: dict sample: "{'OS::project_id': '7f6a3a3e01164a4eb4eecb2ab7742101', 'OS::stack_id': '97a3f543-8136-4570-920e-fd7605c989d6', 'OS::stack_name': 'test-stack', 'stack_status': 'CREATE_COMPLETE', 'stack_status_reason': 'Stack CREATE completed successfully', 'status': 'COMPLETE', 'template_description': 'HOT template to create a new instance and networks', 'timeout_mins': 60, 'updated_time': null}" ''' def _create_stack(module, stack, cloud): try: stack = cloud.create_stack(module.params['name'], template_file=module.params['template'], environment_files=module.params['environment'], timeout=module.params['timeout'], wait=True, rollback=module.params['rollback'], **module.params['parameters']) stack = cloud.get_stack(stack.id, None) if stack.stack_status == 'CREATE_COMPLETE': return stack else: return False module.fail_json(msg = "Failure in creating stack: ".format(stack)) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e)) def _update_stack(module, stack, cloud): try: stack = cloud.update_stack( module.params['name'], template_file=module.params['template'], environment_files=module.params['environment'], timeout=module.params['timeout'], rollback=module.params['rollback'], wait=module.params['wait'], **module.params['parameters']) if stack['stack_status'] == 'UPDATE_COMPLETE': return stack else: module.fail_json(msg = "Failure in updating stack: %s" % stack['stack_status_reason']) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e)) def _system_state_change(module, stack, cloud): state = module.params['state'] if state == 'present': if not stack: return True if state == 'absent' and stack: return True return False def main(): argument_spec = openstack_full_argument_spec( name=dict(required=True), template=dict(default=None), environment=dict(default=None, type='list'), parameters=dict(default={}, type='dict'), rollback=dict(default=False, type='bool'), timeout=dict(default=3600, type='int'), state=dict(default='present', choices=['absent', 'present']), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule(argument_spec, supports_check_mode=True, **module_kwargs) # stack API introduced in 1.8.0 if not HAS_SHADE or (StrictVersion(shade.__version__) < StrictVersion('1.8.0')): module.fail_json(msg='shade 1.8.0 or higher is required for this module') state = module.params['state'] name = module.params['name'] # Check for required parameters when state == 'present' if state == 'present': for p in ['template']: if not module.params[p]: module.fail_json(msg='%s required with present state' % p) try: cloud = shade.openstack_cloud(**module.params) stack = cloud.get_stack(name) if module.check_mode: module.exit_json(changed=_system_state_change(module, stack, cloud)) if state == 'present': if not stack: stack = _create_stack(module, stack, cloud) else: stack = _update_stack(module, stack, cloud) changed = True module.exit_json(changed=changed, stack=stack, id=stack.id) elif state == 'absent': if not stack: changed = False else: changed = True if not cloud.delete_stack(name, wait=module.params['wait']): module.fail_json(msg='delete stack failed for stack: %s' % name) module.exit_json(changed=changed) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e)) from ansible.module_utils.basic import * from ansible.module_utils.openstack import * if __name__ == '__main__': main()
gpl-3.0
alexsavio/scikit-learn
sklearn/gaussian_process/gpr.py
13
18747
"""Gaussian processes regression. """ # Authors: Jan Hendrik Metzen <[email protected]> # # License: BSD 3 clause import warnings from operator import itemgetter import numpy as np from scipy.linalg import cholesky, cho_solve, solve_triangular from scipy.optimize import fmin_l_bfgs_b from sklearn.base import BaseEstimator, RegressorMixin, clone from sklearn.gaussian_process.kernels import RBF, ConstantKernel as C from sklearn.utils import check_random_state from sklearn.utils.validation import check_X_y, check_array class GaussianProcessRegressor(BaseEstimator, RegressorMixin): """Gaussian process regression (GPR). The implementation is based on Algorithm 2.1 of Gaussian Processes for Machine Learning (GPML) by Rasmussen and Williams. In addition to standard scikit-learn estimator API, GaussianProcessRegressor: * allows prediction without prior fitting (based on the GP prior) * provides an additional method sample_y(X), which evaluates samples drawn from the GPR (prior or posterior) at given inputs * exposes a method log_marginal_likelihood(theta), which can be used externally for other ways of selecting hyperparameters, e.g., via Markov chain Monte Carlo. Read more in the :ref:`User Guide <gaussian_process>`. .. versionadded:: 0.18 Parameters ---------- kernel : kernel object The kernel specifying the covariance function of the GP. If None is passed, the kernel "1.0 * RBF(1.0)" is used as default. Note that the kernel's hyperparameters are optimized during fitting. alpha : float or array-like, optional (default: 1e-10) Value added to the diagonal of the kernel matrix during fitting. Larger values correspond to increased noise level in the observations and reduce potential numerical issue during fitting. If an array is passed, it must have the same number of entries as the data used for fitting and is used as datapoint-dependent noise level. Note that this is equivalent to adding a WhiteKernel with c=alpha. Allowing to specify the noise level directly as a parameter is mainly for convenience and for consistency with Ridge. optimizer : string or callable, optional (default: "fmin_l_bfgs_b") Can either be one of the internally supported optimizers for optimizing the kernel's parameters, specified by a string, or an externally defined optimizer passed as a callable. If a callable is passed, it must have the signature:: def optimizer(obj_func, initial_theta, bounds): # * 'obj_func' is the objective function to be maximized, which # takes the hyperparameters theta as parameter and an # optional flag eval_gradient, which determines if the # gradient is returned additionally to the function value # * 'initial_theta': the initial value for theta, which can be # used by local optimizers # * 'bounds': the bounds on the values of theta .... # Returned are the best found hyperparameters theta and # the corresponding value of the target function. return theta_opt, func_min Per default, the 'fmin_l_bfgs_b' algorithm from scipy.optimize is used. If None is passed, the kernel's parameters are kept fixed. Available internal optimizers are:: 'fmin_l_bfgs_b' n_restarts_optimizer : int, optional (default: 0) The number of restarts of the optimizer for finding the kernel's parameters which maximize the log-marginal likelihood. The first run of the optimizer is performed from the kernel's initial parameters, the remaining ones (if any) from thetas sampled log-uniform randomly from the space of allowed theta-values. If greater than 0, all bounds must be finite. Note that n_restarts_optimizer == 0 implies that one run is performed. normalize_y : boolean, optional (default: False) Whether the target values y are normalized, i.e., the mean of the observed target values become zero. This parameter should be set to True if the target values' mean is expected to differ considerable from zero. When enabled, the normalization effectively modifies the GP's prior based on the data, which contradicts the likelihood principle; normalization is thus disabled per default. copy_X_train : bool, optional (default: True) If True, a persistent copy of the training data is stored in the object. Otherwise, just a reference to the training data is stored, which might cause predictions to change if the data is modified externally. random_state : integer or numpy.RandomState, optional The generator used to initialize the centers. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. Attributes ---------- X_train_ : array-like, shape = (n_samples, n_features) Feature values in training data (also required for prediction) y_train_ : array-like, shape = (n_samples, [n_output_dims]) Target values in training data (also required for prediction) kernel_ : kernel object The kernel used for prediction. The structure of the kernel is the same as the one passed as parameter but with optimized hyperparameters L_ : array-like, shape = (n_samples, n_samples) Lower-triangular Cholesky decomposition of the kernel in ``X_train_`` alpha_ : array-like, shape = (n_samples,) Dual coefficients of training data points in kernel space log_marginal_likelihood_value_ : float The log-marginal-likelihood of ``self.kernel_.theta`` """ def __init__(self, kernel=None, alpha=1e-10, optimizer="fmin_l_bfgs_b", n_restarts_optimizer=0, normalize_y=False, copy_X_train=True, random_state=None): self.kernel = kernel self.alpha = alpha self.optimizer = optimizer self.n_restarts_optimizer = n_restarts_optimizer self.normalize_y = normalize_y self.copy_X_train = copy_X_train self.random_state = random_state def fit(self, X, y): """Fit Gaussian process regression model Parameters ---------- X : array-like, shape = (n_samples, n_features) Training data y : array-like, shape = (n_samples, [n_output_dims]) Target values Returns ------- self : returns an instance of self. """ if self.kernel is None: # Use an RBF kernel as default self.kernel_ = C(1.0, constant_value_bounds="fixed") \ * RBF(1.0, length_scale_bounds="fixed") else: self.kernel_ = clone(self.kernel) self.rng = check_random_state(self.random_state) X, y = check_X_y(X, y, multi_output=True, y_numeric=True) # Normalize target value if self.normalize_y: self.y_train_mean = np.mean(y, axis=0) # demean y y = y - self.y_train_mean else: self.y_train_mean = np.zeros(1) if np.iterable(self.alpha) \ and self.alpha.shape[0] != y.shape[0]: if self.alpha.shape[0] == 1: self.alpha = self.alpha[0] else: raise ValueError("alpha must be a scalar or an array" " with same number of entries as y.(%d != %d)" % (self.alpha.shape[0], y.shape[0])) self.X_train_ = np.copy(X) if self.copy_X_train else X self.y_train_ = np.copy(y) if self.copy_X_train else y if self.optimizer is not None and self.kernel_.n_dims > 0: # Choose hyperparameters based on maximizing the log-marginal # likelihood (potentially starting from several initial values) def obj_func(theta, eval_gradient=True): if eval_gradient: lml, grad = self.log_marginal_likelihood( theta, eval_gradient=True) return -lml, -grad else: return -self.log_marginal_likelihood(theta) # First optimize starting from theta specified in kernel optima = [(self._constrained_optimization(obj_func, self.kernel_.theta, self.kernel_.bounds))] # Additional runs are performed from log-uniform chosen initial # theta if self.n_restarts_optimizer > 0: if not np.isfinite(self.kernel_.bounds).all(): raise ValueError( "Multiple optimizer restarts (n_restarts_optimizer>0) " "requires that all bounds are finite.") bounds = self.kernel_.bounds for iteration in range(self.n_restarts_optimizer): theta_initial = \ self.rng.uniform(bounds[:, 0], bounds[:, 1]) optima.append( self._constrained_optimization(obj_func, theta_initial, bounds)) # Select result from run with minimal (negative) log-marginal # likelihood lml_values = list(map(itemgetter(1), optima)) self.kernel_.theta = optima[np.argmin(lml_values)][0] self.log_marginal_likelihood_value_ = -np.min(lml_values) else: self.log_marginal_likelihood_value_ = \ self.log_marginal_likelihood(self.kernel_.theta) # Precompute quantities required for predictions which are independent # of actual query points K = self.kernel_(self.X_train_) K[np.diag_indices_from(K)] += self.alpha self.L_ = cholesky(K, lower=True) # Line 2 self.alpha_ = cho_solve((self.L_, True), self.y_train_) # Line 3 return self def predict(self, X, return_std=False, return_cov=False): """Predict using the Gaussian process regression model We can also predict based on an unfitted model by using the GP prior. In addition to the mean of the predictive distribution, also its standard deviation (return_std=True) or covariance (return_cov=True). Note that at most one of the two can be requested. Parameters ---------- X : array-like, shape = (n_samples, n_features) Query points where the GP is evaluated return_std : bool, default: False If True, the standard-deviation of the predictive distribution at the query points is returned along with the mean. return_cov : bool, default: False If True, the covariance of the joint predictive distribution at the query points is returned along with the mean Returns ------- y_mean : array, shape = (n_samples, [n_output_dims]) Mean of predictive distribution a query points y_std : array, shape = (n_samples,), optional Standard deviation of predictive distribution at query points. Only returned when return_std is True. y_cov : array, shape = (n_samples, n_samples), optional Covariance of joint predictive distribution a query points. Only returned when return_cov is True. """ if return_std and return_cov: raise RuntimeError( "Not returning standard deviation of predictions when " "returning full covariance.") X = check_array(X) if not hasattr(self, "X_train_"): # Unfitted;predict based on GP prior y_mean = np.zeros(X.shape[0]) if return_cov: y_cov = self.kernel(X) return y_mean, y_cov elif return_std: y_var = self.kernel.diag(X) return y_mean, np.sqrt(y_var) else: return y_mean else: # Predict based on GP posterior K_trans = self.kernel_(X, self.X_train_) y_mean = K_trans.dot(self.alpha_) # Line 4 (y_mean = f_star) y_mean = self.y_train_mean + y_mean # undo normal. if return_cov: v = cho_solve((self.L_, True), K_trans.T) # Line 5 y_cov = self.kernel_(X) - K_trans.dot(v) # Line 6 return y_mean, y_cov elif return_std: # compute inverse K_inv of K based on its Cholesky # decomposition L and its inverse L_inv L_inv = solve_triangular(self.L_.T, np.eye(self.L_.shape[0])) K_inv = L_inv.dot(L_inv.T) # Compute variance of predictive distribution y_var = self.kernel_.diag(X) y_var -= np.einsum("ki,kj,ij->k", K_trans, K_trans, K_inv) # Check if any of the variances is negative because of # numerical issues. If yes: set the variance to 0. y_var_negative = y_var < 0 if np.any(y_var_negative): warnings.warn("Predicted variances smaller than 0. " "Setting those variances to 0.") y_var[y_var_negative] = 0.0 return y_mean, np.sqrt(y_var) else: return y_mean def sample_y(self, X, n_samples=1, random_state=0): """Draw samples from Gaussian process and evaluate at X. Parameters ---------- X : array-like, shape = (n_samples_X, n_features) Query points where the GP samples are evaluated n_samples : int, default: 1 The number of samples drawn from the Gaussian process random_state: RandomState or an int seed (0 by default) A random number generator instance Returns ------- y_samples : array, shape = (n_samples_X, [n_output_dims], n_samples) Values of n_samples samples drawn from Gaussian process and evaluated at query points. """ rng = check_random_state(random_state) y_mean, y_cov = self.predict(X, return_cov=True) if y_mean.ndim == 1: y_samples = rng.multivariate_normal(y_mean, y_cov, n_samples).T else: y_samples = \ [rng.multivariate_normal(y_mean[:, i], y_cov, n_samples).T[:, np.newaxis] for i in range(y_mean.shape[1])] y_samples = np.hstack(y_samples) return y_samples def log_marginal_likelihood(self, theta=None, eval_gradient=False): """Returns log-marginal likelihood of theta for training data. Parameters ---------- theta : array-like, shape = (n_kernel_params,) or None Kernel hyperparameters for which the log-marginal likelihood is evaluated. If None, the precomputed log_marginal_likelihood of ``self.kernel_.theta`` is returned. eval_gradient : bool, default: False If True, the gradient of the log-marginal likelihood with respect to the kernel hyperparameters at position theta is returned additionally. If True, theta must not be None. Returns ------- log_likelihood : float Log-marginal likelihood of theta for training data. log_likelihood_gradient : array, shape = (n_kernel_params,), optional Gradient of the log-marginal likelihood with respect to the kernel hyperparameters at position theta. Only returned when eval_gradient is True. """ if theta is None: if eval_gradient: raise ValueError( "Gradient can only be evaluated for theta!=None") return self.log_marginal_likelihood_value_ kernel = self.kernel_.clone_with_theta(theta) if eval_gradient: K, K_gradient = kernel(self.X_train_, eval_gradient=True) else: K = kernel(self.X_train_) K[np.diag_indices_from(K)] += self.alpha try: L = cholesky(K, lower=True) # Line 2 except np.linalg.LinAlgError: return (-np.inf, np.zeros_like(theta)) \ if eval_gradient else -np.inf # Support multi-dimensional output of self.y_train_ y_train = self.y_train_ if y_train.ndim == 1: y_train = y_train[:, np.newaxis] alpha = cho_solve((L, True), y_train) # Line 3 # Compute log-likelihood (compare line 7) log_likelihood_dims = -0.5 * np.einsum("ik,ik->k", y_train, alpha) log_likelihood_dims -= np.log(np.diag(L)).sum() log_likelihood_dims -= K.shape[0] / 2 * np.log(2 * np.pi) log_likelihood = log_likelihood_dims.sum(-1) # sum over dimensions if eval_gradient: # compare Equation 5.9 from GPML tmp = np.einsum("ik,jk->ijk", alpha, alpha) # k: output-dimension tmp -= cho_solve((L, True), np.eye(K.shape[0]))[:, :, np.newaxis] # Compute "0.5 * trace(tmp.dot(K_gradient))" without # constructing the full matrix tmp.dot(K_gradient) since only # its diagonal is required log_likelihood_gradient_dims = \ 0.5 * np.einsum("ijl,ijk->kl", tmp, K_gradient) log_likelihood_gradient = log_likelihood_gradient_dims.sum(-1) if eval_gradient: return log_likelihood, log_likelihood_gradient else: return log_likelihood def _constrained_optimization(self, obj_func, initial_theta, bounds): if self.optimizer == "fmin_l_bfgs_b": theta_opt, func_min, convergence_dict = \ fmin_l_bfgs_b(obj_func, initial_theta, bounds=bounds) if convergence_dict["warnflag"] != 0: warnings.warn("fmin_l_bfgs_b terminated abnormally with the " " state: %s" % convergence_dict) elif callable(self.optimizer): theta_opt, func_min = \ self.optimizer(obj_func, initial_theta, bounds=bounds) else: raise ValueError("Unknown optimizer %s." % self.optimizer) return theta_opt, func_min
bsd-3-clause
jaysonsantos/python-binary-memcached
test/test_auth.py
1
2626
import os import unittest import six import bmemcached from bmemcached.exceptions import AuthenticationNotSupported, InvalidCredentials, MemcachedException if six.PY3: from unittest import mock else: import mock class TestServerAuth(unittest.TestCase): @mock.patch.object(bmemcached.protocol.Protocol, '_get_response') def testServerDoesntNeedAuth(self, mocked_response): """ If 0x81 ('unkown_command') comes back in the status field when authenticating, it isn't needed. """ mocked_response.return_value = (0, 0, 0, 0, 0, 0x81, 0, 0, 0, 0) server = bmemcached.protocol.Protocol(os.environ['MEMCACHED_HOST']) # can pass anything and it'll work self.assertTrue(server.authenticate('user', 'badpassword')) @mock.patch.object(bmemcached.protocol.Protocol, '_get_response') def testNotUsingPlainAuth(self, mocked_response): """ Raise AuthenticationNotSupported unless we're using PLAIN auth. """ mocked_response.return_value = (0, 0, 0, 0, 0, 0, 0, 0, 0, []) server = bmemcached.protocol.Protocol(os.environ['MEMCACHED_HOST']) self.assertRaises(AuthenticationNotSupported, server.authenticate, 'user', 'password') @mock.patch.object(bmemcached.protocol.Protocol, '_get_response') def testAuthNotSuccessful(self, mocked_response): """ Raise MemcachedException for anything unsuccessful. """ mocked_response.return_value = (0, 0, 0, 0, 0, 0x01, 0, 0, 0, [b'PLAIN']) server = bmemcached.protocol.Protocol(os.environ['MEMCACHED_HOST']) self.assertRaises(MemcachedException, server.authenticate, 'user', 'password') @mock.patch.object(bmemcached.protocol.Protocol, '_get_response') def testAuthSuccessful(self, mocked_response): """ Valid logins return True. """ mocked_response.return_value = (0, 0, 0, 0, 0, 0, 0, 0, 0, [b'PLAIN']) server = bmemcached.protocol.Protocol(os.environ['MEMCACHED_HOST']) self.assertTrue(server.authenticate('user', 'password')) @mock.patch.object(bmemcached.protocol.Protocol, '_get_response') def testAuthUnsuccessful(self, mocked_response): """ Invalid logins raise InvalidCredentials """ mocked_response.return_value = (0, 0, 0, 0, 0, 0x08, 0, 0, 0, [b'PLAIN']) server = bmemcached.protocol.Protocol(os.environ['MEMCACHED_HOST']) self.assertRaises(InvalidCredentials, server.authenticate, 'user', 'password2')
mit
sovietspy2/uzletiProject
python/Lib/encodings/charmap.py
103
2153
""" Generic Python Character Mapping Codec. Use this codec directly rather than through the automatic conversion mechanisms supplied by unicode() and .encode(). Written by Marc-Andre Lemburg ([email protected]). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """#" import codecs ### Codec APIs class Codec(codecs.Codec): # Note: Binding these as C functions will result in the class not # converting them to methods. This is intended. encode = codecs.charmap_encode decode = codecs.charmap_decode class IncrementalEncoder(codecs.IncrementalEncoder): def __init__(self, errors='strict', mapping=None): codecs.IncrementalEncoder.__init__(self, errors) self.mapping = mapping def encode(self, input, final=False): return codecs.charmap_encode(input, self.errors, self.mapping)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def __init__(self, errors='strict', mapping=None): codecs.IncrementalDecoder.__init__(self, errors) self.mapping = mapping def decode(self, input, final=False): return codecs.charmap_decode(input, self.errors, self.mapping)[0] class StreamWriter(Codec,codecs.StreamWriter): def __init__(self,stream,errors='strict',mapping=None): codecs.StreamWriter.__init__(self,stream,errors) self.mapping = mapping def encode(self,input,errors='strict'): return Codec.encode(input,errors,self.mapping) class StreamReader(Codec,codecs.StreamReader): def __init__(self,stream,errors='strict',mapping=None): codecs.StreamReader.__init__(self,stream,errors) self.mapping = mapping def decode(self,input,errors='strict'): return Codec.decode(input,errors,self.mapping) ### encodings module API def getregentry(): return codecs.CodecInfo( name='charmap', encode=Codec.encode, decode=Codec.decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamwriter=StreamWriter, streamreader=StreamReader, )
gpl-3.0
samueldotj/TeeRISC-Simulator
tests/configs/realview-simple-timing.py
6
2284
# Copyright (c) 2012 ARM Limited # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality of the software # licensed hereunder. You may use the software subject to the license # terms below provided that you ensure that this notice is replicated # unmodified and in its entirety in all distributions of the software, # modified or unmodified, in source code or in binary form. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Andreas Sandberg from m5.objects import * from arm_generic import * root = LinuxArmFSSystemUniprocessor(mem_mode='timing', cpu_class=TimingSimpleCPU).create_root()
bsd-3-clause
pmeier82/spike_gnode
demo/forms.py
1
1639
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.forms.formsets import BaseFormSet, formset_factory from bootstrap3.tests import TestForm RADIO_CHOICES = ( ('1', 'Radio 1'), ('2', 'Radio 2'), ) MEDIA_CHOICES = ( ('Audio', ( ('vinyl', 'Vinyl'), ('cd', 'CD'), ) ), ('Video', ( ('vhs', 'VHS Tape'), ('dvd', 'DVD'), ) ), ('unknown', 'Unknown'), ) class ContactForm(TestForm): pass class ContactBaseFormSet(BaseFormSet): def add_fields(self, form, index): super(ContactBaseFormSet, self).add_fields(form, index) def clean(self): super(ContactBaseFormSet, self).clean() raise forms.ValidationError("This error was added to show the non form errors styling") ContactFormSet = formset_factory(TestForm, formset=ContactBaseFormSet, extra=2, max_num=4, validate_max=True) class FilesForm(forms.Form): text1 = forms.CharField() file1 = forms.FileField() file2 = forms.FileField(required=False) file3 = forms.FileField(widget=forms.ClearableFileInput) file4 = forms.FileField(required=False, widget=forms.ClearableFileInput) class ArticleForm(forms.Form): title = forms.CharField() pub_date = forms.DateField() def clean(self): cleaned_data = super(ArticleForm, self).clean() raise forms.ValidationError("This error was added to show the non field errors styling.") return cleaned_data if __name__ == "__main__": pass
bsd-3-clause
Lanozavr/pvs
python/src/ui/mmgr.py
4
9888
# This class manages all the menu items in the main menu of the editor import wx from constants import * from evhdlr import * import util import logging from preference import Preferences from wx.lib.pubsub import setupkwargs, pub import pvscomm class MainFrameMenu(wx.MenuBar): """The class implementing and managing the main menu bar in the application""" def __init__(self): wx.MenuBar.__init__(self) self.plugins = {} self.toolbars = {} self._recentContexts = {} self._recentFiles = {} self.addFileMenu() self.addEditMenu() self.addViewMenu() self.addPVSMenu() self.addHelpMenu() self.setBindings() pub.subscribe(self.update, PUB_UPDATEMENUBAR) pub.subscribe(self.showPlugin, PUB_SHOWPLUGIN) pub.subscribe(self.addPluginToViewMenu, PUB_ADDITEMTOVIEWMENU) pub.subscribe(self.prepareRecentContextsSubMenu, PUB_UPDATEPVSCONTEXT) pub.subscribe(self.prepareRecentFilesSubMenu, PUB_PREPARERECENTFILESMENU) def addFileMenu(self): """Adding menu items to File menu""" fileMenu = wx.Menu() self.newFileMenuItem = fileMenu.Append(wx.ID_NEW, self._makeLabel(LABEL_NEW, "N", True), EMPTY_STRING, wx.ITEM_NORMAL) self.openFileMenuItem = fileMenu.Append(wx.ID_OPEN, self._makeLabel(LABEL_OPEN, "O", True), EMPTY_STRING, wx.ITEM_NORMAL) self.recentFilesMenu = wx.Menu() self.prepareRecentFilesSubMenu() fileMenu.AppendMenu(wx.ID_ANY, "Recent Files", self.recentFilesMenu) self.saveFileMenuItem = fileMenu.Append(wx.ID_SAVE, self._makeLabel(LABEL_SAVE, "S"), EMPTY_STRING, wx.ITEM_NORMAL) self.saveFileAsMenuItem = fileMenu.Append(wx.ID_SAVEAS, self._makeLabel(LABEL_SAVEAS, None, True), EMPTY_STRING, wx.ITEM_NORMAL) self.closeFileMenuItem = fileMenu.Append(wx.ID_CLOSE, self._makeLabel(LABEL_CLOSEFILE, "W"), EMPTY_STRING, wx.ITEM_NORMAL) fileMenu.AppendSeparator() self.quitMenuItem = fileMenu.Append(wx.ID_ANY, self._makeLabel(LABEL_QUIT, "Q"), EMPTY_STRING, wx.ITEM_NORMAL) self.Append(fileMenu, LABEL_FILE) def addEditMenu(self): """Adding menu items to Edit menu""" editMenu = wx.Menu() self.undoMenuItem = editMenu.Append(wx.ID_UNDO, self._makeLabel(LABEL_UNDO, "U"), EMPTY_STRING, wx.ITEM_NORMAL) self.redoMenuItem = editMenu.Append(wx.ID_UNDO, self._makeLabel(LABEL_REDO, SHIFT + "-Z"), EMPTY_STRING, wx.ITEM_NORMAL) editMenu.AppendSeparator() self.cutMenuItem = editMenu.Append(wx.ID_CUT, self._makeLabel(LABEL_CUT, "X"), EMPTY_STRING, wx.ITEM_NORMAL) self.copyMenuItem = editMenu.Append(wx.ID_COPY, self._makeLabel(LABEL_COPY, "C"), EMPTY_STRING, wx.ITEM_NORMAL) self.pasteMenuItem = editMenu.Append(wx.ID_PASTE, self._makeLabel(LABEL_PASTE, "V"), EMPTY_STRING, wx.ITEM_NORMAL) self.selectAllMenuItem = editMenu.Append(wx.ID_SELECTALL, self._makeLabel(LABEL_SELECTALL, "A"), EMPTY_STRING, wx.ITEM_NORMAL) editMenu.AppendSeparator() self.findMenuItem = editMenu.Append(wx.ID_FIND, self._makeLabel(LABEL_FIND, "F"), EMPTY_STRING, wx.ITEM_NORMAL) self.Append(editMenu, LABEL_EDIT) def addViewMenu(self): """Adding menu items to View menu""" self.viewMenu = wx.Menu() self.pluginMenu = wx.Menu() self.viewMenu.AppendMenu(wx.ID_ANY, 'Plugins', self.pluginMenu) # Add View Menu to the menu bar: self.Append(self.viewMenu, LABEL_VIEW) def addPVSMenu(self): """Adding menu items to PVS menu""" pvsMenu = wx.Menu() self.changeContextMenuItem = pvsMenu.Append(wx.ID_ANY, self._makeLabel("Change Context", None, True), EMPTY_STRING, wx.ITEM_NORMAL) self.recentContextsMenu = wx.Menu() self.prepareRecentContextsSubMenu() pvsMenu.AppendMenu(wx.ID_ANY, "Recent Contexts", self.recentContextsMenu) self.pvsResetMenuItem = pvsMenu.Append(wx.ID_ANY, "Reset PVS", EMPTY_STRING, wx.ITEM_NORMAL) pvsMenu.AppendSeparator() self.typecheckMenuItem = pvsMenu.Append(wx.ID_ANY, LABEL_TYPECHECK, EMPTY_STRING, wx.ITEM_NORMAL) self.pvsDialogMenuItem = pvsMenu.Append(wx.ID_ANY, "PVS Log...", EMPTY_STRING, wx.ITEM_NORMAL) self.Append(pvsMenu, PVS_U) def addHelpMenu(self): """Adding menu items to Help menu""" helpMenu = wx.Menu() self.helpMenuItem = helpMenu.Append(wx.ID_ANY, self._makeLabel("PVS GUI Help", None, True), EMPTY_STRING, wx.ITEM_NORMAL) self.Append(helpMenu, "Help") def prepareRecentFilesSubMenu(self): try: while True: #TODO: Find out if there is a better way to remove all the items from a menu item = self.recentFilesMenu.FindItemByPosition(0) self.recentFilesMenu.RemoveItem(item) except: pass self._recentFiles = {} preferences = Preferences() recentFiles = preferences.getRecentFiles() logging.debug("Recent Files: %s", recentFiles) frame = util.getMainFrame() for fullname in recentFiles: item = self.recentFilesMenu.Append(wx.ID_ANY, fullname, EMPTY_STRING, wx.ITEM_NORMAL) self._recentFiles[item.GetId()] = fullname frame.Bind(wx.EVT_MENU, self.onRecentFileSelected, item) def prepareRecentContextsSubMenu(self): try: while True: #TODO: Find out if there is a better way to remove all the items from a menu item = self.recentContextsMenu.FindItemByPosition(0) self.recentContextsMenu.RemoveItem(item) except: pass self._recentContexts = {} preferences = Preferences() recentContexts = preferences.getRecentContexts() logging.debug("Recent Contexts: %s", recentContexts) frame = util.getMainFrame() for cxt in recentContexts: item = self.recentContextsMenu.Append(wx.ID_ANY, cxt, EMPTY_STRING, wx.ITEM_NORMAL) self._recentContexts[item.GetId()] = cxt frame.Bind(wx.EVT_MENU, self.onRecentContextSelected, item) def onRecentContextSelected(self, event): context = self._recentContexts[event.GetId()] pvscomm.PVSCommandManager().changeContext(context) def onRecentFileSelected(self, event): fullname = self._recentFiles[event.GetId()] pub.sendMessage(PUB_ADDFILE, fullname=fullname) Preferences().removeFromRecentFiles(fullname) self.prepareRecentFilesSubMenu() def addPluginToViewMenu(self, name, callBackFunction): logging.debug("Name: %s", name) frame = util.getMainFrame() item = self.pluginMenu.Append(wx.ID_ANY, name, EMPTY_STRING, wx.ITEM_CHECK) self.plugins[name] = item self.pluginMenu.Check(item.GetId(), PluginManager().shouldPluginBeVisible(name, pvscomm.PVSCommandManager().pvsMode)) frame.Bind(wx.EVT_MENU, callBackFunction, item) def _makeLabel(self, name, shortcut=None, addDots = False): if addDots: name = name + DOTDOTDOT return name if shortcut is None else "%s\t%s-%s"%(name, CONTROL, shortcut) def setBindings(self): frame = util.getMainFrame() frame.Bind(wx.EVT_MENU, onCreateNewFile, self.newFileMenuItem) frame.Bind(wx.EVT_MENU, onOpenFile, self.openFileMenuItem) frame.Bind(wx.EVT_MENU, onSaveFile, self.saveFileMenuItem) frame.Bind(wx.EVT_MENU, onSaveAsFile, self.saveFileAsMenuItem) frame.Bind(wx.EVT_MENU, onCloseFile, self.closeFileMenuItem) frame.Bind(wx.EVT_MENU, onQuitFrame, self.quitMenuItem) frame.Bind(wx.EVT_MENU, onUndo, self.undoMenuItem) frame.Bind(wx.EVT_MENU, onRedo, self.redoMenuItem) frame.Bind(wx.EVT_MENU, onSelectAll, self.selectAllMenuItem) frame.Bind(wx.EVT_MENU, onCutText, self.cutMenuItem) frame.Bind(wx.EVT_MENU, onCopyText, self.copyMenuItem) frame.Bind(wx.EVT_MENU, onPasteText, self.pasteMenuItem) frame.Bind(wx.EVT_MENU, onFindText, self.findMenuItem) frame.Bind(wx.EVT_MENU, onChangeContext, self.changeContextMenuItem) frame.Bind(wx.EVT_MENU, onTypecheck, self.typecheckMenuItem) frame.Bind(wx.EVT_MENU, onResetPVS, self.pvsResetMenuItem) frame.Bind(wx.EVT_MENU, onShowPVSCommunicationLog, self.pvsDialogMenuItem) frame.Bind(wx.EVT_MENU, onShowHelpFrame, self.helpMenuItem) def update(self, parameters): if OPENFILES in parameters: value = parameters[OPENFILES] > 0 self.closeFileMenuItem.Enable(value) self.cutMenuItem.Enable(value) self.copyMenuItem.Enable(value) self.pasteMenuItem.Enable(value) self.selectAllMenuItem.Enable(value) self.findMenuItem.Enable(value) self.undoMenuItem.Enable(value) self.redoMenuItem.Enable(value) if PVSMODE in parameters: pvsMode = parameters[PVSMODE] if pvsMode == PVS_MODE_OFF: pass elif pvsMode == PVS_MODE_LISP: pass elif pvsMode == PVS_MODE_PROVER: pass elif pvsMode == PVS_MODE_UNKNOWN: pass else: logging.error("pvsMode %s is not recognized", pvsMode) def showPlugin(self, name, value): if name in self.plugins: logging.info("Changing the visibility of %s to %s", name, value) item = self.plugins[name] item.Check(value) else: logging.warn("No menu option for plugin %s", name)
gpl-2.0
andytimes/kernel-msm8660
tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/Util.py
12527
1935
# Util.py - Python extension for perf script, miscellaneous utility code # # Copyright (C) 2010 by Tom Zanussi <[email protected]> # # This software may be distributed under the terms of the GNU General # Public License ("GPL") version 2 as published by the Free Software # Foundation. import errno, os FUTEX_WAIT = 0 FUTEX_WAKE = 1 FUTEX_PRIVATE_FLAG = 128 FUTEX_CLOCK_REALTIME = 256 FUTEX_CMD_MASK = ~(FUTEX_PRIVATE_FLAG | FUTEX_CLOCK_REALTIME) NSECS_PER_SEC = 1000000000 def avg(total, n): return total / n def nsecs(secs, nsecs): return secs * NSECS_PER_SEC + nsecs def nsecs_secs(nsecs): return nsecs / NSECS_PER_SEC def nsecs_nsecs(nsecs): return nsecs % NSECS_PER_SEC def nsecs_str(nsecs): str = "%5u.%09u" % (nsecs_secs(nsecs), nsecs_nsecs(nsecs)), return str def add_stats(dict, key, value): if not dict.has_key(key): dict[key] = (value, value, value, 1) else: min, max, avg, count = dict[key] if value < min: min = value if value > max: max = value avg = (avg + value) / 2 dict[key] = (min, max, avg, count + 1) def clear_term(): print("\x1b[H\x1b[2J") audit_package_warned = False try: import audit machine_to_id = { 'x86_64': audit.MACH_86_64, 'alpha' : audit.MACH_ALPHA, 'ia64' : audit.MACH_IA64, 'ppc' : audit.MACH_PPC, 'ppc64' : audit.MACH_PPC64, 's390' : audit.MACH_S390, 's390x' : audit.MACH_S390X, 'i386' : audit.MACH_X86, 'i586' : audit.MACH_X86, 'i686' : audit.MACH_X86, } try: machine_to_id['armeb'] = audit.MACH_ARMEB except: pass machine_id = machine_to_id[os.uname()[4]] except: if not audit_package_warned: audit_package_warned = True print "Install the audit-libs-python package to get syscall names" def syscall_name(id): try: return audit.audit_syscall_to_name(id, machine_id) except: return str(id) def strerror(nr): try: return errno.errorcode[abs(nr)] except: return "Unknown %d errno" % nr
gpl-2.0
Vishluck/sympy
sympy/physics/quantum/matrixcache.py
124
3519
"""A cache for storing small matrices in multiple formats.""" from __future__ import print_function, division from sympy import Matrix, I, Pow, Rational, exp, pi from sympy.physics.quantum.matrixutils import ( to_sympy, to_numpy, to_scipy_sparse ) class MatrixCache(object): """A cache for small matrices in different formats. This class takes small matrices in the standard ``sympy.Matrix`` format, and then converts these to both ``numpy.matrix`` and ``scipy.sparse.csr_matrix`` matrices. These matrices are then stored for future recovery. """ def __init__(self, dtype='complex'): self._cache = {} self.dtype = dtype def cache_matrix(self, name, m): """Cache a matrix by its name. Parameters ---------- name : str A descriptive name for the matrix, like "identity2". m : list of lists The raw matrix data as a sympy Matrix. """ try: self._sympy_matrix(name, m) except ImportError: pass try: self._numpy_matrix(name, m) except ImportError: pass try: self._scipy_sparse_matrix(name, m) except ImportError: pass def get_matrix(self, name, format): """Get a cached matrix by name and format. Parameters ---------- name : str A descriptive name for the matrix, like "identity2". format : str The format desired ('sympy', 'numpy', 'scipy.sparse') """ m = self._cache.get((name, format)) if m is not None: return m raise NotImplementedError( 'Matrix with name %s and format %s is not available.' % (name, format) ) def _store_matrix(self, name, format, m): self._cache[(name, format)] = m def _sympy_matrix(self, name, m): self._store_matrix(name, 'sympy', to_sympy(m)) def _numpy_matrix(self, name, m): m = to_numpy(m, dtype=self.dtype) self._store_matrix(name, 'numpy', m) def _scipy_sparse_matrix(self, name, m): # TODO: explore different sparse formats. But sparse.kron will use # coo in most cases, so we use that here. m = to_scipy_sparse(m, dtype=self.dtype) self._store_matrix(name, 'scipy.sparse', m) sqrt2_inv = Pow(2, Rational(-1, 2), evaluate=False) # Save the common matrices that we will need matrix_cache = MatrixCache() matrix_cache.cache_matrix('eye2', Matrix([[1, 0], [0, 1]])) matrix_cache.cache_matrix('op11', Matrix([[0, 0], [0, 1]])) # |1><1| matrix_cache.cache_matrix('op00', Matrix([[1, 0], [0, 0]])) # |0><0| matrix_cache.cache_matrix('op10', Matrix([[0, 0], [1, 0]])) # |1><0| matrix_cache.cache_matrix('op01', Matrix([[0, 1], [0, 0]])) # |0><1| matrix_cache.cache_matrix('X', Matrix([[0, 1], [1, 0]])) matrix_cache.cache_matrix('Y', Matrix([[0, -I], [I, 0]])) matrix_cache.cache_matrix('Z', Matrix([[1, 0], [0, -1]])) matrix_cache.cache_matrix('S', Matrix([[1, 0], [0, I]])) matrix_cache.cache_matrix('T', Matrix([[1, 0], [0, exp(I*pi/4)]])) matrix_cache.cache_matrix('H', sqrt2_inv*Matrix([[1, 1], [1, -1]])) matrix_cache.cache_matrix('Hsqrt2', Matrix([[1, 1], [1, -1]])) matrix_cache.cache_matrix( 'SWAP', Matrix([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])) matrix_cache.cache_matrix('ZX', sqrt2_inv*Matrix([[1, 1], [1, -1]])) matrix_cache.cache_matrix('ZY', Matrix([[I, 0], [0, -I]]))
bsd-3-clause